From d385b4b813b7255dbd2a2323cb7768a4ab3a76b0 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Thu, 16 Jan 2025 09:18:46 +0100 Subject: [PATCH 1/5] [src] Run 'make format-csproj'. This runs 'dotnet format' on the generated project files, which will format code inside #if blocks (which 'dotnet format --folder ...' doesn't). This is a code formatting update only, no functional changes. --- .../AVAssetDownloadStorageManagementPolicy.cs | 2 +- src/AVFoundation/AVCaptureMetadataOutput.cs | 4 +- .../AVMetadataMachineReadableCodeObject.cs | 4 +- src/AVFoundation/AVOutputSettingsAssistant.cs | 6 +- src/AVRouting/AVCustomDeviceRoute.cs | 2 +- src/Accessibility/AXSettings.cs | 2 +- src/AddressBook/ABAddressBook.cs | 2 +- src/AppKit/Functions.cs | 4 +- src/AppKit/NSGraphics.cs | 4 +- src/AppKit/NSPasteboardReading.cs | 2 +- src/AudioToolbox/AudioConverter.cs | 4 +- src/AudioToolbox/AudioFile.cs | 2 +- src/AudioToolbox/AudioFileStream.cs | 2 +- src/AudioToolbox/AudioQueue.cs | 10 +- src/AudioToolbox/MusicTrack.cs | 2 +- src/AudioToolbox/SystemSound.cs | 2 +- src/AudioUnit/AUEnums.cs | 60 +- src/AudioUnit/AUGraph.cs | 8 +- src/AudioUnit/AudioComponent.cs | 21 +- src/AudioUnit/AudioComponentDescription.cs | 38 +- src/AudioUnit/AudioUnit.cs | 9 +- src/AudioUnit/AudioUnitUtils.cs | 8 +- src/AudioUnit/ExtAudioFile.cs | 8 +- src/BrowserEngineKit/BEStructs.cs | 19 +- src/Compression/CompressionStreamStruct.cs | 8 +- src/Compression/TaskToApm.cs | 180 +- src/CoreAnimation/CATextLayer.cs | 2 +- src/CoreAnimation/CATransform3D.cs | 8 +- src/CoreBluetooth/CBPeer.cs | 2 +- src/CoreFoundation/CFMessagePort.cs | 12 +- src/CoreFoundation/CFProxySupport.cs | 52 +- src/CoreGraphics/CGAffineTransform.cs | 22 +- src/CoreGraphics/CGColorSpace.cs | 2 +- src/CoreGraphics/CGDisplay.cs | 45 +- src/CoreGraphics/CGEvent.cs | 58 +- src/CoreGraphics/CGEventSource.cs | 22 +- src/CoreGraphics/CGEventTypes.cs | 50 +- src/CoreGraphics/CGImage.cs | 22 +- src/CoreGraphics/CGPattern.cs | 3 +- src/CoreGraphics/CGVector.cs | 4 +- src/CoreImage/Enums.cs | 2 +- src/CoreLocation/CLLocationManager.cs | 2 +- src/CoreMedia/CMSampleBuffer.cs | 6 +- src/CoreMidi/MidiBluetoothDriver.cs | 8 +- src/CoreServices/FSEvents.cs | 34 +- src/CoreServices/LaunchServices.cs | 41 +- src/CoreSpotlight/CSSearchableIndex.cs | 2 +- .../CSSearchableItemAttributeSet.cs | 13 +- src/CoreText/CTFontCollection.cs | 2 +- src/CoreText/CTFontManager.cs | 8 +- src/CoreVideo/CVBuffer.cs | 4 +- src/CoreVideo/CVDisplayLink.cs | 56 +- src/CoreVideo/CVImageBuffer.cs | 2 +- src/CoreVideo/CVPixelFormatDescription.cs | 2 +- src/Darwin/KernelNotification.cs | 146 +- src/Darwin/SystemLog.cs | 60 +- src/FileProvider/Structs.cs | 5 +- src/Foundation/Enum.cs | 4 +- src/Foundation/NSAppleEventDescriptor.cs | 6 +- src/Foundation/NSArray.cs | 2 +- src/Foundation/NSAttributedString.cs | 10 +- src/Foundation/NSAttributedString.mac.cs | 10 +- src/Foundation/NSConnection.cs | 8 +- src/Foundation/NSHost.cs | 8 +- src/Foundation/NSIndexSet.cs | 38 +- src/Foundation/NSNumber.mac.cs | 28 +- src/Foundation/NSObject.mac.cs | 2 +- src/Foundation/NSObject2.cs | 14 +- src/Foundation/NSPropertyListSerialization.cs | 6 +- .../NSScriptCommandArgumentDescription.cs | 8 +- src/Foundation/NSScriptCommandDescription.cs | 16 +- .../NSScriptCommandDescriptionDictionary.cs | 20 +- src/Foundation/NSSecureCoding.cs | 3 +- src/Foundation/NSString.cs | 6 +- src/Foundation/NSThread.mac.cs | 13 +- src/Foundation/NSUrlDownload.cs | 2 +- src/Foundation/NSUrlSessionHandler.cs | 17 +- src/GameKit/GKCompat.cs | 5 +- src/ImageIO/CGImageAnimation.cs | 40 +- src/Intents/INBillTypeResolutionResult.cs | 4 +- .../INCallRecordTypeResolutionResult.cs | 4 +- .../INCarSignalOptionsResolutionResult.cs | 4 +- ...MessageAttributeOptionsResolutionResult.cs | 4 +- .../INMessageAttributeResolutionResult.cs | 4 +- .../INPaymentStatusResolutionResult.cs | 4 +- .../INSetClimateSettingsInCarIntent.cs | 2 +- src/Intents/INSpeakableString.cs | 2 +- .../INWorkoutGoalUnitTypeResolutionResult.cs | 4 +- .../INWorkoutLocationTypeResolutionResult.cs | 4 +- src/MapKit/MapKit.cs | 2 +- src/MediaExtension/MEByteSource.cs | 8 +- .../MERawProcessingListParameter.cs | 2 +- src/MediaExtension/MESampleCursor.cs | 2 +- src/MediaToolbox/MTAudioProcessingTap.cs | 64 +- src/Metal/Defs.cs | 3 +- src/Metal/MTLArgumentEncoder.cs | 4 +- src/Metal/MTLArrays.cs | 3 +- src/Metal/MTLComputeCommandEncoder.cs | 4 +- .../MTLRasterizationRateLayerDescriptor.cs | 17 +- src/Metal/MTLResourceStateCommandEncoder.cs | 10 +- .../MPSGraphExecutable.cs | 8 +- src/MetricKit/MXMetaData.cs | 2 +- src/MetricKit/MXMetric.cs | 2 +- src/MetricKit/MXMetricPayload.cs | 2 +- ...IAlgorithmConvergenceStatusReasonValues.cs | 3 +- src/NearbyInteraction/NINearbyObject.cs | 15 +- src/Network/NWConnection.cs | 2 +- src/Network/NWConnectionGroup.cs | 2 +- src/Network/NWEndpoint.cs | 2 +- src/Network/NWEstablishmentReport.cs | 2 +- src/Network/NWEthernetChannel.cs | 22 +- src/Network/NWInterface.cs | 2 +- src/Network/NWParameters.cs | 4 +- src/Network/NWPath.cs | 2 +- src/Network/NWPrivacyContext.cs | 2 +- src/Network/NWProtocolDefinition.cs | 2 +- src/Network/NWProtocolFramerOptions.cs | 2 +- src/Network/NWProtocolMetadata.cs | 2 +- src/Network/NWProtocolOptions.cs | 2 +- src/Network/NWProtocolStack.cs | 2 +- src/Network/NWProxyConfig.cs | 2 +- src/Network/NWRelayHop.cs | 2 +- src/Network/NWResolverConfig.cs | 2 +- src/ObjCRuntime/BackingField.cs | 3 +- src/ObjCRuntime/BindAs.cs | 12 +- src/ObjCRuntime/Blocks.cs | 12 +- src/ObjCRuntime/Class.cs | 2 +- .../DelayedRegistrationAttribute.cs | 3 +- src/ObjCRuntime/Dlfcn.cs | 3 +- src/ObjCRuntime/INativeObject.cs | 2 +- src/ObjCRuntime/NativeHandle.cs | 4 +- src/ObjCRuntime/PlatformAvailability.cs | 2 +- src/ObjCRuntime/RegistrarHelper.cs | 24 +- src/ObjCRuntime/RequiredFrameworkAttribute.cs | 7 +- src/ObjCRuntime/Runtime.CoreCLR.cs | 52 +- src/ObjCRuntime/Runtime.cs | 31 +- src/ObjCRuntime/Runtime.mac.cs | 4 +- src/PassKit/PKCompat.cs | 5 +- src/PdfKit/Enums.cs | 100 +- src/PhotosUI/PHEnums.cs | 4 +- src/QuickLook/Thumbnail.cs | 6 +- src/SceneKit/Defs.cs | 18 +- src/SceneKit/SCNMatrix4_dotnet.cs | 180 +- src/SceneKit/SCNQuaternion.cs | 18 +- src/SceneKit/SCNVector3.cs | 88 +- src/SceneKit/SCNVector4.cs | 50 +- src/Security/Authorization.cs | 80 +- src/Security/Enums.cs | 4 +- src/Security/Items.cs | 130 +- src/Security/SecCertificate2.cs | 2 +- src/Security/SecIdentity2.cs | 2 +- src/Security/SecSharedCredential.cs | 26 +- src/Security/SecTrust2.cs | 2 +- src/Simd/MathHelper.cs | 3 +- src/Simd/MatrixFloat3x3RM.cs | 32 +- src/Simd/MatrixFloat4x3.cs | 2 +- src/Simd/QuaternionDouble.cs | 13 +- src/Simd/VectorDouble2.cs | 8 +- src/Simd/VectorDouble4.cs | 11 +- src/Simd/VectorInt2.cs | 8 +- src/Simd/VectorInt3.cs | 8 +- src/Simd/VectorInt4.cs | 8 +- src/StoreKit/SKOverlayAppClipConfiguration.cs | 7 +- src/StoreKit/SKOverlayAppConfiguration.cs | 7 +- src/System.Net.Http/CFNetworkHandler.cs | 2 +- src/UIKit/NSLayoutManager.cs | 2 +- src/UIKit/UIActionSheet.cs | 10 +- src/UIKit/UIAppearance.cs | 4 +- src/UIKit/UIButton.cs | 2 +- src/UIKit/UIDevice.cs | 2 +- src/UIKit/UIDocumentBrowserViewController.cs | 6 +- src/UIKit/UIImage.cs | 6 +- src/UIKit/UINavigationBar.cs | 4 +- src/UIKit/UIPasteboard.cs | 14 +- src/UIKit/UIPickerView.cs | 2 +- src/UIKit/UIPopoverPresentationController.cs | 2 +- src/UIKit/UIStringDrawing.cs | 2 +- src/UIKit/UITextAttributes.cs | 18 +- src/UIKit/UIToolbar.cs | 8 +- src/UIKit/UIVideo.cs | 12 +- src/VideoToolbox/VTCompressionSession.cs | 2 +- src/VideoToolbox/VTDecompressionSession.cs | 6 +- src/VideoToolbox/VTRawProcessingSession.cs | 4 +- src/WebKit/WKPreferences.cs | 2 +- src/accessorysetupkit.cs | 54 +- src/appkit.cs | 4 +- src/authenticationservices.cs | 9 +- src/avfoundation.cs | 10 +- src/backgroundassets.cs | 3 +- src/browserenginekit.cs | 297 +- src/contactsui.cs | 9 +- src/coreanimation.cs | 5 +- src/coredata.cs | 14 +- src/corehaptics.cs | 2 +- src/coreimage.cs | 6 +- src/corelocation.cs | 4 +- src/corenfc.cs | 8 +- src/coretext.cs | 9 +- src/cryptotokenkit.cs | 249 +- src/eventkit.cs | 2 +- src/foundation.cs | 29 +- src/gamekit.cs | 16 +- src/healthkit.cs | 2 +- src/mapkit.cs | 10 +- src/mediaextension.cs | 225 +- src/mediaplayer.cs | 6 +- src/metal.cs | 2 +- src/metrickit.cs | 2 +- src/networkextension.cs | 4 +- src/quicklook.cs | 6 +- src/scenekit.cs | 2 +- src/sharedwithyou.cs | 12 +- src/soundanalysis.cs | 2 +- src/spritekit.cs | 5100 ++++++++--------- src/storekit.cs | 18 +- src/tvmlkit.cs | 9 +- src/uikit.cs | 4 +- src/webkit.cs | 6 +- src/xkit.cs | 76 +- 219 files changed, 4389 insertions(+), 4539 deletions(-) diff --git a/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs b/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs index 02331fe8f91a..b4bcb7ff7a81 100644 --- a/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs +++ b/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs @@ -17,7 +17,7 @@ public virtual AVAssetDownloadedAssetEvictionPriority Priority { } public partial class AVMutableAssetDownloadStorageManagementPolicy { - + public override AVAssetDownloadedAssetEvictionPriority Priority { get { return AVAssetDownloadedAssetEvictionPriorityExtensions.GetValue (_Priority); } set { _Priority = value.GetConstant () ?? throw new ArgumentOutOfRangeException (nameof (Priority)); } diff --git a/src/AVFoundation/AVCaptureMetadataOutput.cs b/src/AVFoundation/AVCaptureMetadataOutput.cs index a4d7564bdeb2..48806d4fdf78 100644 --- a/src/AVFoundation/AVCaptureMetadataOutput.cs +++ b/src/AVFoundation/AVCaptureMetadataOutput.cs @@ -36,12 +36,12 @@ namespace AVFoundation { public partial class AVCaptureMetadataOutput { - + public AVMetadataObjectType AvailableMetadataObjectTypes { get { return AVMetadataObjectTypeExtensions.ToFlags (WeakAvailableMetadataObjectTypes); } } - public AVMetadataObjectType MetadataObjectTypes { + public AVMetadataObjectType MetadataObjectTypes { get { return AVMetadataObjectTypeExtensions.ToFlags (WeakMetadataObjectTypes); } set { WeakMetadataObjectTypes = value.ToArray (); } } diff --git a/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs b/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs index 0d40567dc4df..efa68e1be136 100644 --- a/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs +++ b/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs @@ -36,12 +36,12 @@ namespace AVFoundation { public partial class AVMetadataMachineReadableCodeObject { - public CGPoint[]? Corners { + public CGPoint []? Corners { get { var arr = WeakCorners; if (arr is null) return null; - var rv = new CGPoint[arr.Length]; + var rv = new CGPoint [arr.Length]; for (int i = 0; i < rv.Length; i++) { var dict = arr [i]; CGPoint pnt; diff --git a/src/AVFoundation/AVOutputSettingsAssistant.cs b/src/AVFoundation/AVOutputSettingsAssistant.cs index 0b38d546a4a2..246b8e373345 100644 --- a/src/AVFoundation/AVOutputSettingsAssistant.cs +++ b/src/AVFoundation/AVOutputSettingsAssistant.cs @@ -20,19 +20,19 @@ public AVOutputSettingsAssistant? Preset640x480 { return FromPreset (_Preset640x480); } } - + public AVOutputSettingsAssistant? Preset960x540 { get { return FromPreset (_Preset960x540); } } - + public AVOutputSettingsAssistant? Preset1280x720 { get { return FromPreset (_Preset1280x720); } } - + public AVOutputSettingsAssistant? Preset1920x1080 { get { return FromPreset (_Preset1920x1080); diff --git a/src/AVRouting/AVCustomDeviceRoute.cs b/src/AVRouting/AVCustomDeviceRoute.cs index 0e48913281e2..20a878143495 100644 --- a/src/AVRouting/AVCustomDeviceRoute.cs +++ b/src/AVRouting/AVCustomDeviceRoute.cs @@ -13,7 +13,7 @@ namespace AVRouting { partial class AVCustomDeviceRoute { - public NWEndpoint NetworkEndpoint => new NWEndpoint (_NetworkEndpoint, owns: false); + public NWEndpoint NetworkEndpoint => new NWEndpoint (_NetworkEndpoint, owns: false); } } diff --git a/src/Accessibility/AXSettings.cs b/src/Accessibility/AXSettings.cs index 0d2cd574f394..760988c28a26 100644 --- a/src/Accessibility/AXSettings.cs +++ b/src/Accessibility/AXSettings.cs @@ -51,7 +51,7 @@ public static bool IsAssistiveAccessEnabled { [SupportedOSPlatform ("macos15.0")] [SupportedOSPlatform ("tvos18.0")] [DllImport (Constants.AccessibilityLibrary)] - unsafe static extern void AXOpenSettingsFeature (nint /* AXSettingsFeature */ feature, BlockLiteral *block); + unsafe static extern void AXOpenSettingsFeature (nint /* AXSettingsFeature */ feature, BlockLiteral* block); /// Open the Settings app to the specified section. /// The section to open. diff --git a/src/AddressBook/ABAddressBook.cs b/src/AddressBook/ABAddressBook.cs index cfcee0027fda..fbeeb3e682f1 100644 --- a/src/AddressBook/ABAddressBook.cs +++ b/src/AddressBook/ABAddressBook.cs @@ -85,7 +85,7 @@ static InitConstants () { #if __MACCATALYST__ // avoid TypeLoadException if used before macOS 11.x - if (!SystemVersion.CheckiOS (14,0)) + if (!SystemVersion.CheckiOS (14, 0)) return; #endif // ensure we can init. This is needed before iOS6 (as per doc). diff --git a/src/AppKit/Functions.cs b/src/AppKit/Functions.cs index afe5a2e27b13..4a4299de2950 100644 --- a/src/AppKit/Functions.cs +++ b/src/AppKit/Functions.cs @@ -36,9 +36,9 @@ namespace AppKit { #if MONOMAC // Class to access C functions public partial class AppKitFramework { - + [DllImport (Constants.AppKitLibrary)] - public static extern void NSBeep(); + public static extern void NSBeep (); } #endif } diff --git a/src/AppKit/NSGraphics.cs b/src/AppKit/NSGraphics.cs index 4d8d857e889e..617f034b17ef 100644 --- a/src/AppKit/NSGraphics.cs +++ b/src/AppKit/NSGraphics.cs @@ -181,7 +181,7 @@ public static void FrameRect (CGRect rect, nfloat frameWidth, NSCompositingOpera #if NET [SupportedOSPlatform ("macos")] - [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead." )] + [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead.")] #else [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use 'NSCursor.DisappearingItemCursor' instead.")] #endif @@ -190,7 +190,7 @@ public static void FrameRect (CGRect rect, nfloat frameWidth, NSCompositingOpera #if NET [SupportedOSPlatform ("macos")] - [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead." )] + [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead.")] #else [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use 'NSCursor.DisappearingItemCursor' instead.")] #endif diff --git a/src/AppKit/NSPasteboardReading.cs b/src/AppKit/NSPasteboardReading.cs index 04e90627818c..a6587fa1a415 100644 --- a/src/AppKit/NSPasteboardReading.cs +++ b/src/AppKit/NSPasteboardReading.cs @@ -11,7 +11,7 @@ namespace AppKit { public partial interface INSPasteboardReading { [BindingImpl (BindingImplOptions.Optimizable)] - public unsafe static T? CreateInstance (NSObject propertyList, NSPasteboardType type) where T: NSObject, INSPasteboardReading + public unsafe static T? CreateInstance (NSObject propertyList, NSPasteboardType type) where T : NSObject, INSPasteboardReading { return CreateInstance (propertyList, type.GetConstant ()!); } diff --git a/src/AudioToolbox/AudioConverter.cs b/src/AudioToolbox/AudioConverter.cs index 4a672adc6b86..b993c9f7208d 100644 --- a/src/AudioToolbox/AudioConverter.cs +++ b/src/AudioToolbox/AudioConverter.cs @@ -583,13 +583,13 @@ AudioConverterError FillComplexBuffer (ref int outputDataPacketSize, var packetSize = outputDataPacketSize; int* packetSizePtr = &packetSize; if (packetDescription is null) { - var returnOne = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr)packetSizePtr, (IntPtr) outputData, IntPtr.Zero); + var returnOne = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr) packetSizePtr, (IntPtr) outputData, IntPtr.Zero); outputDataPacketSize = packetSize; return returnOne; } fixed (AudioStreamPacketDescription* pdesc = packetDescription) { - var returnTwo = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr)packetSizePtr, (IntPtr) outputData, (IntPtr) pdesc); + var returnTwo = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr) packetSizePtr, (IntPtr) outputData, (IntPtr) pdesc); outputDataPacketSize = packetSize; return returnTwo; } diff --git a/src/AudioToolbox/AudioFile.cs b/src/AudioToolbox/AudioFile.cs index 71130c797555..83c5ca7ac299 100644 --- a/src/AudioToolbox/AudioFile.cs +++ b/src/AudioToolbox/AudioFile.cs @@ -1444,7 +1444,7 @@ public IntPtr GetProperty (AudioFileProperty property, out int size) return IntPtr.Zero; } #if NET - unsafe T? GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileProperty property) where T : unmanaged + unsafe T? GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileProperty property) where T : unmanaged #else unsafe T? GetProperty (AudioFileProperty property) where T : unmanaged #endif diff --git a/src/AudioToolbox/AudioFileStream.cs b/src/AudioToolbox/AudioFileStream.cs index 5c6395deb45a..d227efe43049 100644 --- a/src/AudioToolbox/AudioFileStream.cs +++ b/src/AudioToolbox/AudioFileStream.cs @@ -438,7 +438,7 @@ long GetLong (AudioFileStreamProperty property) } #if NET - unsafe T? GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileStreamProperty property) where T : unmanaged + unsafe T? GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileStreamProperty property) where T : unmanaged #else unsafe T? GetProperty (AudioFileStreamProperty property) where T : unmanaged #endif diff --git a/src/AudioToolbox/AudioQueue.cs b/src/AudioToolbox/AudioQueue.cs index 3d2a248651d8..1e7bee989edb 100644 --- a/src/AudioToolbox/AudioQueue.cs +++ b/src/AudioToolbox/AudioQueue.cs @@ -988,7 +988,7 @@ public IntPtr GetProperty (AudioQueueProperty property, out int size) // Should be private #if NET - public unsafe T GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioQueueProperty property) where T : struct + public unsafe T GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioQueueProperty property) where T : struct #else public unsafe T GetProperty (AudioQueueProperty property) where T : struct #endif @@ -1016,7 +1016,7 @@ public unsafe T GetProperty (AudioQueueProperty property) where T : struct } #if NET - unsafe T GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioConverterPropertyID property) where T : struct + unsafe T GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioConverterPropertyID property) where T : struct #else unsafe T GetProperty (AudioConverterPropertyID property) where T : struct #endif @@ -1189,7 +1189,7 @@ public AudioStreamBasicDescription AudioStreamDescription { #if !MONOMAC return GetProperty (AudioQueueProperty.StreamDescription); #else - return GetProperty (AudioConverterPropertyID.CurrentInputStreamDescription); + return GetProperty (AudioConverterPropertyID.CurrentInputStreamDescription); #endif } } @@ -1296,7 +1296,7 @@ extern static AudioQueueStatus AudioQueueProcessingTapNew (IntPtr inAQ, AudioQue #if NET unsafe { status = AudioQueueProcessingTapNew (handle, &AudioQueueProcessingTap.TapCallback, GCHandle.ToIntPtr (aqpt.Handle), flags, &maxFrames, - &processingFormat, &tapHandle); + &processingFormat, &tapHandle); } #else status = AudioQueueProcessingTapNew (handle, AudioQueueProcessingTap.CreateTapCallback, GCHandle.ToIntPtr (aqpt.Handle), flags, out maxFrames, @@ -1459,7 +1459,7 @@ public class OutputAudioQueue : AudioQueue { #if NET [DllImport (Constants.AudioToolboxLibrary)] extern unsafe static OSStatus AudioQueueNewOutput (AudioStreamBasicDescription* format, delegate* unmanaged callback, - IntPtr userData, IntPtr cfrunLoop_callbackRunloop, IntPtr cfstr_runMode, + IntPtr userData, IntPtr cfrunLoop_callbackRunloop, IntPtr cfstr_runMode, uint flags, IntPtr* audioQueue); #else static readonly AudioQueueOutputCallback dOutputCallback = output_callback; diff --git a/src/AudioToolbox/MusicTrack.cs b/src/AudioToolbox/MusicTrack.cs index 53d36bafc3cf..37866a3a50cc 100644 --- a/src/AudioToolbox/MusicTrack.cs +++ b/src/AudioToolbox/MusicTrack.cs @@ -309,7 +309,7 @@ public MusicPlayerStatus GetDestMidiEndpoint (out MidiEndpoint? outEndpoint) unsafe { result = MusicTrackGetDestMIDIEndpoint (Handle, &midiHandle); } - outEndpoint = (result == MusicPlayerStatus.Success)? new MidiEndpoint (midiHandle): null; + outEndpoint = (result == MusicPlayerStatus.Success) ? new MidiEndpoint (midiHandle) : null; return result; } #endif diff --git a/src/AudioToolbox/SystemSound.cs b/src/AudioToolbox/SystemSound.cs index 70295f4cb8c0..1e3d4be7f3fa 100644 --- a/src/AudioToolbox/SystemSound.cs +++ b/src/AudioToolbox/SystemSound.cs @@ -402,7 +402,7 @@ public AudioServicesError AddSystemSoundCompletion (Action routine, CFRunLoop? r runLoop.GetHandle (), IntPtr.Zero, // runLoopMode should be enum runLoopMode.GetHandle (), #if NET - &SoundCompletionShared, + &SoundCompletionShared, #else SoundCompletionCallback, #endif diff --git a/src/AudioUnit/AUEnums.cs b/src/AudioUnit/AUEnums.cs index 9eb7acba5f32..54a921159598 100644 --- a/src/AudioUnit/AUEnums.cs +++ b/src/AudioUnit/AUEnums.cs @@ -505,16 +505,16 @@ public enum AudioUnitParameterType // UInt32 in AudioUnitParameterInfo Mixer3DGain = 3, Mixer3DPlaybackRate = 4, #if MONOMAC - Mixer3DReverbBlend = 5, - Mixer3DGlobalReverbGain = 6, - Mixer3DOcclusionAttenuation = 7, - Mixer3DObstructionAttenuation = 8, - Mixer3DMinGain = 9, - Mixer3DMaxGain = 10, - Mixer3DPreAveragePower = 1000, - Mixer3DPrePeakHoldLevel = 2000, - Mixer3DPostAveragePower = 3000, - Mixer3DPostPeakHoldLevel = 4000, + Mixer3DReverbBlend = 5, + Mixer3DGlobalReverbGain = 6, + Mixer3DOcclusionAttenuation = 7, + Mixer3DObstructionAttenuation = 8, + Mixer3DMinGain = 9, + Mixer3DMaxGain = 10, + Mixer3DPreAveragePower = 1000, + Mixer3DPrePeakHoldLevel = 2000, + Mixer3DPostAveragePower = 3000, + Mixer3DPostPeakHoldLevel = 4000, #else Mixer3DEnable = 5, Mixer3DMinGain = 6, @@ -563,8 +563,8 @@ public enum AudioUnitParameterType // UInt32 in AudioUnitParameterInfo // AUTimePitch, AUTimePitch (offline), AUPitch units TimePitchRate = 0, #if MONOMAC - TimePitchPitch = 1, - TimePitchEffectBlend = 2, + TimePitchPitch = 1, + TimePitchEffectBlend = 2, #endif // AUNewTimePitch @@ -969,24 +969,24 @@ public enum AudioUnitSubType : uint { AudioFilePlayer = 0x6166706C, // 'afpl' #if MONOMAC - HALOutput = 0x6168616C, // 'ahal' - DefaultOutput = 0x64656620, // 'def ' - SystemOutput = 0x73797320, // 'sys ' - DLSSynth = 0x646C7320, // 'dls ' - TimePitch = 0x746D7074, // 'tmpt' - GraphicEQ = 0x67726571, // 'greq' - MultiBandCompressor = 0x6D636D70, // 'mcmp' - MatrixReverb = 0x6D726576, // 'mrev' - Pitch = 0x746D7074, // 'tmpt' - AUFilter = 0x66696C74, // 'filt - NetSend = 0x6E736E64, // 'nsnd' - RogerBeep = 0x726F6772, // 'rogr' - StereoMixer = 0x736D7872, // 'smxr' - SphericalHeadPanner = 0x73706872, // 'sphr' - VectorPanner = 0x76626173, // 'vbas' - SoundFieldPanner = 0x616D6269, // 'ambi' - HRTFPanner = 0x68727466, // 'hrtf' - NetReceive = 0x6E726376, // 'nrcv' + HALOutput = 0x6168616C, // 'ahal' + DefaultOutput = 0x64656620, // 'def ' + SystemOutput = 0x73797320, // 'sys ' + DLSSynth = 0x646C7320, // 'dls ' + TimePitch = 0x746D7074, // 'tmpt' + GraphicEQ = 0x67726571, // 'greq' + MultiBandCompressor = 0x6D636D70, // 'mcmp' + MatrixReverb = 0x6D726576, // 'mrev' + Pitch = 0x746D7074, // 'tmpt' + AUFilter = 0x66696C74, // 'filt + NetSend = 0x6E736E64, // 'nsnd' + RogerBeep = 0x726F6772, // 'rogr' + StereoMixer = 0x736D7872, // 'smxr' + SphericalHeadPanner = 0x73706872, // 'sphr' + VectorPanner = 0x76626173, // 'vbas' + SoundFieldPanner = 0x616D6269, // 'ambi' + HRTFPanner = 0x68727466, // 'hrtf' + NetReceive = 0x6E726376, // 'nrcv' #endif } diff --git a/src/AudioUnit/AUGraph.cs b/src/AudioUnit/AUGraph.cs index eaed2bec657b..e0637a5c1a94 100644 --- a/src/AudioUnit/AUGraph.cs +++ b/src/AudioUnit/AUGraph.cs @@ -175,7 +175,7 @@ public AudioUnitStatus RemoveRenderNotify (RenderDelegate callback) #if NET unsafe { if (graphUserCallbacks.Count == 0) - error = (AudioUnitStatus)AUGraphRemoveRenderNotify (Handle, &renderCallback, GCHandle.ToIntPtr (gcHandle)); + error = (AudioUnitStatus) AUGraphRemoveRenderNotify (Handle, &renderCallback, GCHandle.ToIntPtr (gcHandle)); } #else if (graphUserCallbacks.Count == 0) @@ -201,7 +201,7 @@ static CallbackShared static_CallbackShared { #if NET [UnmanagedCallersOnly] - static unsafe AudioUnitStatus renderCallback(IntPtr inRefCon, + static unsafe AudioUnitStatus renderCallback (IntPtr inRefCon, AudioUnitRenderActionFlags* _ioActionFlags, AudioTimeStamp* _inTimeStamp, uint _inBusNumber, @@ -530,14 +530,14 @@ protected override void Dispose (bool disposing) [DllImport (Constants.AudioToolboxLibrary)] #if NET - static unsafe extern int AUGraphAddRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon ); + static unsafe extern int AUGraphAddRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon); #else static extern int AUGraphAddRenderNotify (IntPtr inGraph, CallbackShared inCallback, IntPtr inRefCon); #endif #if NET [DllImport (Constants.AudioToolboxLibrary)] - static unsafe extern int AUGraphRemoveRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon ); + static unsafe extern int AUGraphRemoveRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon); #else [DllImport (Constants.AudioToolboxLibrary)] static extern int AUGraphRemoveRenderNotify (IntPtr inGraph, CallbackShared inCallback, IntPtr inRefCon); diff --git a/src/AudioUnit/AudioComponent.cs b/src/AudioUnit/AudioComponent.cs index f5a073cc670c..8cdc6261ab28 100644 --- a/src/AudioUnit/AudioComponent.cs +++ b/src/AudioUnit/AudioComponent.cs @@ -43,7 +43,7 @@ #else using AppKit; #if !COREBUILD -using UIImage=AppKit.NSImage; +using UIImage = AppKit.NSImage; #endif #endif @@ -512,7 +512,8 @@ public double LastActiveTime { [Mac (13,0)] [iOS (16,0)] #endif - public NSDictionary? GetConfigurationInfo (out int resultCode) { + public NSDictionary? GetConfigurationInfo (out int resultCode) + { IntPtr dictPtr; unsafe { resultCode = AudioComponentCopyConfigurationInfo (GetCheckedHandle (), &dictPtr); @@ -561,7 +562,8 @@ unsafe static extern int AudioComponentValidate (IntPtr /* AudioComponent* */ in [iOS (16,0)] [MacCatalyst (16,0)] #endif - public AudioComponentValidationResult Validate (NSDictionary? validationParameters, out int resultCode) { + public AudioComponentValidationResult Validate (NSDictionary? validationParameters, out int resultCode) + { AudioComponentValidationResult result; unsafe { resultCode = AudioComponentValidate (GetCheckedHandle (), validationParameters.GetHandle (), &result); @@ -597,7 +599,7 @@ static void TrampolineAction (IntPtr blockPtr, AudioComponentValidationResult re { var del = BlockLiteral.GetTarget> (blockPtr); if (del is not null) - del (result, Runtime.GetNSObject(dictionary)); + del (result, Runtime.GetNSObject (dictionary)); } #if NET @@ -625,10 +627,11 @@ static void TrampolineAction (IntPtr blockPtr, AudioComponentValidationResult re #endif [BindingImpl (BindingImplOptions.Optimizable)] public void ValidateAsync (NSDictionary? validationParameters, - Action onCompletion, out int resultCode) { + Action onCompletion, out int resultCode) + { if (onCompletion is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (onCompletion)); - + unsafe { #if NET delegate* unmanaged trampoline = &TrampolineAction; @@ -696,7 +699,7 @@ public void ValidateAsync (NSDictionary? validationParameters, #else [NoTV] #endif - public AudioComponentInfo[]? ComponentList { + public AudioComponentInfo []? ComponentList { get { var nameHandle = CFString.CreateNative (Name); try { @@ -707,10 +710,10 @@ public AudioComponentInfo[]? ComponentList { if (nsArray is null) return null; // make things easier for developers since we do not know how to have an implicit conversion from NSObject to AudioComponentInfo - var dics = NSArray.FromArray (nsArray); + var dics = NSArray.FromArray (nsArray); var result = new AudioComponentInfo [dics.Length]; for (var i = 0; i < result.Length; i++) { - result [i] = new AudioComponentInfo (dics[i]); + result [i] = new AudioComponentInfo (dics [i]); } return result; } diff --git a/src/AudioUnit/AudioComponentDescription.cs b/src/AudioUnit/AudioComponentDescription.cs index 48b801c68c16..019ee39f512f 100644 --- a/src/AudioUnit/AudioComponentDescription.cs +++ b/src/AudioUnit/AudioComponentDescription.cs @@ -97,9 +97,9 @@ public enum AudioComponentType : uint { // OSType in AudioComponentDescription public enum AudioTypeOutput { // OSType in AudioComponentDescription Generic = 0x67656e72, // 'genr' #if MONOMAC - HAL=0x6168616c, // 'ahal' - Default=0x64656620, // 'def' - System=0x73797320, // 'sys' + HAL = 0x6168616c, // 'ahal' + Default = 0x64656620, // 'def' + System = 0x73797320, // 'sys' #endif #if NET [SupportedOSPlatform ("macos")] @@ -113,7 +113,7 @@ public enum AudioTypeOutput { // OSType in AudioComponentDescription public enum AudioTypeMusicDevice { // OSType in AudioComponentDescription #if MONOMAC - DlsSynth = 0x646c7320, // 'dls ' + DlsSynth = 0x646c7320, // 'dls ' #endif Sampler = 0x73616d70, // 'samp' @@ -137,7 +137,7 @@ public enum AudioTypeConverter { // OSType in AudioComponentDescription RoundTripAAC = 0x72616163, // 'raac' MultiSplitter = 0x6d73706c, // 'mspl' #if MONOMAC - TimePitch=0x746d7074, // 'tmpt' + TimePitch = 0x746d7074, // 'tmpt' #else #if NET [SupportedOSPlatform ("ios")] @@ -188,13 +188,13 @@ public enum AudioTypeEffect { // OSType in AudioComponentDescription Distortion = 0x64697374, // 'dist' BandPassFilter = 0x62706173, // 'bpas' #if MONOMAC - GraphicEQ=0x67726571, // 'greq' - MultiBandCompressor=0x6d636d70, // 'mcmp' - MatrixReverb=0x6d726576, // 'mrev' - Pitch=0x70697463, // 'pitc' - AUFilter=0x66696c74, // 'filt' - NetSend=0x6e736e64, // 'nsnd' - RogerBeep=0x726f6772, // 'rogr' + GraphicEQ = 0x67726571, // 'greq' + MultiBandCompressor = 0x6d636d70, // 'mcmp' + MatrixReverb = 0x6d726576, // 'mrev' + Pitch = 0x70697463, // 'pitc' + AUFilter = 0x66696c74, // 'filt' + NetSend = 0x6e736e64, // 'nsnd' + RogerBeep = 0x726f6772, // 'rogr' #else #if NET [SupportedOSPlatform ("ios")] @@ -227,7 +227,7 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription Matrix = 0x6d786d78, // 'mxmx' Spacial = 0x3364656d, // Same as Embedded3D #if MONOMAC - Stereo=0x736d7872, // 'smxr' + Stereo = 0x736d7872, // 'smxr' #if NET [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("maccatalyst")] @@ -237,7 +237,7 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription #else [Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'Spacial' instead.")] #endif - ThreeD=0x33646d78, // '3dmx' + ThreeD = 0x33646d78, // '3dmx' #else #if NET [SupportedOSPlatform ("ios")] @@ -252,16 +252,16 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription public enum AudioTypePanner { // OSType in AudioComponentDescription #if MONOMAC - SphericalHead=0x73706872, // 'sphr' - Vector=0x76626173, // 'vbas' - SoundField=0x616d6269, // 'ambi' - rHRTF=0x68727466, // 'hrtf' + SphericalHead = 0x73706872, // 'sphr' + Vector = 0x76626173, // 'vbas' + SoundField = 0x616d6269, // 'ambi' + rHRTF = 0x68727466, // 'hrtf' #endif } public enum AudioTypeGenerator { // OSType in AudioComponentDescription #if MONOMAC - NetReceive=0x6e726376, // 'nrcv' + NetReceive = 0x6e726376, // 'nrcv' #endif ScheduledSoundPlayer = 0x7373706c, // 'sspl' AudioFilePlayer = 0x6166706c, // 'afpl' diff --git a/src/AudioUnit/AudioUnit.cs b/src/AudioUnit/AudioUnit.cs index 332c6302aa1f..ede6350113d9 100644 --- a/src/AudioUnit/AudioUnit.cs +++ b/src/AudioUnit/AudioUnit.cs @@ -131,14 +131,13 @@ internal AudioUnitException (int k) : base (Lookup (k)) #if NET [StructLayout (LayoutKind.Sequential)] - unsafe struct AURenderCallbackStruct - { + unsafe struct AURenderCallbackStruct { #if COREBUILD public delegate* unmanaged Proc; #else public delegate* unmanaged Proc; #endif - public IntPtr ProcRefCon; + public IntPtr ProcRefCon; } #else [StructLayout (LayoutKind.Sequential)] @@ -701,7 +700,7 @@ public AudioUnitStatus SetRenderCallback (RenderDelegate renderDelegate, AudioUn #if NET [UnmanagedCallersOnly] - static unsafe AudioUnitStatus RenderCallbackImpl (IntPtr clientData, AudioUnitRenderActionFlags* actionFlags, AudioTimeStamp* timeStamp, uint busNumber, uint numberFrames, IntPtr data) + static unsafe AudioUnitStatus RenderCallbackImpl (IntPtr clientData, AudioUnitRenderActionFlags* actionFlags, AudioTimeStamp* timeStamp, uint busNumber, uint numberFrames, IntPtr data) #else [MonoPInvokeCallback (typeof (CallbackShared))] static AudioUnitStatus RenderCallbackImpl (IntPtr clientData, ref AudioUnitRenderActionFlags actionFlags, ref AudioTimeStamp timeStamp, uint busNumber, uint numberFrames, IntPtr data) @@ -1173,7 +1172,7 @@ public AudioObjectPropertyAddress (AudioObjectPropertySelector selector, AudioOb #endif public unsafe class AURenderEventEnumerator : INativeObject #if COREBUILD - {} + { } #else , IEnumerator { AURenderEvent* current; diff --git a/src/AudioUnit/AudioUnitUtils.cs b/src/AudioUnit/AudioUnitUtils.cs index 9303de1a98d0..156b07afcda2 100644 --- a/src/AudioUnit/AudioUnitUtils.cs +++ b/src/AudioUnit/AudioUnitUtils.cs @@ -40,10 +40,10 @@ namespace AudioUnit { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public static class AudioUnitUtils { public const int SampleFractionBits = 24; diff --git a/src/AudioUnit/ExtAudioFile.cs b/src/AudioUnit/ExtAudioFile.cs index 83fab37e4822..06d154f43695 100644 --- a/src/AudioUnit/ExtAudioFile.cs +++ b/src/AudioUnit/ExtAudioFile.cs @@ -70,10 +70,10 @@ public enum ExtAudioFileError // Implictly cast to OSType } #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public class ExtAudioFile : IDisposable { IntPtr _extAudioFile; diff --git a/src/BrowserEngineKit/BEStructs.cs b/src/BrowserEngineKit/BEStructs.cs index b969768b35f7..c6f6a5c1e1dc 100644 --- a/src/BrowserEngineKit/BEStructs.cs +++ b/src/BrowserEngineKit/BEStructs.cs @@ -6,16 +6,15 @@ namespace BrowserEngineKit { #if IOS || MACCATALYST || TVOS - [SupportedOSPlatform ("ios17.4")] - [SupportedOSPlatform ("maccatalyst17.4")] - [SupportedOSPlatform ("tvos17.4")] - [UnsupportedOSPlatform ("macos")] - [StructLayout (LayoutKind.Sequential)] - public struct BEDirectionalTextRange - { - public nint Offset; - public nint Length; - } + [SupportedOSPlatform ("ios17.4")] + [SupportedOSPlatform ("maccatalyst17.4")] + [SupportedOSPlatform ("tvos17.4")] + [UnsupportedOSPlatform ("macos")] + [StructLayout (LayoutKind.Sequential)] + public struct BEDirectionalTextRange { + public nint Offset; + public nint Length; + } #endif // __IOS__ || __MACCATALYST__ } #endif // NET diff --git a/src/Compression/CompressionStreamStruct.cs b/src/Compression/CompressionStreamStruct.cs index 1bc4c1199b06..f50a88783d3d 100644 --- a/src/Compression/CompressionStreamStruct.cs +++ b/src/Compression/CompressionStreamStruct.cs @@ -8,10 +8,10 @@ namespace Compression { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("tvos")] #endif [StructLayout (LayoutKind.Sequential)] struct CompressionStreamStruct { diff --git a/src/Compression/TaskToApm.cs b/src/Compression/TaskToApm.cs index 4207ccc2c802..643eefcf889b 100644 --- a/src/Compression/TaskToApm.cs +++ b/src/Compression/TaskToApm.cs @@ -22,107 +22,99 @@ #nullable enable using System.Diagnostics; -namespace System.Threading.Tasks -{ - /// - /// Provides support for efficiently using Tasks to implement the APM (Begin/End) pattern. - /// - internal static class TaskToApm - { - /// - /// Marshals the Task as an IAsyncResult, using the supplied callback and state - /// to implement the APM pattern. - /// - /// The Task to be marshaled. - /// The callback to be invoked upon completion. - /// The state to be stored in the IAsyncResult. - /// An IAsyncResult to represent the task's asynchronous operation. - public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state) => - new TaskAsyncResult(task, state, callback); +namespace System.Threading.Tasks { + /// + /// Provides support for efficiently using Tasks to implement the APM (Begin/End) pattern. + /// + internal static class TaskToApm { + /// + /// Marshals the Task as an IAsyncResult, using the supplied callback and state + /// to implement the APM pattern. + /// + /// The Task to be marshaled. + /// The callback to be invoked upon completion. + /// The state to be stored in the IAsyncResult. + /// An IAsyncResult to represent the task's asynchronous operation. + public static IAsyncResult Begin (Task task, AsyncCallback? callback, object? state) => + new TaskAsyncResult (task, state, callback); - /// Processes an IAsyncResult returned by Begin. - /// The IAsyncResult to unwrap. - public static void End(IAsyncResult asyncResult) - { - if (asyncResult is TaskAsyncResult twar) - { - twar._task.GetAwaiter().GetResult(); - return; - } + /// Processes an IAsyncResult returned by Begin. + /// The IAsyncResult to unwrap. + public static void End (IAsyncResult asyncResult) + { + if (asyncResult is TaskAsyncResult twar) { + twar._task.GetAwaiter ().GetResult (); + return; + } - throw new ArgumentNullException(); - } + throw new ArgumentNullException (); + } - /// Processes an IAsyncResult returned by Begin. - /// The IAsyncResult to unwrap. - public static TResult End(IAsyncResult asyncResult) - { - if (asyncResult is TaskAsyncResult twar && twar._task is Task task) - { - return task.GetAwaiter().GetResult(); - } - throw new ArgumentNullException(); - } + /// Processes an IAsyncResult returned by Begin. + /// The IAsyncResult to unwrap. + public static TResult End (IAsyncResult asyncResult) + { + if (asyncResult is TaskAsyncResult twar && twar._task is Task task) { + return task.GetAwaiter ().GetResult (); + } + throw new ArgumentNullException (); + } - /// Provides a simple IAsyncResult that wraps a Task. - /// - /// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state, - /// but that's very rare, in particular in a situation where someone cares about allocation, and always - /// using TaskAsyncResult simplifies things and enables additional optimizations. - /// - internal sealed class TaskAsyncResult : IAsyncResult - { - /// The wrapped Task. - internal readonly Task _task; - /// Callback to invoke when the wrapped task completes. - private readonly AsyncCallback? _callback; + /// Provides a simple IAsyncResult that wraps a Task. + /// + /// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state, + /// but that's very rare, in particular in a situation where someone cares about allocation, and always + /// using TaskAsyncResult simplifies things and enables additional optimizations. + /// + internal sealed class TaskAsyncResult : IAsyncResult { + /// The wrapped Task. + internal readonly Task _task; + /// Callback to invoke when the wrapped task completes. + private readonly AsyncCallback? _callback; - /// Initializes the IAsyncResult with the Task to wrap and the associated object state. - /// The Task to wrap. - /// The new AsyncState value. - /// Callback to invoke when the wrapped task completes. - internal TaskAsyncResult(Task task, object? state, AsyncCallback? callback) - { - Debug.Assert(task is not null); - _task = task; - AsyncState = state; + /// Initializes the IAsyncResult with the Task to wrap and the associated object state. + /// The Task to wrap. + /// The new AsyncState value. + /// Callback to invoke when the wrapped task completes. + internal TaskAsyncResult (Task task, object? state, AsyncCallback? callback) + { + Debug.Assert (task is not null); + _task = task; + AsyncState = state; - if (task.IsCompleted) - { - // Synchronous completion. Invoke the callback. No need to store it. - CompletedSynchronously = true; - callback?.Invoke(this); - } - else if (callback is not null) - { - // Asynchronous completion, and we have a callback; schedule it. We use OnCompleted rather than ContinueWith in - // order to avoid running synchronously if the task has already completed by the time we get here but still run - // synchronously as part of the task's completion if the task completes after (the more common case). - _callback = callback; - _task.ConfigureAwait(continueOnCapturedContext: false) - .GetAwaiter() - .OnCompleted(InvokeCallback); // allocates a delegate, but avoids a closure - } - } + if (task.IsCompleted) { + // Synchronous completion. Invoke the callback. No need to store it. + CompletedSynchronously = true; + callback?.Invoke (this); + } else if (callback is not null) { + // Asynchronous completion, and we have a callback; schedule it. We use OnCompleted rather than ContinueWith in + // order to avoid running synchronously if the task has already completed by the time we get here but still run + // synchronously as part of the task's completion if the task completes after (the more common case). + _callback = callback; + _task.ConfigureAwait (continueOnCapturedContext: false) + .GetAwaiter () + .OnCompleted (InvokeCallback); // allocates a delegate, but avoids a closure + } + } - /// Invokes the callback. - private void InvokeCallback() - { - Debug.Assert(!CompletedSynchronously); - Debug.Assert(_callback is not null); - _callback.Invoke(this); - } + /// Invokes the callback. + private void InvokeCallback () + { + Debug.Assert (!CompletedSynchronously); + Debug.Assert (_callback is not null); + _callback.Invoke (this); + } - /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. - public object? AsyncState { get; } - /// Gets a value that indicates whether the asynchronous operation completed synchronously. - /// This is set lazily based on whether the has completed by the time this object is created. - public bool CompletedSynchronously { get; } - /// Gets a value that indicates whether the asynchronous operation has completed. - public bool IsCompleted => _task.IsCompleted; - /// Gets a that is used to wait for an asynchronous operation to complete. - public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle; - } - } + /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. + public object? AsyncState { get; } + /// Gets a value that indicates whether the asynchronous operation completed synchronously. + /// This is set lazily based on whether the has completed by the time this object is created. + public bool CompletedSynchronously { get; } + /// Gets a value that indicates whether the asynchronous operation has completed. + public bool IsCompleted => _task.IsCompleted; + /// Gets a that is used to wait for an asynchronous operation to complete. + public WaitHandle AsyncWaitHandle => ((IAsyncResult) _task).AsyncWaitHandle; + } + } } #endif diff --git a/src/CoreAnimation/CATextLayer.cs b/src/CoreAnimation/CATextLayer.cs index 135d5879a8cb..40a377a5ef8f 100644 --- a/src/CoreAnimation/CATextLayer.cs +++ b/src/CoreAnimation/CATextLayer.cs @@ -106,7 +106,7 @@ public object? WeakFont { set { #if MONOMAC var ns = value as NSFont; - if (ns is not null){ + if (ns is not null) { _Font = ns.Handle; return; } diff --git a/src/CoreAnimation/CATransform3D.cs b/src/CoreAnimation/CATransform3D.cs index 88845428cbc6..a9608e3f0cfe 100644 --- a/src/CoreAnimation/CATransform3D.cs +++ b/src/CoreAnimation/CATransform3D.cs @@ -267,10 +267,10 @@ public override string ToString () { return String.Format ("[{0} {1} {2} {3}; {4} {5} {6} {7}; {8} {9} {10} {11}; {12} {13} {14} {15}]", #if NET - M11, M12, M13, M14, - M21, M22, M23, M24, - M31, M32, M33, M34, - M41, M42, M43, M44); + M11, M12, M13, M14, + M21, M22, M23, M24, + M31, M32, M33, M34, + M41, M42, M43, M44); #else m11, m12, m13, m14, m21, m22, m23, m24, diff --git a/src/CoreBluetooth/CBPeer.cs b/src/CoreBluetooth/CBPeer.cs index 4d08fc531522..418b3b009123 100644 --- a/src/CoreBluetooth/CBPeer.cs +++ b/src/CoreBluetooth/CBPeer.cs @@ -7,7 +7,7 @@ #nullable enable namespace CoreBluetooth { - public partial class CBPeer { + public partial class CBPeer { #if !NET [Deprecated (PlatformName.iOS, 7, 0)] [Obsoleted (PlatformName.iOS, 9, 0)] diff --git a/src/CoreFoundation/CFMessagePort.cs b/src/CoreFoundation/CFMessagePort.cs index 7c71ba32ec86..741bbbfabf46 100644 --- a/src/CoreFoundation/CFMessagePort.cs +++ b/src/CoreFoundation/CFMessagePort.cs @@ -264,12 +264,12 @@ protected override void Dispose (bool disposing) if (context is not null) { #if NET unsafe { - if (context.Retain is not null) - contextProxy.retain = &RetainProxy; - if (context.Release is not null) - contextProxy.release = &ReleaseProxy; - if (context.CopyDescription is not null) - contextProxy.copyDescription = &CopyDescriptionProxy; + if (context.Retain is not null) + contextProxy.retain = &RetainProxy; + if (context.Release is not null) + contextProxy.release = &ReleaseProxy; + if (context.CopyDescription is not null) + contextProxy.copyDescription = &CopyDescriptionProxy; } #else if (context.Retain is not null) diff --git a/src/CoreFoundation/CFProxySupport.cs b/src/CoreFoundation/CFProxySupport.cs index 24cdf7178f35..3ccd9134be87 100644 --- a/src/CoreFoundation/CFProxySupport.cs +++ b/src/CoreFoundation/CFProxySupport.cs @@ -719,27 +719,27 @@ await Task.Run (() => { #if NET unsafe { - using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) + using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) #else using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) #endif - using (var mode = new NSString ("Xamarin.iOS.Proxy")) { - - if (cancellationToken.IsCancellationRequested) - throw new OperationCanceledException ("Operation was cancelled."); - - cancellationToken.Register (() => { - //if user cancels, we invalidte the source, stop the runloop and remove the source - loopSource.Invalidate (); + using (var mode = new NSString ("Xamarin.iOS.Proxy")) { + + if (cancellationToken.IsCancellationRequested) + throw new OperationCanceledException ("Operation was cancelled."); + + cancellationToken.Register (() => { + //if user cancels, we invalidte the source, stop the runloop and remove the source + loopSource.Invalidate (); + runLoop.RemoveSource (loopSource, mode); + runLoop.Stop (); + }); + runLoop.AddSource (loopSource, mode); + // blocks until stop is called, will be done in the cb set previously + runLoop.RunInMode (mode, double.MaxValue, false); + // does not raise an error if source is not longer present, so no need to worry runLoop.RemoveSource (loopSource, mode); - runLoop.Stop (); - }); - runLoop.AddSource (loopSource, mode); - // blocks until stop is called, will be done in the cb set previously - runLoop.RunInMode (mode, double.MaxValue, false); - // does not raise an error if source is not longer present, so no need to worry - runLoop.RemoveSource (loopSource, mode); - } + } #if NET } // matches the unsafe block #endif @@ -783,18 +783,18 @@ await Task.Run (() => { #if NET unsafe { - using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) + using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) #else using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) #endif - using (var mode = new NSString ("Xamarin.iOS.Proxy")) { - runLoop.AddSource (loopSource, mode); - runLoop.RunInMode (mode, double.MaxValue, false); - runLoop.RemoveSource (loopSource, mode); - } - pacCbData = Marshal.PtrToStructure (pacDataPtr)!; - // get data from the struct - outError = pacCbData.Error; + using (var mode = new NSString ("Xamarin.iOS.Proxy")) { + runLoop.AddSource (loopSource, mode); + runLoop.RunInMode (mode, double.MaxValue, false); + runLoop.RemoveSource (loopSource, mode); + } + pacCbData = Marshal.PtrToStructure (pacDataPtr)!; + // get data from the struct + outError = pacCbData.Error; #if NET } // unsafe #endif diff --git a/src/CoreGraphics/CGAffineTransform.cs b/src/CoreGraphics/CGAffineTransform.cs index 620b85fdd7d7..fe3f74d41eac 100644 --- a/src/CoreGraphics/CGAffineTransform.cs +++ b/src/CoreGraphics/CGAffineTransform.cs @@ -162,11 +162,11 @@ public static CGAffineTransform Multiply (CGAffineTransform a, CGAffineTransform { #if NET return new CGAffineTransform (a.A * b.A + a.B * b.C, - a.A * b.B + a.B * b.D, - a.C * b.A + a.D * b.C, - a.C * b.B + a.D * b.D, - a.Tx * b.A + a.Ty * b.C + b.Tx, - a.Tx * b.B + a.Ty * b.D + b.Ty); + a.A * b.B + a.B * b.D, + a.C * b.A + a.D * b.C, + a.C * b.B + a.D * b.D, + a.Tx * b.A + a.Ty * b.C + b.Tx, + a.Tx * b.B + a.Ty * b.D + b.Ty); #else #pragma warning disable CS0618 // Type or member is obsolete return new CGAffineTransform (a.xx * b.xx + a.yx * b.xy, @@ -388,11 +388,11 @@ public bool IsIdentity { { #if NET return new CGAffineTransform (a.A * b.A + a.B * b.C, - a.A * b.B + a.B * b.D, - a.C * b.A + a.D * b.C, - a.C * b.B + a.D * b.D, - a.Tx * b.A + a.Ty * b.C + b.Tx, - a.Tx * b.B + a.Ty * b.D + b.Ty); + a.A * b.B + a.B * b.D, + a.C * b.A + a.D * b.C, + a.C * b.B + a.D * b.D, + a.Tx * b.A + a.Ty * b.C + b.Tx, + a.Tx * b.B + a.Ty * b.D + b.Ty); #else return new CGAffineTransform (a.xx * b.xx + a.yx * b.xy, a.xx * b.yx + a.yx * b.yy, @@ -426,7 +426,7 @@ public CGPoint TransformPoint (CGPoint point) { #if NET return new CGPoint (A * point.X + C * point.Y + Tx, - B * point.X + D * point.Y + Ty); + B * point.X + D * point.Y + Ty); #else return new CGPoint (xx * point.X + xy * point.Y + x0, yx * point.X + yy * point.Y + y0); diff --git a/src/CoreGraphics/CGColorSpace.cs b/src/CoreGraphics/CGColorSpace.cs index c0eb87cfa104..54163367aa75 100644 --- a/src/CoreGraphics/CGColorSpace.cs +++ b/src/CoreGraphics/CGColorSpace.cs @@ -512,7 +512,7 @@ public byte [] GetColorTable () /* CGColorSpaceRef __nullable */ IntPtr alternate); #if NET - public static CGColorSpace? CreateIccProfile (nfloat[]? range, CGDataProvider profile, CGColorSpace alternate) + public static CGColorSpace? CreateIccProfile (nfloat []? range, CGDataProvider profile, CGColorSpace alternate) #else public static CGColorSpace? CreateICCProfile (nfloat []? range, CGDataProvider profile, CGColorSpace alternate) #endif diff --git a/src/CoreGraphics/CGDisplay.cs b/src/CoreGraphics/CGDisplay.cs index e526968846e1..d9afcb3d6ae3 100644 --- a/src/CoreGraphics/CGDisplay.cs +++ b/src/CoreGraphics/CGDisplay.cs @@ -6,8 +6,7 @@ using ObjCRuntime; using Foundation; -namespace CoreGraphics -{ +namespace CoreGraphics { #if NET [SupportedOSPlatform ("maccatalyst")] @@ -15,8 +14,7 @@ namespace CoreGraphics #else [MacCatalyst (13,1)] #endif - public enum CGCaptureOptions : uint - { + public enum CGCaptureOptions : uint { None = 0, NoFill = 1 << 0 } @@ -27,19 +25,18 @@ public enum CGCaptureOptions : uint #else [MacCatalyst (13,1)] #endif - public static class CGDisplay - { + public static class CGDisplay { #if !COREBUILD [DllImport (Constants.CoreGraphicsLibrary)] static extern uint CGMainDisplayID (); public static int MainDisplayID { get { - return (int)CGMainDisplayID (); + return (int) CGMainDisplayID (); } } - [DllImport (Constants.CoreGraphicsLibrary, EntryPoint="CGDisplayModeGetTypeID")] + [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGDisplayModeGetTypeID")] public static extern nint GetTypeID (); [DllImport (Constants.CoreGraphicsLibrary)] @@ -47,7 +44,7 @@ public static int MainDisplayID { public static CGRect GetBounds (int display) { - return CGDisplayBounds ((uint)display); + return CGDisplayBounds ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -55,7 +52,7 @@ public static CGRect GetBounds (int display) public static nint GetWidth (int display) { - return (nint)CGDisplayPixelsWide ((uint)display); + return (nint) CGDisplayPixelsWide ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -63,7 +60,7 @@ public static nint GetWidth (int display) public static nint GetHeight (int display) { - return (nint)CGDisplayPixelsHigh ((uint)display); + return (nint) CGDisplayPixelsHigh ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -71,7 +68,7 @@ public static nint GetHeight (int display) public static int SetDisplayTransfer (int display, float redMin, float redMax, float redGamma, float greenMin, float greenMax, float greenGamma, float blueMin, float blueMax, float blueGamma) { - return CGSetDisplayTransferByFormula ((uint)display, redMin, redMax, redGamma, greenMin, greenMax, greenGamma, blueMin, blueMax, blueGamma); + return CGSetDisplayTransferByFormula ((uint) display, redMin, redMax, redGamma, greenMin, greenMax, greenGamma, blueMin, blueMax, blueGamma); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -79,7 +76,7 @@ public static int SetDisplayTransfer (int display, float redMin, float redMax, f public static int GetGammaTableCapacity (int display) { - return (int)CGDisplayGammaTableCapacity ((uint)display); + return (int) CGDisplayGammaTableCapacity ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGDisplayRestoreColorSyncSettings")] @@ -98,7 +95,7 @@ public static int GetGammaTableCapacity (int display) public static bool IsCaptured (int display) { - return CGDisplayIsCaptured ((uint)display) != 0; + return CGDisplayIsCaptured ((uint) display) != 0; } [DllImport (Constants.CoreGraphicsLibrary)] @@ -106,7 +103,7 @@ public static bool IsCaptured (int display) public static int Capture (int display) { - return CGDisplayCapture ((uint)display); + return CGDisplayCapture ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -114,7 +111,7 @@ public static int Capture (int display) public static int Capture (int display, CGCaptureOptions options) { - return CGDisplayCaptureWithOptions ((uint)display, options); + return CGDisplayCaptureWithOptions ((uint) display, options); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -122,13 +119,13 @@ public static int Capture (int display, CGCaptureOptions options) public static int Release (int display) { - return CGDisplayRelease ((uint)display); + return CGDisplayRelease ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGCaptureAllDisplays")] public static extern int CaptureAllDisplays (); - [DllImport (Constants.CoreGraphicsLibrary, EntryPoint="CGCaptureAllDisplaysWithOptions")] + [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGCaptureAllDisplaysWithOptions")] static extern int CaptureAllDisplays (CGCaptureOptions options); @@ -140,7 +137,7 @@ public static int Release (int display) public static int HideCursor (int display) { - return CGDisplayHideCursor ((uint)display); + return CGDisplayHideCursor ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -148,7 +145,7 @@ public static int HideCursor (int display) public static int ShowCursor (int display) { - return CGDisplayShowCursor ((uint)display); + return CGDisplayShowCursor ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -156,7 +153,7 @@ public static int ShowCursor (int display) public static int MoveCursor (int display, CGPoint point) { - return CGDisplayMoveCursorToPoint ((uint)display, point); + return CGDisplayMoveCursorToPoint ((uint) display, point); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -164,7 +161,7 @@ public static int MoveCursor (int display, CGPoint point) public static int GetOpenGLDisplayMask (int display) { - return (int)CGDisplayIDToOpenGLDisplayMask ((uint)display); + return (int) CGDisplayIDToOpenGLDisplayMask ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -172,7 +169,7 @@ public static int GetOpenGLDisplayMask (int display) public static int GetDisplayID (int displayMask) { - return (int)CGOpenGLDisplayMaskToDisplayID ((uint)displayMask); + return (int) CGOpenGLDisplayMaskToDisplayID ((uint) displayMask); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -180,7 +177,7 @@ public static int GetDisplayID (int displayMask) public static int GetShieldingWindowID (int display) { - return (int)CGShieldingWindowID ((uint)display); + return (int) CGShieldingWindowID ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] diff --git a/src/CoreGraphics/CGEvent.cs b/src/CoreGraphics/CGEvent.cs index bdec2da8e97f..e13ead361bdc 100644 --- a/src/CoreGraphics/CGEvent.cs +++ b/src/CoreGraphics/CGEvent.cs @@ -70,10 +70,10 @@ public void Dispose () static IntPtr TapCallback (IntPtr tapProxyEvent, CGEventType eventType, IntPtr eventRef, IntPtr userInfo) { var gch = GCHandle.FromIntPtr (userInfo); - var tapData = (TapData)gch.Target!; + var tapData = (TapData) gch.Target!; return tapData.Callback (tapProxyEvent, eventType, eventRef, tapData.UserInfo); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static unsafe IntPtr CGEventTapCreate (CGEventTapLocation location, CGEventTapPlacement place, CGEventTapOptions options, CGEventMask mask, delegate* unmanaged cback, IntPtr data); #else @@ -126,7 +126,7 @@ static IntPtr TapCallback (IntPtr tapProxyEvent, CGEventType eventType, IntPtr e [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventTapCreateForPSN (IntPtr processSerialNumer, CGEventTapPlacement place, CGEventTapOptions options, CGEventMask mask, CGEventTapCallback cback, IntPtr data); #endif - + #if !XAMCORE_5_0 [Obsolete ("The location parameter is not used. Consider using the overload without the location parameter.", false)] [System.ComponentModel.EditorBrowsable (System.ComponentModel.EditorBrowsableState.Never)] @@ -193,14 +193,14 @@ static IntPtr Create (NSData source) return CGEventCreateFromData (IntPtr.Zero, source.Handle); } - public CGEvent (NSData source) + public CGEvent (NSData source) : base (Create (source), true) { } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventCreate (IntPtr eventSourceHandle); - + public CGEvent (CGEventSource? eventSource) : base (CGEventCreate (eventSource.GetHandle ()), true) { @@ -220,8 +220,8 @@ internal CGEvent (NativeHandle handle, bool owns) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - extern static IntPtr CGEventCreateMouseEvent(IntPtr source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton); - + extern static IntPtr CGEventCreateMouseEvent (IntPtr source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton); + public CGEvent (CGEventSource? source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton) : base (CGEventCreateMouseEvent (source.GetHandle (), mouseType, mouseCursorPosition, mouseButton), true) { @@ -297,8 +297,8 @@ public CGEvent Copy () return null; return new CGEventSource (esh, true); } - - + + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGPoint CGEventGetLocation (IntPtr handle); @@ -325,7 +325,7 @@ public CGPoint UnflippedLocation { // Keep this public, as we want to avoid creating instances of the object // just to peek at the flags - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetFlags")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetFlags")] public extern static CGEventFlags GetFlags (IntPtr eventHandle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] @@ -340,16 +340,16 @@ public CGEventFlags Flags { } } - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetIntegerValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetIntegerValueField")] extern static long GetLong (IntPtr eventHandle, CGEventField eventField); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSetIntegerValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSetIntegerValueField")] extern static void SetLong (IntPtr eventHandle, CGEventField eventField, long value); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetDoubleValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetDoubleValueField")] extern static double GetDouble (IntPtr eventHandle, CGEventField eventField); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSetDoubleValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSetDoubleValueField")] extern static void SetDouble (IntPtr eventHandle, CGEventField eventField, double value); /// Get the 64-bit integer value of the specified event field. @@ -468,7 +468,7 @@ public long MouseEventSubtype { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventSetSource (IntPtr handle, IntPtr source); - + public void SetEventSource (CGEventSource eventSource) { if (eventSource is null) @@ -477,11 +477,11 @@ public void SetEventSource (CGEventSource eventSource) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - extern static CGEventType CGEventGetType (IntPtr handle); + extern static CGEventType CGEventGetType (IntPtr handle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSetType (IntPtr handle, CGEventType evtType); - + public CGEventType EventType { get { return CGEventGetType (Handle); @@ -497,7 +497,7 @@ public CGEventType EventType { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSetTimestamp (IntPtr handle, ulong timeStampp); - + #if !NET [Obsolete ("Use 'Timestamp' instead.")] public ulong Timestampe { @@ -547,15 +547,15 @@ public static bool IsTapEnabled (CFMachPort machPort) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - unsafe extern static void CGEventKeyboardGetUnicodeString (IntPtr handle, nuint maxLen, nuint* actualLen, ushort *buffer); + unsafe extern static void CGEventKeyboardGetUnicodeString (IntPtr handle, nuint maxLen, nuint* actualLen, ushort* buffer); public unsafe string GetUnicodeString () { const int bufferLength = 40; - ushort *buffer = stackalloc ushort [bufferLength]; + ushort* buffer = stackalloc ushort [bufferLength]; nuint actual = 0; CGEventKeyboardGetUnicodeString (Handle, bufferLength, &actual, buffer); - return new String ((char *) buffer, 0, (int) actual); + return new String ((char*) buffer, 0, (int) actual); } #if NET @@ -585,10 +585,10 @@ public static void TapPostEven (IntPtr tapProxyEvent, CGEvent evt) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventTapPostEvent (tapProxyEvent, evt.Handle); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventPost (CGEventTapLocation location, IntPtr handle); @@ -596,7 +596,7 @@ public static void Post (CGEvent evt, CGEventTapLocation location) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventPost (location, evt.Handle); } @@ -609,7 +609,7 @@ public static void PostToPSN (CGEvent evt, IntPtr processSerialNumber) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventPostToPSN (processSerialNumber, evt.Handle); } @@ -637,11 +637,11 @@ public void PostToPid (int pid) { PostToPid (this, pid); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] unsafe extern static int /* CGError = int32_t */ CGGetEventTapList ( uint /* uint32_t */ maxNumberOfTaps, - CGEventTapInformation *tapList, + CGEventTapInformation* tapList, uint* /* uint32_t* */ eventTapCount); public unsafe CGEventTapInformation []? GetEventTapList () @@ -650,7 +650,7 @@ public void PostToPid (int pid) if (CGGetEventTapList (0, null, &count) != 0) return null; var result = new CGEventTapInformation [count]; - fixed (CGEventTapInformation *p = result){ + fixed (CGEventTapInformation* p = result) { if (CGGetEventTapList (count, p, &count) != 0) return null; } @@ -674,7 +674,7 @@ public void PostToPid (int pid) [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] #endif - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGRequestListenEventAccess")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGRequestListenEventAccess")] static extern byte CGRequestListenEventAccess (); #if NET diff --git a/src/CoreGraphics/CGEventSource.cs b/src/CoreGraphics/CGEventSource.cs index 44e47bbcb81f..e0e6f0e35fcf 100644 --- a/src/CoreGraphics/CGEventSource.cs +++ b/src/CoreGraphics/CGEventSource.cs @@ -50,7 +50,7 @@ public CGEventSource (NativeHandle handle, bool owns) [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventSourceCreate (CGEventSourceStateID stateID); - + public CGEventSource (CGEventSourceStateID stateID) : base (CGEventSourceCreate (stateID), true) { @@ -62,7 +62,7 @@ public CGEventSource (CGEventSourceStateID stateID) [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetKeyboardType (IntPtr handle, int /* CGEventSourceKeyboardType = uint32_t */ keyboardType); - public int KeyboardType { + public int KeyboardType { get { return CGEventSourceGetKeyboardType (Handle); } @@ -73,7 +73,7 @@ public int KeyboardType { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventSourceStateID CGEventSourceGetSourceStateID (IntPtr handle); - + public CGEventSourceStateID StateID { get { return CGEventSourceGetSourceStateID (Handle); @@ -86,7 +86,7 @@ public CGEventSourceStateID StateID { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetPixelsPerLine (IntPtr handle, double value); - + public double PixelsPerLine { get { return CGEventSourceGetPixelsPerLine (Handle); @@ -108,13 +108,13 @@ public static bool GetButtonState (CGEventSourceStateID stateID, CGMouseButton b public static bool GetKeyState (CGEventSourceStateID stateID, ushort keycode) => CGEventSourceKeyState (stateID, keycode) != 0; - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceFlagsState")] - public extern static CGEventFlags GetFlagsState (CGEventSourceStateID stateID); + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceFlagsState")] + public extern static CGEventFlags GetFlagsState (CGEventSourceStateID stateID); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceSecondsSinceLastEventType")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceSecondsSinceLastEventType")] public extern static double GetSecondsSinceLastEventType (CGEventSourceStateID stateID, CGEventType eventType); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceCounterForEventType")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceCounterForEventType")] public extern static uint /* uint32_t */ GetCounterForEventType (CGEventSourceStateID stateID, CGEventType eventType); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] @@ -140,7 +140,7 @@ public void SetLocalEventsFilterDuringSupressionState (CGEventFilterMask filter, { CGEventSourceSetLocalEventsFilterDuringSuppressionState (Handle, filter, state); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventFilterMask CGEventSourceGetLocalEventsFilterDuringSuppressionState (IntPtr handle, CGEventSuppressionState state); @@ -148,7 +148,7 @@ public CGEventFilterMask GetLocalEventsFilterDuringSupressionState (CGEventSuppr { return CGEventSourceGetLocalEventsFilterDuringSuppressionState (Handle, state); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetLocalEventsSuppressionInterval (IntPtr handle, double seconds); @@ -163,7 +163,7 @@ public double LocalEventsSupressionInterval { CGEventSourceSetLocalEventsSuppressionInterval (Handle, value); } } - + } } diff --git a/src/CoreGraphics/CGEventTypes.cs b/src/CoreGraphics/CGEventTypes.cs index 0dfe9dccc45e..2ccc52411296 100644 --- a/src/CoreGraphics/CGEventTypes.cs +++ b/src/CoreGraphics/CGEventTypes.cs @@ -56,7 +56,7 @@ public enum CGEventTapPlacement : uint { [MacCatalyst (13,1)] #endif public enum CGEventTapOptions : uint { - Default, + Default, ListenOnly, } @@ -94,22 +94,22 @@ public enum CGScrollEventUnit : uint { #endif [Flags] public enum CGEventMask : ulong { - Null = 0x00000001, - LeftMouseDown = 0x00000002, - LeftMouseUp = 0x00000004, - RightMouseDown = 0x00000008, - RightMouseUp = 0x00000010, - MouseMoved = 0x00000020, - LeftMouseDragged = 0x00000040, + Null = 0x00000001, + LeftMouseDown = 0x00000002, + LeftMouseUp = 0x00000004, + RightMouseDown = 0x00000008, + RightMouseUp = 0x00000010, + MouseMoved = 0x00000020, + LeftMouseDragged = 0x00000040, RightMouseDragged = 0x00000080, - KeyDown = 0x00000400, - KeyUp = 0x00000800, - FlagsChanged = 0x00001000, - ScrollWheel = 0x00400000, - TabletPointer = 0x00800000, - TabletProximity = 0x01000000, - OtherMouseDown = 0x02000000, - OtherMouseUp = 0x04000000, + KeyDown = 0x00000400, + KeyUp = 0x00000800, + FlagsChanged = 0x00001000, + ScrollWheel = 0x00400000, + TabletPointer = 0x00800000, + TabletProximity = 0x01000000, + OtherMouseDown = 0x02000000, + OtherMouseUp = 0x04000000, OtherMouseDragged = 0x08000000, } @@ -123,14 +123,14 @@ public enum CGEventMask : ulong { [Flags] public enum CGEventFlags : ulong { NonCoalesced = 0x00000100, - AlphaShift = 0x00010000, - Shift = 0x00020000, - Control = 0x00040000, - Alternate = 0x00080000, - Command = 0x00100000, - NumericPad = 0x00200000, - Help = 0x00400000, - SecondaryFn = 0x00800000, + AlphaShift = 0x00010000, + Shift = 0x00020000, + Control = 0x00040000, + Alternate = 0x00080000, + Command = 0x00100000, + NumericPad = 0x00200000, + Help = 0x00400000, + SecondaryFn = 0x00800000, } // CGEventTypes.h:typedef uint32_t CGEventField; @@ -482,7 +482,7 @@ public enum CGEventSuppressionState : int { RemoteMouseDrag, NumberOfEventSuppressionStates, } - + } #endif // MONOMAC diff --git a/src/CoreGraphics/CGImage.cs b/src/CoreGraphics/CGImage.cs index bb0ce4fde487..9453ae774b20 100644 --- a/src/CoreGraphics/CGImage.cs +++ b/src/CoreGraphics/CGImage.cs @@ -51,12 +51,12 @@ namespace CoreGraphics { #endif [Flags] public enum CGWindowImageOption : uint { - Default = 0, + Default = 0, BoundsIgnoreFraming = (1 << 0), - ShouldBeOpaque = (1 << 1), - OnlyShadows = (1 << 2), - BestResolution = (1 << 3), - NominalResolution = (1 << 4), + ShouldBeOpaque = (1 << 1), + OnlyShadows = (1 << 2), + BestResolution = (1 << 3), + NominalResolution = (1 << 4), } // uint32_t -> CGWindow.h (OSX SDK only) @@ -68,12 +68,12 @@ public enum CGWindowImageOption : uint { #endif [Flags] public enum CGWindowListOption : uint { - All = 0, - OnScreenOnly = (1 << 0), + All = 0, + OnScreenOnly = (1 << 0), OnScreenAboveWindow = (1 << 1), OnScreenBelowWindow = (1 << 2), - IncludingWindow = (1 << 3), - ExcludeDesktopElements = (1 << 4) + IncludingWindow = (1 << 3), + ExcludeDesktopElements = (1 << 4) } #endif @@ -264,8 +264,8 @@ public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, i [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use ScreenCaptureKit instead.")] #endif [DllImport (Constants.CoreGraphicsLibrary)] - static extern IntPtr CGWindowListCreateImage(CGRect screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption); - + static extern IntPtr CGWindowListCreateImage (CGRect screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption); + #if NET [SupportedOSPlatform ("maccatalyst")] [ObsoletedOSPlatform ("maccatalyst18.0", "Use ScreenCaptureKit instead.")] diff --git a/src/CoreGraphics/CGPattern.cs b/src/CoreGraphics/CGPattern.cs index 791131f63a40..07a187fd53f3 100644 --- a/src/CoreGraphics/CGPattern.cs +++ b/src/CoreGraphics/CGPattern.cs @@ -102,7 +102,8 @@ unsafe extern static IntPtr CGPatternCreate (/* void* */ IntPtr info, CGRect bou #if NET static CGPatternCallbacks callbacks; - static CGPattern () { + static CGPattern () + { unsafe { callbacks = new CGPatternCallbacks () { version = 0, diff --git a/src/CoreGraphics/CGVector.cs b/src/CoreGraphics/CGVector.cs index 4972a0fcee7b..45ec779f1ca1 100644 --- a/src/CoreGraphics/CGVector.cs +++ b/src/CoreGraphics/CGVector.cs @@ -93,7 +93,7 @@ public override bool Equals (object? other) #endif [DllImport (Constants.UIKitLibrary)] extern static IntPtr NSStringFromCGVector (CGVector vector); - + #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -113,7 +113,7 @@ public override bool Equals (object? other) #endif [DllImport (Constants.UIKitLibrary)] extern static CGVector CGVectorFromString (IntPtr str); - + #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] diff --git a/src/CoreImage/Enums.cs b/src/CoreImage/Enums.cs index 60941bb22369..4b5ab1a56943 100644 --- a/src/CoreImage/Enums.cs +++ b/src/CoreImage/Enums.cs @@ -53,7 +53,7 @@ public enum CIFormat { #if MONOMAC RGBA16 = 2, [Obsolete ("This value can not be shared across Mac/iOS binaries, future proof with kRGBAf instead.")] - RGBAf = 3, + RGBAf = 3, // Please, do not add values into MonoMac/iOS without adding an explicit value #endif diff --git a/src/CoreLocation/CLLocationManager.cs b/src/CoreLocation/CLLocationManager.cs index e3e39e3ff36a..930268432daa 100644 --- a/src/CoreLocation/CLLocationManager.cs +++ b/src/CoreLocation/CLLocationManager.cs @@ -45,7 +45,7 @@ public partial class CLLocationManager : NSObject { #if IOS public static bool IsMonitoringAvailable (Type t) { - if (SystemVersion.CheckiOS (7,0)) + if (SystemVersion.CheckiOS (7, 0)) return IsMonitoringAvailable (new Class (t)); return false; } diff --git a/src/CoreMedia/CMSampleBuffer.cs b/src/CoreMedia/CMSampleBuffer.cs index dd2cd47b4d63..c113833aae73 100644 --- a/src/CoreMedia/CMSampleBuffer.cs +++ b/src/CoreMedia/CMSampleBuffer.cs @@ -168,7 +168,7 @@ unsafe static extern OSStatus CMSampleBufferCreateCopyWithNewTiming ( unsafe static extern CMSampleBufferError CMSampleBufferCallForEachSample ( /* CMSampleBufferRef */ IntPtr sbuf, #if NET - delegate* unmanaged callback, + delegate* unmanaged callback, #else CMSampleBufferCallForEachSampleCallback callback, #endif @@ -663,7 +663,7 @@ public CMSampleBufferError SetInvalidateCallback (Action invalid #if NET unsafe { #endif - return CMSampleBufferSetInvalidateCallback (Handle, null, 0); + return CMSampleBufferSetInvalidateCallback (Handle, null, 0); #if NET } #endif @@ -678,7 +678,7 @@ public CMSampleBufferError SetInvalidateCallback (Action invalid invalidate = GCHandle.Alloc (Tuple.Create (invalidateHandler, this)); #if NET unsafe { - return CMSampleBufferSetInvalidateCallback (Handle, &InvalidateHandler, (ulong)(IntPtr)invalidate); + return CMSampleBufferSetInvalidateCallback (Handle, &InvalidateHandler, (ulong) (IntPtr) invalidate); } #else return CMSampleBufferSetInvalidateCallback (Handle, invalidate_handler, (ulong) (IntPtr) invalidate); diff --git a/src/CoreMidi/MidiBluetoothDriver.cs b/src/CoreMidi/MidiBluetoothDriver.cs index f74cc15aa2b7..3bc6de0f656d 100644 --- a/src/CoreMidi/MidiBluetoothDriver.cs +++ b/src/CoreMidi/MidiBluetoothDriver.cs @@ -23,10 +23,10 @@ namespace CoreMidi { #if NET - [SupportedOSPlatform ("ios16.0")] - [SupportedOSPlatform ("maccatalyst16.0")] - [SupportedOSPlatform ("tvos16.0")] - [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("tvos16.0")] + [SupportedOSPlatform ("macos13.0")] #else [iOS (16, 0), Mac (13, 0), TV (16, 0), MacCatalyst (16, 0)] #endif // NET diff --git a/src/CoreServices/FSEvents.cs b/src/CoreServices/FSEvents.cs index aed8dc85b289..e0a55724352d 100644 --- a/src/CoreServices/FSEvents.cs +++ b/src/CoreServices/FSEvents.cs @@ -18,12 +18,11 @@ using CoreFoundation; using Foundation; -namespace CoreServices -{ +namespace CoreServices { // FSEvents.h: typedef UInt32 FSEventStreamCreateFlags; [Flags] public enum FSEventStreamCreateFlags : uint { - None = 0x00000000, + None = 0x00000000, /*UseCFTypes = 0x00000001,*/ NoDefer = 0x00000002, WatchRoot = 0x00000004, @@ -66,7 +65,7 @@ public enum FSEventStreamEventFlags : uint { ItemIsFile = 0x00010000, ItemIsDir = 0x00020000, ItemIsSymlink = 0x00040000, - OwnEvent = 0x00080000, + OwnEvent = 0x00080000, ItemIsHardlink = 0x00100000, ItemIsLastHardlink = 0x00200000, #if NET @@ -78,8 +77,7 @@ public enum FSEventStreamEventFlags : uint { #if NET [SupportedOSPlatform ("macos")] #endif - public struct FSEvent - { + public struct FSEvent { public ulong Id { get; internal set; } public string? Path { get; internal set; } public FSEventStreamEventFlags Flags { get; internal set; } @@ -151,8 +149,7 @@ struct FSEventStreamContext { #if NET [SupportedOSPlatform ("macos")] #endif - public sealed class FSEventStreamEventsArgs : EventArgs - { + public sealed class FSEventStreamEventsArgs : EventArgs { public FSEvent [] Events { get; private set; } internal FSEventStreamEventsArgs (FSEvent [] events) @@ -167,8 +164,7 @@ internal FSEventStreamEventsArgs (FSEvent [] events) #if NET [SupportedOSPlatform ("macos")] #endif - public sealed class FSEventStreamCreateOptions - { + public sealed class FSEventStreamCreateOptions { /// /// The allocator to use to allocate memory for the stream. If null, the default /// allocator will be used. @@ -243,8 +239,7 @@ public FSEventStreamCreateOptions (FSEventStreamCreateFlags flags, TimeSpan late #if NET [SupportedOSPlatform ("macos")] #endif - public class FSEventStream : NativeObject - { + public class FSEventStream : NativeObject { [DllImport (Constants.CoreServicesLibrary)] static extern void FSEventStreamRetain (IntPtr handle); @@ -317,7 +312,7 @@ public FSEventStream (FSEventStreamCreateOptions options) var allocator = options.Allocator.GetHandle (); var sinceWhenId = options.SinceWhenId ?? FSEvent.SinceNowId; var latency = options.Latency.TotalSeconds; - var flags = options.Flags |= (FSEventStreamCreateFlags)0x1 /* UseCFTypes */; + var flags = options.Flags |= (FSEventStreamCreateFlags) 0x1 /* UseCFTypes */; IntPtr handle; unsafe { @@ -403,7 +398,7 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, return; } - var events = new FSEvent[numEvents]; + var events = new FSEvent [numEvents]; for (int i = 0; i < events.Length; i++) { string? path = null; @@ -415,7 +410,7 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, if (eventDataType == CFStringTypeID) { path = CFString.FromHandle (eventDataHandle); } else if (eventDataType == CFDictionaryTypeID) { - path = CFString.FromHandle (CFDictionary.GetValue ( + path = CFString.FromHandle (CFDictionary.GetValue ( eventDataHandle, kFSEventStreamEventExtendedDataPathKey.Handle)); @@ -429,12 +424,11 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, } } - events[i] = new FSEvent - { - Id = (ulong)Marshal.ReadInt64 (eventIds, i * 8), + events [i] = new FSEvent { + Id = (ulong) Marshal.ReadInt64 (eventIds, i * 8), Path = path, - Flags = (FSEventStreamEventFlags)(uint)Marshal.ReadInt32 (eventFlags, i * 4), - FileId = (ulong)fileId, + Flags = (FSEventStreamEventFlags) (uint) Marshal.ReadInt32 (eventFlags, i * 4), + FileId = (ulong) fileId, }; } diff --git a/src/CoreServices/LaunchServices.cs b/src/CoreServices/LaunchServices.cs index 8bc434315164..d19a890f7423 100644 --- a/src/CoreServices/LaunchServices.cs +++ b/src/CoreServices/LaunchServices.cs @@ -30,8 +30,7 @@ using Foundation; using ObjCRuntime; -namespace CoreServices -{ +namespace CoreServices { [Flags] public enum LSRoles/*Mask*/ : uint /* always 32-bit uint */ { @@ -49,8 +48,7 @@ public enum LSAcceptanceFlags : uint /* always 32-bit uint */ AllowLoginUI = 2 } - public enum LSResult - { + public enum LSResult { Success = 0, #if NET [SupportedOSPlatform ("macos13.0")] @@ -89,9 +87,8 @@ public enum LSResult #if NET [SupportedOSPlatform ("macos")] #endif - public static class LaunchServices - { -#region Locating an Application + public static class LaunchServices { + #region Locating an Application #if NET [SupportedOSPlatform ("macos")] @@ -221,19 +218,19 @@ public static NSUrl [] GetApplicationUrlsForBundleIdentifier (string bundleIdent ); } -#endregion + #endregion -#region Opening Items + #region Opening Items [DllImport (Constants.CoreServicesLibrary)] - unsafe static extern LSResult LSOpenCFURLRef (IntPtr inUrl, void **outLaunchedUrl); + unsafe static extern LSResult LSOpenCFURLRef (IntPtr inUrl, void** outLaunchedUrl); public unsafe static LSResult Open (NSUrl url) { if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - return LSOpenCFURLRef (url.Handle, (void **)0); + return LSOpenCFURLRef (url.Handle, (void**) 0); } public unsafe static LSResult Open (NSUrl url, out NSUrl? launchedUrl) @@ -241,15 +238,15 @@ public unsafe static LSResult Open (NSUrl url, out NSUrl? launchedUrl) if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - void *launchedUrlHandle; + void* launchedUrlHandle; var result = LSOpenCFURLRef (url.Handle, &launchedUrlHandle); launchedUrl = Runtime.GetNSObject (new IntPtr (launchedUrlHandle)); return result; } -#endregion + #endregion -#region Registering an Application + #region Registering an Application [DllImport (Constants.CoreServicesLibrary)] static extern LSResult LSRegisterURL (IntPtr inUrl, byte inUpdate); @@ -259,12 +256,12 @@ public static LSResult Register (NSUrl url, bool update) if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - return LSRegisterURL (url.Handle, (byte)(update ? 1 : 0)); + return LSRegisterURL (url.Handle, (byte) (update ? 1 : 0)); } -#endregion + #endregion -#region Working with Role Handlers + #region Working with Role Handlers #if NET [SupportedOSPlatform ("macos")] @@ -281,7 +278,7 @@ public static LSResult Register (NSUrl url, bool update) #else [Deprecated (PlatformName.MacOSX, 14, 0)] #endif - public static string?[]? GetAllRoleHandlersForContentType (string contentType, LSRoles roles = LSRoles.All) + public static string? []? GetAllRoleHandlersForContentType (string contentType, LSRoles roles = LSRoles.All) { if (contentType is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (contentType)); @@ -311,7 +308,7 @@ public static string GetDefaultRoleHandlerForContentType (string contentType, LS if (contentType is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (contentType)); - return (string)Runtime.GetNSObject ( + return (string) Runtime.GetNSObject ( LSCopyDefaultRoleHandlerForContentType (new NSString (contentType).Handle, roles) ); } @@ -363,7 +360,7 @@ public static LSResult SetDefaultRoleHandlerForContentType (string contentType, #else [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'GetApplicationUrlsForUrl' instead.")] #endif - public static string?[]? GetAllHandlersForUrlScheme (string urlScheme) + public static string? []? GetAllHandlersForUrlScheme (string urlScheme) { if (urlScheme is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (urlScheme)); @@ -393,7 +390,7 @@ public static string GetDefaultHandlerForUrlScheme (string urlScheme) if (urlScheme is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (urlScheme)); - return (string)Runtime.GetNSObject ( + return (string) Runtime.GetNSObject ( LSCopyDefaultHandlerForURLScheme (new NSString (urlScheme).Handle) ); } @@ -426,7 +423,7 @@ public static LSResult SetDefaultHandlerForUrlScheme (string urlScheme, string h ); } -#endregion + #endregion } } diff --git a/src/CoreSpotlight/CSSearchableIndex.cs b/src/CoreSpotlight/CSSearchableIndex.cs index 3886817384de..0b0a04696d38 100644 --- a/src/CoreSpotlight/CSSearchableIndex.cs +++ b/src/CoreSpotlight/CSSearchableIndex.cs @@ -21,7 +21,7 @@ public partial class CSSearchableIndex { // Strongly typed version of initWithName:protectionClass: public CSSearchableIndex (string name, CSFileProtection protectionOption = CSFileProtection.None) : this (name, Translate (protectionOption)) - {} + { } static NSString? Translate (CSFileProtection protectionOption) { diff --git a/src/CoreSpotlight/CSSearchableItemAttributeSet.cs b/src/CoreSpotlight/CSSearchableItemAttributeSet.cs index 44fc02577858..5efd455a0e95 100644 --- a/src/CoreSpotlight/CSSearchableItemAttributeSet.cs +++ b/src/CoreSpotlight/CSSearchableItemAttributeSet.cs @@ -28,10 +28,11 @@ public INSSecureCoding? this [CSCustomAttributeKey key] { [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] #endif - public bool? IsUserCreated { + public bool? IsUserCreated { get { return _IsUserCreated?.BoolValue; - } set { + } + set { _IsUserCreated = value.HasValue ? new NSNumber (value.Value) : null; } } @@ -45,7 +46,8 @@ public bool? IsUserCreated { public bool? IsUserOwned { get { return _IsUserOwned?.BoolValue; - } set { + } + set { _IsUserOwned = value.HasValue ? new NSNumber (value.Value) : null; } } @@ -56,10 +58,11 @@ public bool? IsUserOwned { [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] #endif - public bool? IsUserCurated { + public bool? IsUserCurated { get { return _IsUserCurated?.BoolValue; - } set { + } + set { _IsUserCurated = value.HasValue ? new NSNumber (value.Value) : null; } } diff --git a/src/CoreText/CTFontCollection.cs b/src/CoreText/CTFontCollection.cs index 89154017f8f4..c3e5dfec1c72 100644 --- a/src/CoreText/CTFontCollection.cs +++ b/src/CoreText/CTFontCollection.cs @@ -191,7 +191,7 @@ public CTFontDescriptor [] GetMatchingFontDescriptors (CTFontCollectionOptions? #if NET [DllImport (Constants.CoreTextLibrary)] static unsafe extern IntPtr CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback ( - IntPtr collection, delegate* unmanaged sortCallback, + IntPtr collection, delegate* unmanaged sortCallback, IntPtr refCon); #else [DllImport (Constants.CoreTextLibrary)] diff --git a/src/CoreText/CTFontManager.cs b/src/CoreText/CTFontManager.cs index e9150b2970d3..7fc1b47f49db 100644 --- a/src/CoreText/CTFontManager.cs +++ b/src/CoreText/CTFontManager.cs @@ -666,7 +666,7 @@ public unsafe static void UnregisterFontDescriptors (CTFontDescriptor [] fontDes [NoTV] [NoMac] #endif - public static CTFontDescriptor[]? GetRegisteredFontDescriptors (CTFontManagerScope scope, bool enabled) + public static CTFontDescriptor []? GetRegisteredFontDescriptors (CTFontManagerScope scope, bool enabled) { var p = CTFontManagerCopyRegisteredFontDescriptors (scope, enabled.AsByte ()); // Copy/Create rule - we must release the CFArrayRef @@ -746,7 +746,7 @@ public unsafe static void UnregisterFontDescriptors (CTFontDescriptor [] fontDes [iOS (13,0)] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public unsafe static void RegisterFonts (string[] assetNames, CFBundle bundle, CTFontManagerScope scope, bool enabled, CTFontRegistrationHandler registrationHandler) + public unsafe static void RegisterFonts (string [] assetNames, CFBundle bundle, CTFontManagerScope scope, bool enabled, CTFontRegistrationHandler registrationHandler) { using (var arr = EnsureNonNullArray (assetNames, nameof (assetNames))) { if (registrationHandler is null) { @@ -774,7 +774,7 @@ public unsafe static void RegisterFonts (string[] assetNames, CFBundle bundle, C [NoMac] [iOS (13,0)] #endif - public delegate void CTFontManagerRequestFontsHandler (CTFontDescriptor[] unresolvedFontDescriptors); + public delegate void CTFontManagerRequestFontsHandler (CTFontDescriptor [] unresolvedFontDescriptors); #if NET [SupportedOSPlatform ("ios13.0")] @@ -817,7 +817,7 @@ static unsafe void TrampolineRequestFonts (IntPtr block, /* CFArray */ IntPtr fo [iOS (13,0)] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public static void RequestFonts (CTFontDescriptor[] fontDescriptors, CTFontManagerRequestFontsHandler completionHandler) + public static void RequestFonts (CTFontDescriptor [] fontDescriptors, CTFontManagerRequestFontsHandler completionHandler) { if (completionHandler is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (completionHandler)); diff --git a/src/CoreVideo/CVBuffer.cs b/src/CoreVideo/CVBuffer.cs index 8eebf4912d78..35284bd03ef8 100644 --- a/src/CoreVideo/CVBuffer.cs +++ b/src/CoreVideo/CVBuffer.cs @@ -148,7 +148,7 @@ unsafe static IntPtr CVBufferCopyAttachment (IntPtr buffer, IntPtr key, out CVAt #if IOS || __MACCATALYST__ || TVOS if (SystemVersion.CheckiOS (15, 0)) #endif - return Runtime.GetINativeObject (CVBufferCopyAttachment (Handle, key.Handle, out attachmentMode), true); + return Runtime.GetINativeObject (CVBufferCopyAttachment (Handle, key.Handle, out attachmentMode), true); return Runtime.GetINativeObject (CVBufferGetAttachment (Handle, key.Handle, out attachmentMode), false); } #else @@ -201,7 +201,7 @@ unsafe static IntPtr CVBufferCopyAttachment (IntPtr buffer, IntPtr key, out CVAt #elif MONOMAC if (SystemVersion.CheckmacOS (12, 0)) #endif - return Runtime.GetINativeObject (CVBufferCopyAttachments (Handle, attachmentMode), true); + return Runtime.GetINativeObject (CVBufferCopyAttachments (Handle, attachmentMode), true); return Runtime.GetNSObject (CVBufferGetAttachments (Handle, attachmentMode), false); } diff --git a/src/CoreVideo/CVDisplayLink.cs b/src/CoreVideo/CVDisplayLink.cs index b8059e928234..a0572e325594 100644 --- a/src/CoreVideo/CVDisplayLink.cs +++ b/src/CoreVideo/CVDisplayLink.cs @@ -47,7 +47,7 @@ namespace CoreVideo { #endif public class CVDisplayLink : NativeObject { GCHandle callbackHandle; - + #if !NET public CVDisplayLink (NativeHandle handle) : base (handle, false, true) @@ -55,7 +55,7 @@ public CVDisplayLink (NativeHandle handle) } #endif - [Preserve (Conditional=true)] + [Preserve (Conditional = true)] internal CVDisplayLink (NativeHandle handle, bool owns) : base (handle, owns) { @@ -140,7 +140,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) [NoTV] [NoMacCatalyst] #endif - public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds, out CVReturn error) + public static CVDisplayLink? CreateFromDisplayIds (uint [] displayIds, out CVReturn error) { if (displayIds is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (displayIds)); @@ -168,7 +168,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) [NoTV] [NoMacCatalyst] #endif - public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds) + public static CVDisplayLink? CreateFromDisplayIds (uint [] displayIds) => CreateFromDisplayIds (displayIds, out var _); #if NET @@ -230,7 +230,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) #endif [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRetain (IntPtr handle); - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -239,7 +239,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) #endif [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRelease (IntPtr handle); - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -265,7 +265,7 @@ protected internal override void Release () protected override void Dispose (bool disposing) { if (callbackHandle.IsAllocated) { - callbackHandle.Free(); + callbackHandle.Free (); } base.Dispose (disposing); @@ -310,7 +310,7 @@ static IntPtr Create () public CVDisplayLink () : base (Create (), true) { - } + } #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] @@ -330,8 +330,8 @@ public CVDisplayLink () public CVReturn SetCurrentDisplay (int displayId) { return CVDisplayLinkSetCurrentCGDisplay (Handle, displayId); - } - + } + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -350,7 +350,7 @@ public CVReturn SetCurrentDisplay (int displayId) public CVReturn SetCurrentDisplay (CGLContext cglContext, CGLPixelFormat cglPixelFormat) { return CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext (Handle, cglContext.Handle, cglPixelFormat.Handle); - } + } #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] @@ -371,7 +371,7 @@ public int GetCurrentDisplay () { return CVDisplayLinkGetCurrentCGDisplay (Handle); } - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -390,8 +390,8 @@ public int GetCurrentDisplay () public CVReturn Start () { return CVDisplayLinkStart (Handle); - } - + } + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -410,8 +410,8 @@ public CVReturn Start () public CVReturn Stop () { return CVDisplayLinkStop (Handle); - } - + } + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -474,7 +474,7 @@ public double ActualOutputVideoRefreshPeriod { return CVDisplayLinkGetActualOutputVideoRefreshPeriod (Handle); } } - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -495,7 +495,7 @@ public bool IsRunning { return CVDisplayLinkIsRunning (Handle) != 0; } } - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -516,15 +516,15 @@ public CVReturn GetCurrentTime (out CVTimeStamp outTime) CVReturn ret; outTime = default; unsafe { - ret = CVDisplayLinkGetCurrentTime (this.Handle, (CVTimeStamp *) Unsafe.AsPointer (ref outTime)); + ret = CVDisplayLinkGetCurrentTime (this.Handle, (CVTimeStamp*) Unsafe.AsPointer (ref outTime)); } - + return ret; } - - public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut); - delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext); - + + public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut); + delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext); + #if NET [UnmanagedCallersOnly] static unsafe CVReturn OutputCallback (IntPtr displayLink, CVTimeStamp* inNow, CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, IntPtr displayLinkContext) @@ -538,7 +538,7 @@ static CVReturn OutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref C { GCHandle callbackHandle = GCHandle.FromIntPtr (displayLinkContext); DisplayLinkOutputCallback func = (DisplayLinkOutputCallback) callbackHandle.Target!; - CVDisplayLink delegateDisplayLink = new CVDisplayLink(displayLink, false); + CVDisplayLink delegateDisplayLink = new CVDisplayLink (displayLink, false); #if NET return func (delegateDisplayLink, ref System.Runtime.CompilerServices.Unsafe.AsRef (inNow), @@ -553,7 +553,7 @@ ref System.Runtime.CompilerServices.Unsafe.AsRef (inOutputTime), [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] - extern static unsafe CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, delegate* unmanaged function, IntPtr userInfo); + extern static unsafe CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, delegate* unmanaged function, IntPtr userInfo); #else [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [DllImport (Constants.CoreVideoLibrary)] @@ -578,7 +578,7 @@ public CVReturn SetOutputCallback (DisplayLinkOutputCallback callback) CVReturn ret = CVDisplayLinkSetOutputCallback (this.Handle, static_OutputCallback, GCHandle.ToIntPtr (callbackHandle)); return ret; #endif - + } #if NET @@ -641,7 +641,7 @@ public static nuint GetTypeId () public bool TryTranslateTime (CVTimeStamp inTime, ref CVTimeStamp outTime) { unsafe { - return CVDisplayLinkTranslateTime (this.Handle, inTime, (CVTimeStamp *) Unsafe.AsPointer (ref outTime)) == 0; + return CVDisplayLinkTranslateTime (this.Handle, inTime, (CVTimeStamp*) Unsafe.AsPointer (ref outTime)) == 0; } } } diff --git a/src/CoreVideo/CVImageBuffer.cs b/src/CoreVideo/CVImageBuffer.cs index 063924e77237..1506ee1b39b8 100644 --- a/src/CoreVideo/CVImageBuffer.cs +++ b/src/CoreVideo/CVImageBuffer.cs @@ -95,7 +95,7 @@ public bool IsFlipped { #if MONOMAC [DllImport (Constants.CoreVideoLibrary)] extern static /* CGColorSpaceRef */ IntPtr CVImageBufferGetColorSpace (/* CVImageBufferRef */ IntPtr imageBuffer); - + #if NET [UnsupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] diff --git a/src/CoreVideo/CVPixelFormatDescription.cs b/src/CoreVideo/CVPixelFormatDescription.cs index 2011de0dd91c..3c5b07b6a863 100644 --- a/src/CoreVideo/CVPixelFormatDescription.cs +++ b/src/CoreVideo/CVPixelFormatDescription.cs @@ -329,7 +329,7 @@ public CVFillExtendedPixelsCallBackDataStruct? FillExtendedPixelsCallbackStruct unsafe { if (bytes.Length < sizeof (CVFillExtendedPixelsCallBackDataStruct)) throw new InvalidOperationException ($"The size of the callback data structure is smaller than expected (got {bytes.Length} bytes, expected at least {sizeof (CVFillExtendedPixelsCallBackDataStruct)} bytes)"); - fixed (byte *ptr = bytes) + fixed (byte* ptr = bytes) return Marshal.PtrToStructure ((IntPtr) ptr); } } diff --git a/src/Darwin/KernelNotification.cs b/src/Darwin/KernelNotification.cs index 74234fedb2c9..96ebcc87bc17 100644 --- a/src/Darwin/KernelNotification.cs +++ b/src/Darwin/KernelNotification.cs @@ -57,24 +57,24 @@ public struct KernelEvent { [Flags] public enum EventFlags : ushort { - Add = 0x0001, - Delete = 0x0002, - Enable = 0x0004, - Disable = 0x0008, - OneShot = 0x0010, - Clear = 0x0020, - Receipt = 0x0040, - Dispatch = 0x0080, - - Flag0 = 0x1000, - Flag1 = 0x2000, - SystemFlags = unchecked (0xf000), - + Add = 0x0001, + Delete = 0x0002, + Enable = 0x0004, + Disable = 0x0008, + OneShot = 0x0010, + Clear = 0x0020, + Receipt = 0x0040, + Dispatch = 0x0080, + + Flag0 = 0x1000, + Flag1 = 0x2000, + SystemFlags = unchecked(0xf000), + // Return values. - EOF = 0x8000, - Error = 0x4000, + EOF = 0x8000, + Error = 0x4000, } - + public enum EventFilter : short { Read = -1, Write = -2, @@ -88,60 +88,60 @@ public enum EventFilter : short { User = -10, VM = -11 } - + [Flags] public enum FilterFlags : uint { - ReadPoll = EventFlags.Flag0, - ReadOutOfBand = EventFlags.Flag1, - ReadLowWaterMark = 0x00000001, + ReadPoll = EventFlags.Flag0, + ReadOutOfBand = EventFlags.Flag1, + ReadLowWaterMark = 0x00000001, WriteLowWaterMark = ReadLowWaterMark, - NoteTrigger = 0x01000000, - NoteFFNop = 0x00000000, - NoteFFAnd = 0x40000000, - NoteFFOr = 0x80000000, - NoteFFCopy = 0xc0000000, - NoteFFCtrlMask = 0xc0000000, - NoteFFlagsMask = 0x00ffffff, - - VNodeDelete = 0x00000001, - VNodeWrite = 0x00000002, - VNodeExtend = 0x00000004, - VNodeAttrib = 0x00000008, - VNodeLink = 0x00000010, - VNodeRename = 0x00000020, - VNodeRevoke = 0x00000040, - VNodeNone = 0x00000080, - - ProcExit = 0x80000000, - ProcFork = 0x40000000, - ProcExec = 0x20000000, - ProcReap = 0x10000000, - ProcSignal = 0x08000000, - ProcExitStatus = 0x04000000, - ProcResourceEnd = 0x02000000, + NoteTrigger = 0x01000000, + NoteFFNop = 0x00000000, + NoteFFAnd = 0x40000000, + NoteFFOr = 0x80000000, + NoteFFCopy = 0xc0000000, + NoteFFCtrlMask = 0xc0000000, + NoteFFlagsMask = 0x00ffffff, + + VNodeDelete = 0x00000001, + VNodeWrite = 0x00000002, + VNodeExtend = 0x00000004, + VNodeAttrib = 0x00000008, + VNodeLink = 0x00000010, + VNodeRename = 0x00000020, + VNodeRevoke = 0x00000040, + VNodeNone = 0x00000080, + + ProcExit = 0x80000000, + ProcFork = 0x40000000, + ProcExec = 0x20000000, + ProcReap = 0x10000000, + ProcSignal = 0x08000000, + ProcExitStatus = 0x04000000, + ProcResourceEnd = 0x02000000, // iOS only - ProcAppactive = 0x00800000, + ProcAppactive = 0x00800000, ProcAppBackground = 0x00400000, - ProcAppNonUI = 0x00200000, - ProcAppInactive = 0x00100000, - ProcAppAllStates = 0x00f00000, + ProcAppNonUI = 0x00200000, + ProcAppInactive = 0x00100000, + ProcAppAllStates = 0x00f00000, // Masks - ProcPDataMask = 0x000fffff, - ProcControlMask = 0xfff00000, + ProcPDataMask = 0x000fffff, + ProcControlMask = 0xfff00000, - VMPressure = 0x80000000, + VMPressure = 0x80000000, VMPressureTerminate = 0x40000000, VMPressureSuddenTerminate = 0x20000000, - VMError = 0x10000000, + VMError = 0x10000000, - TimerSeconds = 0x00000001, - TimerMicroSeconds = 0x00000002, - TimerNanoSeconds = 0x00000004, - TimerAbsolute = 0x00000008, + TimerSeconds = 0x00000001, + TimerMicroSeconds = 0x00000002, + TimerNanoSeconds = 0x00000004, + TimerAbsolute = 0x00000008, } public class KernelQueue : IDisposable, INativeObject { @@ -167,19 +167,19 @@ public void Dispose () { Dispose (false); } - + protected virtual void Dispose (bool disposing) { - if (handle != -1){ + if (handle != -1) { DispatchSource.VnodeMonitor.close (handle); handle = -1; } } [DllImport (Constants.SystemLibrary)] - unsafe extern static int /* int */ kevent (int kq, KernelEvent *changeList, int /* int */ nChanges, KernelEvent *eventList, int /* int */ nEvents, TimeSpec* timeout); + unsafe extern static int /* int */ kevent (int kq, KernelEvent* changeList, int /* int */ nChanges, KernelEvent* eventList, int /* int */ nEvents, TimeSpec* timeout); - public int KEvent (KernelEvent[] changeList, KernelEvent[] eventList, TimeSpan? timeout = null) + public int KEvent (KernelEvent [] changeList, KernelEvent [] eventList, TimeSpan? timeout = null) { if (changeList is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (changeList)); @@ -196,7 +196,7 @@ public int KEvent (KernelEvent[] changeList, KernelEvent[] eventList, TimeSpan? return KEvent (changeList, changeList.Length, eventList, eventList.Length, ToTimespec (timeout)); } - public unsafe int KEvent (KernelEvent[] changeList, int nChanges, KernelEvent[] eventList, int nEvents, TimeSpec? timeout = null) + public unsafe int KEvent (KernelEvent [] changeList, int nChanges, KernelEvent [] eventList, int nEvents, TimeSpec? timeout = null) { if (changeList is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (changeList)); @@ -217,15 +217,15 @@ public unsafe int KEvent (KernelEvent[] changeList, int nChanges, KernelEvent[] throw new ArgumentOutOfRangeException ("nEvents is larger than the number of elements in eventList", nameof (nEvents)); unsafe { - fixed (KernelEvent *cp = changeList) - fixed (KernelEvent *ep = eventList) { - if (timeout is null) { - return kevent (handle, cp, nChanges, ep, nEvents, null); - } else { - TimeSpec ts = timeout.Value; - return kevent (handle, cp, nChanges, ep, nEvents, &ts); - } + fixed (KernelEvent* cp = changeList) + fixed (KernelEvent* ep = eventList) { + if (timeout is null) { + return kevent (handle, cp, nChanges, ep, nEvents, null); + } else { + TimeSpec ts = timeout.Value; + return kevent (handle, cp, nChanges, ep, nEvents, &ts); } + } } } @@ -240,7 +240,7 @@ public unsafe int KEvent (KernelEvent[] changeList, int nChanges, KernelEvent[] return rv; } -// Don't worry about nullability for !NET + // Don't worry about nullability for !NET #nullable disable #if !NET [Obsolete ("Use any of the overloads that return an int to get how many events were returned from kevent.")] @@ -295,10 +295,10 @@ public bool KEvent (KernelEvent [] changeList, KernelEvent [] eventList) #endif { unsafe { - fixed (KernelEvent *cp = changeList) - fixed (KernelEvent *ep = eventList) + fixed (KernelEvent* cp = changeList) + fixed (KernelEvent* ep = eventList) #if NET - return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null); + return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null); #else return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null) != -1; #endif diff --git a/src/Darwin/SystemLog.cs b/src/Darwin/SystemLog.cs index 02dcc77443e1..b470534c75d7 100644 --- a/src/Darwin/SystemLog.cs +++ b/src/Darwin/SystemLog.cs @@ -43,7 +43,7 @@ namespace Darwin { public class SystemLog : DisposableObject { static SystemLog? _default; - + public static SystemLog Default { get { if (_default is null) @@ -51,7 +51,7 @@ public static SystemLog Default { return _default!; } } - + [Flags] public enum Option { Stderr, @@ -65,10 +65,10 @@ protected override void Dispose (bool disposing) asl_close (Handle); base.Dispose (disposing); } - + [DllImport (Constants.SystemLibrary)] extern static void asl_close (IntPtr handle); - + [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_open (IntPtr ident, IntPtr facility, Option /* uint32_t */ options); @@ -89,7 +89,7 @@ static IntPtr asl_open (string ident, string facility, Option options) : base (handle, owns) { } - + public SystemLog (string ident, string facility, Option options = 0) : base ( asl_open ( @@ -110,7 +110,7 @@ static IntPtr asl_open_from_file (int /* int */ fd, string ident, string facilit using var facilityStr = new TransientString (facility); return asl_open_from_file (fd, identStr, facilityStr); } - + public SystemLog (int fileDescriptor, string ident, string facility) : base ( asl_open_from_file ( @@ -127,7 +127,7 @@ public SystemLog (int fileDescriptor, string ident, string facility) [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_remove_log_file (IntPtr handle, int /* int */ fd); - + public void AddLogFile (int descriptor) { asl_add_log_file (Handle, descriptor); @@ -159,24 +159,24 @@ public int Log (string text) { if (text is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (text)); - + return asl_log (Handle, IntPtr.Zero, text); } - + [DllImport (Constants.SystemLibrary)] extern static int asl_send (IntPtr handle, IntPtr msgHandle); - + public int Log (Message msg) { if (msg is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (msg)); - + return asl_send (Handle, msg.Handle); } [DllImport (Constants.SystemLibrary)] extern static int asl_set_filter (IntPtr handle, int /* int */ f); - + public int SetFilter (int level) { return asl_set_filter (Handle, level); @@ -187,17 +187,17 @@ public int SetFilter (int level) [DllImport (Constants.SystemLibrary)] extern static IntPtr aslresponse_next (IntPtr handle); - + [DllImport (Constants.SystemLibrary)] extern static void aslresponse_free (IntPtr handle); - + public IEnumerable Search (Message msg) { if (msg is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (msg)); var search = asl_search (Handle, msg.Handle); IntPtr mh; - + while ((mh = aslresponse_next (search)) != IntPtr.Zero) yield return new Message (mh, true); @@ -218,7 +218,7 @@ public enum Op { Suffix = 0x40, Substring = 0x60, Numeric = 0x80, - Regex = 0x100, + Regex = 0x100, Equal = 1, Greater = 2, GreaterEqual = 3, @@ -233,7 +233,7 @@ internal Message (NativeHandle handle, bool owns) : base (handle, owns) { } - + public Message (Kind kind) : base (asl_new (kind), true) { @@ -254,7 +254,7 @@ protected override void Dispose (bool disposing) [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_get (IntPtr handle, IntPtr key); - + [DllImport (Constants.SystemLibrary)] extern static int asl_set (IntPtr handle, IntPtr key, IntPtr value); @@ -276,7 +276,7 @@ public string this [string key] { [DllImport (Constants.SystemLibrary)] extern static int asl_unset (IntPtr handle, IntPtr key); - + public void Remove (string key) { if (key is null) @@ -284,7 +284,7 @@ public void Remove (string key) using var keyStr = new TransientString (key); asl_unset (Handle, keyStr); } - + #if NET [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_key (IntPtr handle, int /* uint32_t */ key); @@ -292,8 +292,8 @@ public void Remove (string key) [DllImport (Constants.SystemLibrary)] extern static string asl_key (IntPtr handle, int /* uint32_t */ key); #endif - - public string this [int key]{ + + public string this [int key] { get { #if NET return Marshal.PtrToStringAuto (asl_key (Handle, key))!; @@ -312,37 +312,37 @@ public string Host { get { return this ["Host"]; } set { this ["Host"] = value; } } - + public string Sender { get { return this ["Sender"]; } set { this ["Sender"] = value; } } - + public string Facility { get { return this ["Facility"]; } set { this ["Facility"] = value; } } - + public string PID { get { return this ["PID"]; } set { this ["PID"] = value; } } - + public string UID { get { return this ["UID"]; } set { this ["UID"] = value; } } - + public string GID { get { return this ["GID"]; } set { this ["GID"] = value; } } - + public string Level { get { return this ["Level"]; } set { this ["Level"] = value; } } - + public string Msg { get { return this ["Message"]; } set { this ["Message"] = value; } @@ -350,7 +350,7 @@ public string Msg { [DllImport (Constants.SystemLibrary)] extern static int asl_set_query (IntPtr handle, IntPtr key, IntPtr value, int /* uint32_t */ op); - + public bool SetQuery (string key, Op op, string value) { using var keyStr = new TransientString (key); diff --git a/src/FileProvider/Structs.cs b/src/FileProvider/Structs.cs index 8fd2a4fa59f2..4a4440fe3f72 100644 --- a/src/FileProvider/Structs.cs +++ b/src/FileProvider/Structs.cs @@ -23,8 +23,7 @@ namespace FileProvider { [NoMacCatalyst] #endif [StructLayout (LayoutKind.Sequential)] - public struct NSFileProviderTypeAndCreator - { + public struct NSFileProviderTypeAndCreator { public uint Type; public uint Creator; @@ -32,7 +31,7 @@ public struct NSFileProviderTypeAndCreator public string GetTypeAsFourCC () => Runtime.ToFourCCString (Type); - public string GetCreatorAsFourCC() + public string GetCreatorAsFourCC () => Runtime.ToFourCCString (Creator); #endif } diff --git a/src/Foundation/Enum.cs b/src/Foundation/Enum.cs index 82ae2939c54f..90f7c2fa9c80 100644 --- a/src/Foundation/Enum.cs +++ b/src/Foundation/Enum.cs @@ -82,7 +82,9 @@ public enum NSUrlCredentialPersistence : ulong { public enum NSBundleExecutableArchitecture : long { #else /// The bundle's architecture. - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] public enum NSBundleExecutableArchitecture { #endif I386 = 0x00000007, diff --git a/src/Foundation/NSAppleEventDescriptor.cs b/src/Foundation/NSAppleEventDescriptor.cs index a4d5a8777b23..1943142b53b7 100644 --- a/src/Foundation/NSAppleEventDescriptor.cs +++ b/src/Foundation/NSAppleEventDescriptor.cs @@ -9,15 +9,13 @@ using AppKit; -namespace Foundation -{ +namespace Foundation { public enum NSAppleEventDescriptorType { Record, List, } - public partial class NSAppleEventDescriptor - { + public partial class NSAppleEventDescriptor { public NSAppleEventDescriptor (NSAppleEventDescriptorType type) { switch (type) { diff --git a/src/Foundation/NSArray.cs b/src/Foundation/NSArray.cs index 47e644bbb58f..b276ebb5e63d 100644 --- a/src/Foundation/NSArray.cs +++ b/src/Foundation/NSArray.cs @@ -242,7 +242,7 @@ static internal NSArray FromIntPtrs (IntPtr [] items) throw new ArgumentNullException (nameof (items)); unsafe { - fixed (IntPtr *valuesPtr = items) + fixed (IntPtr* valuesPtr = items) return Runtime.GetNSObject (NSArray.FromObjects ((IntPtr) valuesPtr, items.Length))!; } } diff --git a/src/Foundation/NSAttributedString.cs b/src/Foundation/NSAttributedString.cs index 5c8de4d962f3..63c936ae8ad0 100644 --- a/src/Foundation/NSAttributedString.cs +++ b/src/Foundation/NSAttributedString.cs @@ -181,22 +181,22 @@ public partial class NSAttributedString { [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSUrl url, NSAttributedStringDocumentAttributes documentAttributes, out NSError error) - : this (url, documentAttributes, out var _, out error) {} + : this (url, documentAttributes, out var _, out error) { } [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSData data, NSAttributedStringDocumentAttributes documentAttributes, out NSError error) - : this (data, documentAttributes, out var _, out error) {} + : this (data, documentAttributes, out var _, out error) { } [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSUrl url, out NSError error) - : this (url, new NSDictionary (), out var _, out error) {} + : this (url, new NSDictionary (), out var _, out error) { } [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSData data, out NSError error) - : this (data, new NSDictionary (), out var _, out error) {} + : this (data, new NSDictionary (), out var _, out error) { } #else [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] @@ -241,7 +241,7 @@ public string? Value { public IntPtr LowLevelGetAttributes (nint location, out NSRange effectiveRange) { unsafe { - fixed (NSRange *effectiveRangePtr = &effectiveRange) { + fixed (NSRange* effectiveRangePtr = &effectiveRange) { return LowLevelGetAttributes (location, (IntPtr) effectiveRangePtr); } } diff --git a/src/Foundation/NSAttributedString.mac.cs b/src/Foundation/NSAttributedString.mac.cs index 078f350d5ca5..74abe3b76959 100644 --- a/src/Foundation/NSAttributedString.mac.cs +++ b/src/Foundation/NSAttributedString.mac.cs @@ -16,10 +16,8 @@ using WebKit; //using CoreText; -namespace Foundation -{ - public partial class NSAttributedString - { +namespace Foundation { + public partial class NSAttributedString { public NSAttributedString (string str, NSFont? font = null, NSColor? foregroundColor = null, @@ -97,11 +95,11 @@ internal NSAttributedString (NSData data, NSAttributedStringDataType type, out N Handle = InitWithRtfd (data, out resultDocumentAttributes); break; default: - throw new ArgumentException("Error creating NSAttributedString."); + throw new ArgumentException ("Error creating NSAttributedString."); } if (Handle == IntPtr.Zero) - throw new ArgumentException("Error creating NSAttributedString."); + throw new ArgumentException ("Error creating NSAttributedString."); } public static NSAttributedString CreateWithRTF (NSData rtfData, out NSDictionary resultDocumentAttributes) diff --git a/src/Foundation/NSConnection.cs b/src/Foundation/NSConnection.cs index 6b2c233a2606..e8cc3a5cc2fc 100644 --- a/src/Foundation/NSConnection.cs +++ b/src/Foundation/NSConnection.cs @@ -36,10 +36,8 @@ // Disable until we get around to enable + fix any issues. #nullable disable -namespace Foundation -{ - public partial class NSConnection - { +namespace Foundation { + public partial class NSConnection { public TProxy GetRootProxy () where TProxy : NSObject { @@ -65,7 +63,7 @@ static TProxy GetRootProxy (IntPtr handle) where TProxy : NSObject var result = Runtime.TryGetNSObject (handle) as TProxy; if (result is null) - result = (TProxy)Activator.CreateInstance (typeof (TProxy), new object[] { handle }); + result = (TProxy) Activator.CreateInstance (typeof (TProxy), new object [] { handle }); return result; } diff --git a/src/Foundation/NSHost.cs b/src/Foundation/NSHost.cs index b410c6000d9b..879e2fbf496b 100644 --- a/src/Foundation/NSHost.cs +++ b/src/Foundation/NSHost.cs @@ -17,10 +17,8 @@ using System.Collections; using System.Collections.Generic; -namespace Foundation -{ - public partial class NSHost : IEquatable, IEnumerable - { +namespace Foundation { + public partial class NSHost : IEquatable, IEnumerable { static NSHost? CheckNull (NSHost? host) { if (host is null) @@ -143,7 +141,7 @@ public IPAddress [] Addresses { public override int GetHashCode () { - return (int)_Hash; + return (int) _Hash; } public override bool Equals (object? obj) diff --git a/src/Foundation/NSIndexSet.cs b/src/Foundation/NSIndexSet.cs index b50df0a7b8e5..27f82b5484d5 100644 --- a/src/Foundation/NSIndexSet.cs +++ b/src/Foundation/NSIndexSet.cs @@ -33,7 +33,7 @@ using ObjCRuntime; namespace Foundation { - + public partial class NSIndexSet : IEnumerable, IEnumerable { IEnumerator IEnumerable.GetEnumerator () @@ -59,8 +59,8 @@ public IEnumerator GetEnumerator () i = this.IndexGreaterThan (i); } } - - public nuint[] ToArray () + + public nuint [] ToArray () { nuint [] indexes = new nuint [Count]; @@ -75,54 +75,54 @@ public nuint[] ToArray () return indexes; } - public static NSIndexSet FromArray (nuint[] items) + public static NSIndexSet FromArray (nuint [] items) { if (items is null) return new NSIndexSet (); - - var indexSet = new NSMutableIndexSet(); - foreach (var index in items) - indexSet.Add (index); + + var indexSet = new NSMutableIndexSet (); + foreach (var index in items) + indexSet.Add (index); return indexSet; } - public static NSIndexSet FromArray (uint[] items) + public static NSIndexSet FromArray (uint [] items) { if (items is null) return new NSIndexSet (); - var indexSet = new NSMutableIndexSet(); + var indexSet = new NSMutableIndexSet (); foreach (var index in items) - indexSet.Add ((nuint)index); + indexSet.Add ((nuint) index); return indexSet; } - public static NSIndexSet FromArray (int[] items) + public static NSIndexSet FromArray (int [] items) { if (items is null) return new NSIndexSet (); - - var indexSet = new NSMutableIndexSet(); - foreach (var index in items){ + + var indexSet = new NSMutableIndexSet (); + foreach (var index in items) { if (index < 0) throw new ArgumentException ("One of the items values is negative"); - indexSet.Add ((nuint)(uint) index); + indexSet.Add ((nuint) (uint) index); } return indexSet; } - public NSIndexSet (uint value) : this ((nuint)value) + public NSIndexSet (uint value) : this ((nuint) value) { } - public NSIndexSet (nint value) : this ((nuint)value) + public NSIndexSet (nint value) : this ((nuint) value) { if (value < 0) throw new ArgumentException ("value must be positive"); // init done by the base ctor } - public NSIndexSet (int value) : this ((nuint)(uint)value) + public NSIndexSet (int value) : this ((nuint) (uint) value) { if (value < 0) throw new ArgumentException ("value must be positive"); diff --git a/src/Foundation/NSNumber.mac.cs b/src/Foundation/NSNumber.mac.cs index 1e5f80b1e701..4f22543ec637 100644 --- a/src/Foundation/NSNumber.mac.cs +++ b/src/Foundation/NSNumber.mac.cs @@ -14,35 +14,33 @@ // Disable until we get around to enable + fix any issues. #nullable disable -namespace Foundation -{ - public partial class NSNumber - { +namespace Foundation { + public partial class NSNumber { #if !COREBUILD public static NSNumber FromObject (object value) { if (value is float) { - return FromFloat ((float)value); + return FromFloat ((float) value); } else if (value is double) { - return FromDouble ((double)value); + return FromDouble ((double) value); } else if (value is sbyte) { - return FromSByte ((sbyte)value); + return FromSByte ((sbyte) value); } else if (value is byte) { - return FromByte ((byte)value); + return FromByte ((byte) value); } else if (value is short) { - return FromInt16 ((short)value); + return FromInt16 ((short) value); } else if (value is ushort) { - return FromUInt16 ((ushort)value); + return FromUInt16 ((ushort) value); } else if (value is int) { - return FromInt32 ((int)value); + return FromInt32 ((int) value); } else if (value is uint) { - return FromUInt32 ((uint)value); + return FromUInt32 ((uint) value); } else if (value is long) { - return FromInt64 ((long)value); + return FromInt64 ((long) value); } else if (value is ulong) { - return FromUInt64 ((ulong)value); + return FromUInt64 ((ulong) value); } else if (value is bool) { - return FromBoolean ((bool)value); + return FromBoolean ((bool) value); } else if (value is nint) { return FromNInt ((nint) value); } else if (value is nuint) { diff --git a/src/Foundation/NSObject.mac.cs b/src/Foundation/NSObject.mac.cs index 0f92d00a4f34..0b1fb0266514 100644 --- a/src/Foundation/NSObject.mac.cs +++ b/src/Foundation/NSObject.mac.cs @@ -100,7 +100,7 @@ public partial class NSObject { static IntPtr nl = Dlfcn.dlopen (Constants.NaturalLanguageLibrary, 1); static IntPtr vs = Dlfcn.dlopen (Constants.VideoSubscriberAccountLibrary, 1); static IntPtr un = Dlfcn.dlopen (Constants.UserNotificationsLibrary, 1); - static IntPtr il = Dlfcn.dlopen (Constants.iTunesLibraryLibrary, 1); + static IntPtr il = Dlfcn.dlopen (Constants.iTunesLibraryLibrary, 1); static IntPtr exl = Dlfcn.dlopen (Constants.ExtensionKitLibrary, 1); static IntPtr sw = Dlfcn.dlopen (Constants.SharedWithYouLibrary, 1); static IntPtr swc = Dlfcn.dlopen (Constants.SharedWithYouCoreLibrary, 1); diff --git a/src/Foundation/NSObject2.cs b/src/Foundation/NSObject2.cs index 83e42eb6d954..2d7cb199aa8d 100644 --- a/src/Foundation/NSObject2.cs +++ b/src/Foundation/NSObject2.cs @@ -77,7 +77,7 @@ public class NSObjectFlag { internal interface INSObjectFactory { // The method will be implemented via custom linker step if the managed static registrar is used // for NSObject subclasses which have an (NativeHandle) or (IntPtr) constructor. - [MethodImpl(MethodImplOptions.NoInlining)] + [MethodImpl (MethodImplOptions.NoInlining)] virtual static NSObject _Xamarin_ConstructNSObject (NativeHandle handle) => null; } #endif @@ -256,7 +256,7 @@ public void Dispose () // This method doesn't necessarily work with NativeAOT, but this is covered by the exception, because the managed static registrar is required for NativeAOT. // // IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in call to 'System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(Type)'. The return value of method 'ObjCRuntime.Runtime.GetGCHandleTarget(IntPtr)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - [UnconditionalSuppressMessage("", "IL2072", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2072", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif internal static IntPtr CreateNSObject (IntPtr type_gchandle, IntPtr handle, Flags flags) { @@ -738,7 +738,7 @@ public void BeginInvokeOnMainThread (Action action) var d = new NSAsyncActionDispatcher (action); #if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - NSDispatcher.Selector.Handle, d.Handle, 0); + NSDispatcher.Selector.Handle, d.Handle, 0); #else #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, @@ -755,7 +755,7 @@ internal void BeginInvokeOnMainThread (System.Threading.SendOrPostCallback cb, o var d = new NSAsyncSynchronizationContextDispatcher (cb, state); #if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 0); + Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 0); #else #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, @@ -771,8 +771,8 @@ public void InvokeOnMainThread (Action action) { using (var d = new NSActionDispatcher (action)) { #if NET - Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); + Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), + Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); #else #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, @@ -790,7 +790,7 @@ internal void InvokeOnMainThread (System.Threading.SendOrPostCallback cb, object using (var d = new NSSynchronizationContextDispatcher (cb, state)) { #if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); + Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); #else #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, diff --git a/src/Foundation/NSPropertyListSerialization.cs b/src/Foundation/NSPropertyListSerialization.cs index 6b56f3612348..aeb80700fdc3 100644 --- a/src/Foundation/NSPropertyListSerialization.cs +++ b/src/Foundation/NSPropertyListSerialization.cs @@ -30,10 +30,8 @@ using System; -namespace Foundation -{ - public partial class NSPropertyListSerialization - { +namespace Foundation { + public partial class NSPropertyListSerialization { public static NSData DataWithPropertyList (NSObject plist, NSPropertyListFormat format, out NSError error) { return DataWithPropertyList (plist, format, NSPropertyListWriteOptions.Immutable, out error); diff --git a/src/Foundation/NSScriptCommandArgumentDescription.cs b/src/Foundation/NSScriptCommandArgumentDescription.cs index e60a43b7231d..4524945bae73 100644 --- a/src/Foundation/NSScriptCommandArgumentDescription.cs +++ b/src/Foundation/NSScriptCommandArgumentDescription.cs @@ -30,16 +30,16 @@ public static NSString OptionalKey { public partial class NSScriptCommandArgumentDescription { public string Name { get; set; } - public bool IsOptional { + public bool IsOptional { get { return Optional is not null && Optional == "Yes"; } - set { + set { Optional = (value) ? "Yes" : "No"; } } - public NSScriptCommandArgumentDescription (string name, string eventCode, string type, bool isOptional=false) + public NSScriptCommandArgumentDescription (string name, string eventCode, string type, bool isOptional = false) { if (String.IsNullOrEmpty (name)) throw new ArgumentException ("name cannot be null or empty."); @@ -58,7 +58,7 @@ public NSScriptCommandArgumentDescription (string name, string eventCode, string } } - + #endif } diff --git a/src/Foundation/NSScriptCommandDescription.cs b/src/Foundation/NSScriptCommandDescription.cs index 04aaf384c62b..afa41557f905 100644 --- a/src/Foundation/NSScriptCommandDescription.cs +++ b/src/Foundation/NSScriptCommandDescription.cs @@ -14,11 +14,11 @@ namespace Foundation { // The kyes are not found in any of the public headers from apple. That is the reason // to use this technique. static class NSScriptCommonKeys { - private static NSString appEventCode = new NSString ("AppleEventCode"); + private static NSString appEventCode = new NSString ("AppleEventCode"); public static NSString AppleEventCodeKey { get { return appEventCode; } } - + private static NSString typeKey = new NSString ("Type"); public static NSString TypeKey { get { return typeKey; } @@ -36,7 +36,7 @@ static int ToIntValue (string fourCC) int ret = 0; for (int i = 0; i < 4; i++) { ret <<= 8; - ret |= fourCC[i]; + ret |= fourCC [i]; } return ret; } @@ -63,7 +63,7 @@ public static NSScriptCommandDescription Create (string suiteName, string comman throw new ArgumentException ("eventClass must be a four characters string."); if (commandDeclaration.ResultAppleEventCode is not null && commandDeclaration.ResultAppleEventCode.Length != 4) throw new ArgumentException ("resultAppleEvent must be a four characters string."); - + using (var nsSuitName = new NSString (suiteName)) using (var nsCommandName = new NSString (commandName)) { try { @@ -96,8 +96,8 @@ public string GetTypeForArgument (string name) { if (name is null) throw new ArgumentNullException ("name"); - - using (var nsName = new NSString(name)) + + using (var nsName = new NSString (name)) using (var nsType = GetNSTypeForArgument (nsName)) { return nsType?.ToString (); } @@ -112,8 +112,8 @@ public string GetAppleEventCodeForArgument (string name) return Runtime.ToFourCCString (FCCAppleEventCodeForArgument (nsName)); } } - - public bool IsOptionalArgument (string name) + + public bool IsOptionalArgument (string name) { using (var nsName = new NSString (name)) { return NSIsOptionalArgument (nsName); diff --git a/src/Foundation/NSScriptCommandDescriptionDictionary.cs b/src/Foundation/NSScriptCommandDescriptionDictionary.cs index 4f140e4d110c..55c42fd4abfc 100644 --- a/src/Foundation/NSScriptCommandDescriptionDictionary.cs +++ b/src/Foundation/NSScriptCommandDescriptionDictionary.cs @@ -9,28 +9,28 @@ namespace Foundation { public static class NSScriptCommandDescriptionDictionaryKeys { private static NSString cmdClass = new NSString ("CommandClass"); - public static NSString CommandClassKey { + public static NSString CommandClassKey { get { return cmdClass; } } - - public static NSString AppleEventCodeKey { + + public static NSString AppleEventCodeKey { get { return NSScriptCommonKeys.AppleEventCodeKey; } } - + private static NSString codeClass = new NSString ("AppleEventClassCode"); - public static NSString AppleEventClassCodeKey { + public static NSString AppleEventClassCodeKey { get { return codeClass; } } - + public static NSString TypeKey { get { return NSScriptCommonKeys.TypeKey; } } - + private static NSString resultAppEventCode = new NSString ("ResultAppleEventCode"); - public static NSString ResultAppleEventCodeKey { + public static NSString ResultAppleEventCodeKey { get { return resultAppEventCode; } } - + private static NSString args = new NSString ("Arguments"); public static NSString ArgumentsKey { get { return args; } @@ -44,7 +44,7 @@ public void Add (NSScriptCommandArgumentDescription arg) if (arg is null) throw new ArgumentNullException ("arg"); if (Arguments is null) - Arguments = new NSMutableDictionary (); + Arguments = new NSMutableDictionary (); using (var nsName = new NSString (arg.Name)) { Arguments.Add (nsName, arg.Dictionary); } diff --git a/src/Foundation/NSSecureCoding.cs b/src/Foundation/NSSecureCoding.cs index 30c523180085..4d616daff386 100644 --- a/src/Foundation/NSSecureCoding.cs +++ b/src/Foundation/NSSecureCoding.cs @@ -28,8 +28,7 @@ public static bool SupportsSecureCoding (Type type) #if MONOMAC try { return SupportsSecureCoding (new Class (type)); - } - catch (ArgumentException) { + } catch (ArgumentException) { // unlike XI the current registration will throw for protocols // until that's fixed we'll only report correctly properly bound protocol types // the workaround is important since this method is used to validate our bindings diff --git a/src/Foundation/NSString.cs b/src/Foundation/NSString.cs index adde5d390fbf..115081a7e8ae 100644 --- a/src/Foundation/NSString.cs +++ b/src/Foundation/NSString.cs @@ -44,11 +44,11 @@ namespace Foundation { #if COREBUILD [Protocol] - public interface INSCopying {} + public interface INSCopying { } [Protocol] - public interface INSCoding {} + public interface INSCoding { } [Protocol] - public interface INSSecureCoding {} + public interface INSSecureCoding { } #endif public partial class NSString : NSObject diff --git a/src/Foundation/NSThread.mac.cs b/src/Foundation/NSThread.mac.cs index 5bf36a09f0d1..f8b681ccf731 100644 --- a/src/Foundation/NSThread.mac.cs +++ b/src/Foundation/NSThread.mac.cs @@ -10,19 +10,16 @@ using System; -namespace Foundation -{ - public partial class NSThread - { - class ActionThread : NSThread - { +namespace Foundation { + public partial class NSThread { + class ActionThread : NSThread { Action action; - + public ActionThread (Action action) { this.action = action; } - + public override void Main () { action (); diff --git a/src/Foundation/NSUrlDownload.cs b/src/Foundation/NSUrlDownload.cs index 2161b97aa83f..e71e7ebdfcd7 100644 --- a/src/Foundation/NSUrlDownload.cs +++ b/src/Foundation/NSUrlDownload.cs @@ -2,7 +2,7 @@ namespace Foundation { public partial class NSUrlDownload { - + public override string ToString () { return GetType ().ToString (); diff --git a/src/Foundation/NSUrlSessionHandler.cs b/src/Foundation/NSUrlSessionHandler.cs index 571e69c12de9..126bc3b249d4 100644 --- a/src/Foundation/NSUrlSessionHandler.cs +++ b/src/Foundation/NSUrlSessionHandler.cs @@ -603,7 +603,7 @@ public int MaxAutomaticRedirections { set { // I believe it's possible to implement support for MaxAutomaticRedirections (it just has to be done) if (value != int.MaxValue) - ObjCRuntime.ThrowHelper.ThrowArgumentOutOfRangeException (nameof (value), value, "It's not possible to lower the max number of automatic redirections.");; + ObjCRuntime.ThrowHelper.ThrowArgumentOutOfRangeException (nameof (value), value, "It's not possible to lower the max number of automatic redirections."); ; } } @@ -657,7 +657,7 @@ public IWebProxy? Proxy { set { if (value is not null) throw new PlatformNotSupportedException (); - } + } } // There doesn't seem to be a trivial way to specify the protocols to accept (or not) @@ -696,8 +696,7 @@ internal bool TryInvokeServerCertificateCustomValidationCallback (HttpRequestMes return true; } - sealed class ServerCertificateCustomValidationCallbackHelper - { + sealed class ServerCertificateCustomValidationCallbackHelper { public Func Callback { get; private set; } public ServerCertificateCustomValidationCallbackHelper (Func callback) @@ -707,7 +706,7 @@ public ServerCertificateCustomValidationCallbackHelper (Func 0 ? certificates [0] : null; using X509Chain chain = CreateChain (certificates); SslPolicyErrors sslPolicyErrors = EvaluateSslPolicyErrors (certificate, chain, secTrust); @@ -715,7 +714,7 @@ public bool Invoke (HttpRequestMessage request, SecTrust secTrust) return Callback (request, certificate, chain, sslPolicyErrors); } - X509Certificate2[] ConvertCertificates (SecTrust secTrust) + X509Certificate2 [] ConvertCertificates (SecTrust secTrust) { var certificates = new X509Certificate2 [secTrust.Count]; @@ -748,7 +747,7 @@ static bool IsSecTrustGetCertificateChainSupported { } } - X509Chain CreateChain (X509Certificate2[] certificates) + X509Chain CreateChain (X509Certificate2 [] certificates) { // inspired by https://github.com/dotnet/runtime/blob/99d21b9276ebe8f7bea7fb3ba74dca9fca625fe2/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs#L691-L696 var chain = new X509Chain (); @@ -761,7 +760,7 @@ X509Chain CreateChain (X509Certificate2[] certificates) SslPolicyErrors EvaluateSslPolicyErrors (X509Certificate2? certificate, X509Chain chain, SecTrust secTrust) { var sslPolicyErrors = SslPolicyErrors.None; - + try { if (certificate is null) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable; @@ -802,7 +801,7 @@ public bool UseProxy { get => true; set { if (!value) - ObjCRuntime.ThrowHelper.ThrowArgumentOutOfRangeException (nameof (value), value, "It's not possible to disable the use of system proxies.");; + ObjCRuntime.ThrowHelper.ThrowArgumentOutOfRangeException (nameof (value), value, "It's not possible to disable the use of system proxies."); ; } } #endif // NET diff --git a/src/GameKit/GKCompat.cs b/src/GameKit/GKCompat.cs index 0f2cadd8d4be..1a70c5f50231 100644 --- a/src/GameKit/GKCompat.cs +++ b/src/GameKit/GKCompat.cs @@ -48,8 +48,7 @@ public static void DidSaveData (GKGameSession session, GKCloudPlayer player, Fou [Unavailable (PlatformName.MacOSX)] [Unavailable (PlatformName.TvOS)] #endif - public interface IGKPeerPickerControllerDelegate : INativeObject, IDisposable - { + public interface IGKPeerPickerControllerDelegate : INativeObject, IDisposable { } [EditorBrowsable (EditorBrowsableState.Never)] @@ -207,7 +206,7 @@ public virtual NSObject? WeakDelegate { protected override void Dispose (bool disposing) { - throw new PlatformNotSupportedException (Constants.TypeUnavailable); + throw new PlatformNotSupportedException (Constants.TypeUnavailable); } } /* class GKPeerPickerController */ #endif // __IOS__ || __MACCATALYST__ diff --git a/src/ImageIO/CGImageAnimation.cs b/src/ImageIO/CGImageAnimation.cs index 954888f9622c..df3743762c81 100644 --- a/src/ImageIO/CGImageAnimation.cs +++ b/src/ImageIO/CGImageAnimation.cs @@ -19,20 +19,20 @@ namespace ImageIO { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public static class CGImageAnimation { public delegate void CGImageSourceAnimationHandler (nint index, CGImage image, out bool stop); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -41,10 +41,10 @@ public static class CGImageAnimation { unsafe static extern /* OSStatus */ CGImageAnimationStatus CGAnimateImageAtURLWithBlock ( /* CFURLRef */ IntPtr url, /* CFDictionaryRef _iio_Nullable */ IntPtr options, /* CGImageSourceAnimationHandler */ BlockLiteral* block); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -53,10 +53,10 @@ public static class CGImageAnimation { unsafe static extern /* OSStatus */ CGImageAnimationStatus CGAnimateImageDataWithBlock ( /* CFDataRef _Nonnull */ IntPtr data, /* CFDictionaryRef _Nullable */ IntPtr options, /* CGImageSourceAnimationHandler _Nonnull */ BlockLiteral* block); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -82,10 +82,10 @@ public static CGImageAnimationStatus AnimateImage (NSUrl url, CGImageAnimationOp } #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] diff --git a/src/Intents/INBillTypeResolutionResult.cs b/src/Intents/INBillTypeResolutionResult.cs index ea6e7a3a7e48..9d33beb35a89 100644 --- a/src/Intents/INBillTypeResolutionResult.cs +++ b/src/Intents/INBillTypeResolutionResult.cs @@ -20,7 +20,7 @@ public static INBillTypeResolutionResult GetSuccess (INBillType resolvedValue) #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedBillType (resolvedValue); + return SuccessWithResolvedBillType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INBillTypeResolutionResult GetConfirmationRequired (INBillType val #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithBillTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithBillTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INCallRecordTypeResolutionResult.cs b/src/Intents/INCallRecordTypeResolutionResult.cs index 9246df1f7567..a61cc33455e5 100644 --- a/src/Intents/INCallRecordTypeResolutionResult.cs +++ b/src/Intents/INCallRecordTypeResolutionResult.cs @@ -22,7 +22,7 @@ public static INCallRecordTypeResolutionResult GetSuccess (INCallRecordType reso #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return SuccessWithResolvedCallRecordType (resolvedValue); + return SuccessWithResolvedCallRecordType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -34,7 +34,7 @@ public static INCallRecordTypeResolutionResult GetConfirmationRequired (INCallRe #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return ConfirmationRequiredWithCallRecordTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithCallRecordTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INCarSignalOptionsResolutionResult.cs b/src/Intents/INCarSignalOptionsResolutionResult.cs index bcdc2196ffc8..aa412bd8bdc4 100644 --- a/src/Intents/INCarSignalOptionsResolutionResult.cs +++ b/src/Intents/INCarSignalOptionsResolutionResult.cs @@ -20,7 +20,7 @@ public static INCarSignalOptionsResolutionResult GetSuccess (INCarSignalOptions #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedCarSignalOptions (resolvedValue); + return SuccessWithResolvedCarSignalOptions (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INCarSignalOptionsResolutionResult GetConfirmationRequired (INCarS #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithCarSignalOptionsToConfirm (valueToConfirm); + return ConfirmationRequiredWithCarSignalOptionsToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INMessageAttributeOptionsResolutionResult.cs b/src/Intents/INMessageAttributeOptionsResolutionResult.cs index ff6439b10fbc..68223a697189 100644 --- a/src/Intents/INMessageAttributeOptionsResolutionResult.cs +++ b/src/Intents/INMessageAttributeOptionsResolutionResult.cs @@ -23,7 +23,7 @@ public static INMessageAttributeOptionsResolutionResult GetSuccess (INMessageAtt #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return SuccessWithResolvedMessageAttributeOptions (resolvedValue); + return SuccessWithResolvedMessageAttributeOptions (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -35,7 +35,7 @@ public static INMessageAttributeOptionsResolutionResult GetConfirmationRequired #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return ConfirmationRequiredWithMessageAttributeOptionsToConfirm (valueToConfirm); + return ConfirmationRequiredWithMessageAttributeOptionsToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INMessageAttributeResolutionResult.cs b/src/Intents/INMessageAttributeResolutionResult.cs index 5e8a2b8d8658..3c64ca4e8d65 100644 --- a/src/Intents/INMessageAttributeResolutionResult.cs +++ b/src/Intents/INMessageAttributeResolutionResult.cs @@ -23,7 +23,7 @@ public static INMessageAttributeResolutionResult GetSuccess (INMessageAttribute #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return SuccessWithResolvedMessageAttribute (resolvedValue); + return SuccessWithResolvedMessageAttribute (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -35,7 +35,7 @@ public static INMessageAttributeResolutionResult GetConfirmationRequired (INMess #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return ConfirmationRequiredWithMessageAttributeToConfirm (valueToConfirm); + return ConfirmationRequiredWithMessageAttributeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INPaymentStatusResolutionResult.cs b/src/Intents/INPaymentStatusResolutionResult.cs index 05098efd515c..7c37db737020 100644 --- a/src/Intents/INPaymentStatusResolutionResult.cs +++ b/src/Intents/INPaymentStatusResolutionResult.cs @@ -20,7 +20,7 @@ public static INPaymentStatusResolutionResult GetSuccess (INPaymentStatus resolv #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedPaymentStatus (resolvedValue); + return SuccessWithResolvedPaymentStatus (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INPaymentStatusResolutionResult GetConfirmationRequired (INPayment #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithPaymentStatusToConfirm (valueToConfirm); + return ConfirmationRequiredWithPaymentStatusToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INSetClimateSettingsInCarIntent.cs b/src/Intents/INSetClimateSettingsInCarIntent.cs index dc2f218e2f01..69b72f2f8d6f 100644 --- a/src/Intents/INSetClimateSettingsInCarIntent.cs +++ b/src/Intents/INSetClimateSettingsInCarIntent.cs @@ -18,7 +18,7 @@ public partial class INSetClimateSettingsInCarIntent { [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] #endif public INSetClimateSettingsInCarIntent (bool? enableFan, bool? enableAirConditioner, bool? enableClimateControl, bool? enableAutoMode, INCarAirCirculationMode airCirculationMode, NSNumber fanSpeedIndex, NSNumber fanSpeedPercentage, INRelativeSetting relativeFanSpeedSetting, NSMeasurement temperature, INRelativeSetting relativeTemperatureSetting, INCarSeat climateZone) : - this (enableFan.HasValue ? new NSNumber (enableFan.Value) : null, enableAirConditioner.HasValue ? new NSNumber (enableAirConditioner.Value) : null, + this (enableFan.HasValue ? new NSNumber (enableFan.Value) : null, enableAirConditioner.HasValue ? new NSNumber (enableAirConditioner.Value) : null, enableClimateControl.HasValue ? new NSNumber (enableClimateControl.Value) : null, enableAutoMode.HasValue ? new NSNumber (enableAutoMode.Value) : null, airCirculationMode, fanSpeedIndex, fanSpeedPercentage, relativeFanSpeedSetting, temperature, relativeTemperatureSetting, climateZone) { diff --git a/src/Intents/INSpeakableString.cs b/src/Intents/INSpeakableString.cs index 7b6ed0e23a73..8ad1f2dab945 100644 --- a/src/Intents/INSpeakableString.cs +++ b/src/Intents/INSpeakableString.cs @@ -21,7 +21,7 @@ public INSpeakableString (string identifier, string spokenPhrase, string pronunc #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - InitializeHandle (InitWithVocabularyIdentifier (identifier, spokenPhrase, pronunciationHint)); + InitializeHandle (InitWithVocabularyIdentifier (identifier, spokenPhrase, pronunciationHint)); #if !TVOS else InitializeHandle (InitWithIdentifier (identifier, spokenPhrase, pronunciationHint)); diff --git a/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs b/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs index 46020fca83a0..7992a54356d8 100644 --- a/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs +++ b/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs @@ -20,7 +20,7 @@ public static INWorkoutGoalUnitTypeResolutionResult GetSuccess (INWorkoutGoalUni #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedWorkoutGoalUnitType (resolvedValue); + return SuccessWithResolvedWorkoutGoalUnitType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INWorkoutGoalUnitTypeResolutionResult GetConfirmationRequired (INW #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithWorkoutGoalUnitTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithWorkoutGoalUnitTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INWorkoutLocationTypeResolutionResult.cs b/src/Intents/INWorkoutLocationTypeResolutionResult.cs index 0afa363d03e1..1fc4bcef3ba3 100644 --- a/src/Intents/INWorkoutLocationTypeResolutionResult.cs +++ b/src/Intents/INWorkoutLocationTypeResolutionResult.cs @@ -20,7 +20,7 @@ public static INWorkoutLocationTypeResolutionResult GetSuccess (INWorkoutLocatio #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedWorkoutLocationType (resolvedValue); + return SuccessWithResolvedWorkoutLocationType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INWorkoutLocationTypeResolutionResult GetConfirmationRequired (INW #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithWorkoutLocationTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithWorkoutLocationTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/MapKit/MapKit.cs b/src/MapKit/MapKit.cs index a5ae570ccccf..a0f966bf0919 100644 --- a/src/MapKit/MapKit.cs +++ b/src/MapKit/MapKit.cs @@ -466,7 +466,7 @@ public static class MKGeometry { } #if COREBUILD - public partial class MKMapLaunchOptions :NSObject { + public partial class MKMapLaunchOptions : NSObject { } #endif } diff --git a/src/MediaExtension/MEByteSource.cs b/src/MediaExtension/MEByteSource.cs index 7db378b6fbc1..3a5f1ef2968e 100644 --- a/src/MediaExtension/MEByteSource.cs +++ b/src/MediaExtension/MEByteSource.cs @@ -12,7 +12,7 @@ public partial class MEByteSource { /// The byte array to write the data into. /// The delegate which is called when the read operation has completed. /// This overload will try to fill the byte array with data. - public void ReadData (long offset, byte[] data, MEByteSourceReadBytesCallback completionHandler) + public void ReadData (long offset, byte [] data, MEByteSourceReadBytesCallback completionHandler) { ReadData ((nuint) data.Length, offset, data, completionHandler); } @@ -22,7 +22,7 @@ public void ReadData (long offset, byte[] data, MEByteSourceReadBytesCallback co /// The offset (relative to the start of the ifle) where to start reading. /// The byte array to write the data into. /// The delegate which is called when the read operation has completed. - public void ReadData (nuint length, long offset, byte[] data, MEByteSourceReadBytesCallback completionHandler) + public void ReadData (nuint length, long offset, byte [] data, MEByteSourceReadBytesCallback completionHandler) { if (data is null) ThrowHelper.ThrowArgumentNullException (nameof (data)); @@ -44,7 +44,7 @@ public void ReadData (nuint length, long offset, byte[] data, MEByteSourceReadBy /// Null if an error occurred, otherwise an instance with information about the error. The error will be if the end was reached. /// True if successful, false otherwise. /// This overload will try to fill the byte array with data. - public bool ReadData (long offset, byte[] data, out nuint bytesRead, out NSError? error) + public bool ReadData (long offset, byte [] data, out nuint bytesRead, out NSError? error) { return ReadData ((nuint) data.Length, offset, data, out bytesRead, out error); } @@ -56,7 +56,7 @@ public bool ReadData (long offset, byte[] data, out nuint bytesRead, out NSError /// Upon return, will contain the number of read bytes. /// Null if an error occurred, otherwise an instance with information about the error. The error will be if the end was reached. /// True if successful, false otherwise. - public bool ReadData (nuint length, long offset, byte[] data, out nuint bytesRead, out NSError? error) + public bool ReadData (nuint length, long offset, byte [] data, out nuint bytesRead, out NSError? error) { if (data is null) ThrowHelper.ThrowArgumentNullException (nameof (data)); diff --git a/src/MediaExtension/MERawProcessingListParameter.cs b/src/MediaExtension/MERawProcessingListParameter.cs index 35aaba9a5026..c5642d5487b8 100644 --- a/src/MediaExtension/MERawProcessingListParameter.cs +++ b/src/MediaExtension/MERawProcessingListParameter.cs @@ -23,7 +23,7 @@ public partial class MERawProcessingListParameter { /// The parameter's initial value. /// The parameter's neutral or camera value. /// Specifies whether is a neutral or a camera value. - public MERawProcessingListParameter (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralOrCameraValue, MERawProcessingListParameterInitializationOption option) + public MERawProcessingListParameter (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralOrCameraValue, MERawProcessingListParameterInitializationOption option) : base (NSObjectFlag.Empty) { switch (option) { diff --git a/src/MediaExtension/MESampleCursor.cs b/src/MediaExtension/MESampleCursor.cs index 340ac8de24fb..2f610ea787a1 100644 --- a/src/MediaExtension/MESampleCursor.cs +++ b/src/MediaExtension/MESampleCursor.cs @@ -14,7 +14,7 @@ public partial interface IMESampleCursor { /// Upon return, the exact location of the sample. /// Upon return, null if successful, otherwise an instance for the error. /// True if successful, false otherwise. - public bool RefineSampleLocation (AVSampleCursorStorageRange estimatedSampleLocation, byte [] refinementData, out AVSampleCursorStorageRange refinedLocation, out NSError? error) + public bool RefineSampleLocation (AVSampleCursorStorageRange estimatedSampleLocation, byte [] refinementData, out AVSampleCursorStorageRange refinedLocation, out NSError? error) { unsafe { fixed (byte* refinementDataPtr = refinementData) { diff --git a/src/MediaToolbox/MTAudioProcessingTap.cs b/src/MediaToolbox/MTAudioProcessingTap.cs index df910cd2e4ac..9bb28c656b6b 100644 --- a/src/MediaToolbox/MTAudioProcessingTap.cs +++ b/src/MediaToolbox/MTAudioProcessingTap.cs @@ -44,19 +44,17 @@ using AudioToolbox; using CoreMedia; -namespace MediaToolbox -{ - public class MTAudioProcessingTap : NativeObject - { +namespace MediaToolbox { + public class MTAudioProcessingTap : NativeObject { #if !COREBUILD delegate void Action_IntPtr (IntPtr arg); // MTAudioProcessingTapCallbacks [StructLayout (LayoutKind.Sequential, Pack = 1)] - unsafe struct Callbacks - { + unsafe struct Callbacks { #pragma warning disable 169 - /* int */ int version; // kMTAudioProcessingTapCallbacksVersion_0 == 0 + /* int */ + int version; // kMTAudioProcessingTapCallbacksVersion_0 == 0 public /* void* */ IntPtr clientInfo; #if NET public /* MTAudioProcessingTapInitCallback */ delegate* unmanaged init; @@ -77,8 +75,8 @@ unsafe struct Callbacks // MTAudioProcessingTapInitCallback unsafe delegate void MTAudioProcessingTapInitCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, /* void* */ IntPtr clientInfo, /* void** */ out void* tapStorageOut); - delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, - IntPtr numberFrames, MTAudioProcessingTapFlags flags, /* AudioBufferList* */ IntPtr bufferListInOut, + delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, + IntPtr numberFrames, MTAudioProcessingTapFlags flags, /* AudioBufferList* */ IntPtr bufferListInOut, out IntPtr numberFramesOut, out MTAudioProcessingTapFlags flagsOut); delegate void MTAudioProcessingTapPrepareCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, IntPtr maxFrames, ref AudioStreamBasicDescription processingFormat); @@ -86,10 +84,10 @@ delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapR static readonly Dictionary handles = new Dictionary (Runtime.IntPtrEqualityComparer); MTAudioProcessingTapCallbacks callbacks; - + internal static MTAudioProcessingTap? FromHandle (IntPtr handle, bool owns) { - lock (handles){ + lock (handles) { if (handles.TryGetValue (handle, out var ret)) return ret; return null; @@ -98,8 +96,8 @@ delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapR [DllImport (Constants.MediaToolboxLibrary)] unsafe extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapCreate ( - /* CFAllocatorRef*/ IntPtr allocator, - /* const MTAudioProcessingTapCallbacks* */ Callbacks* callbacks, + /* CFAllocatorRef*/ IntPtr allocator, + /* const MTAudioProcessingTapCallbacks* */ Callbacks* callbacks, MTAudioProcessingTapCreationFlags flags, /* MTAudioProcessingTapRef* */ IntPtr* tapOut); @@ -144,7 +142,7 @@ public MTAudioProcessingTap (MTAudioProcessingTapCallbacks callbacks, MTAudioPro // and that will call the InitializeProxy. So using this (short-lived) GCHandle allow us to find back the // original managed instance var gch = GCHandle.Alloc (this); - c.clientInfo = (IntPtr)gch; + c.clientInfo = (IntPtr) gch; IntPtr handle; MTAudioProcessingTapError res; @@ -183,7 +181,7 @@ protected override void Dispose (bool disposing) [DllImport (Constants.MediaToolboxLibrary)] unsafe extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapGetSourceAudio ( - /* MTAudioProcessingTapRef */ IntPtr tap, IntPtr numberFrames, + /* MTAudioProcessingTapRef */ IntPtr tap, IntPtr numberFrames, /* AudioBufferList* */ IntPtr bufferListInOut, MTAudioProcessingTapFlags* flagsOut, CMTimeRange* timeRangeOut, IntPtr* numberFramesOut); @@ -200,14 +198,14 @@ public MTAudioProcessingTapError GetSourceAudio (nint frames, AudioBuffers buffe r = MTAudioProcessingTapGetSourceAudio (Handle, (IntPtr) frames, (IntPtr) bufferList, - (MTAudioProcessingTapFlags *) Unsafe.AsPointer (ref flags), - (CMTimeRange *) Unsafe.AsPointer (ref timeRange), + (MTAudioProcessingTapFlags*) Unsafe.AsPointer (ref flags), + (CMTimeRange*) Unsafe.AsPointer (ref timeRange), &result); } framesProvided = (nint) result; return r; } - + // // Proxy callbacks @@ -222,7 +220,7 @@ unsafe static void InitializeProxy (IntPtr tap, IntPtr /*void**/ clientInfo, out #endif { #if NET - void *tempTapStorage = null; + void* tempTapStorage = null; *tapStorage = tempTapStorage; #else tapStorage = null; @@ -238,7 +236,7 @@ unsafe static void InitializeProxy (IntPtr tap, IntPtr /*void**/ clientInfo, out apt?.callbacks.Initialize (apt, out tapStorage); #endif } - } + } #if NET [UnmanagedCallersOnly] @@ -328,30 +326,26 @@ static void UnprepareProxy (IntPtr tap) // uint32_t -> MTAudioProcessingTap.h [Flags] - public enum MTAudioProcessingTapCreationFlags : uint - { - PreEffects = (1 << 0), - PostEffects = (1 << 1), + public enum MTAudioProcessingTapCreationFlags : uint { + PreEffects = (1 << 0), + PostEffects = (1 << 1), } // uint32_t -> MTAudioProcessingTap.h [Flags] - public enum MTAudioProcessingTapFlags : uint - { - StartOfStream = (1 << 8), - EndOfStream = (1 << 9), + public enum MTAudioProcessingTapFlags : uint { + StartOfStream = (1 << 8), + EndOfStream = (1 << 9), } // used as OSStatus (4 bytes) // Not documented error codes - public enum MTAudioProcessingTapError - { - None = 0, - InvalidArgument = -12780 + public enum MTAudioProcessingTapError { + None = 0, + InvalidArgument = -12780 } - public class MTAudioProcessingTapCallbacks - { + public class MTAudioProcessingTapCallbacks { public MTAudioProcessingTapCallbacks (MTAudioProcessingTapProcessDelegate process) { if (process is null) @@ -374,7 +368,7 @@ public delegate void MTAudioProcessingTapProcessDelegate (MTAudioProcessingTap t AudioBuffers bufferList, out nint numberFramesOut, out MTAudioProcessingTapFlags flagsOut); #if COREBUILD - public class AudioBufferList {} + public class AudioBufferList { } #endif } #endif // HAS_MEDIATOOLBOX diff --git a/src/Metal/Defs.cs b/src/Metal/Defs.cs index e3dfdfec36aa..4d01f7e01b29 100644 --- a/src/Metal/Defs.cs +++ b/src/Metal/Defs.cs @@ -531,8 +531,7 @@ public partial interface IMTLTexture { [NoiOS] [NoTV] #endif - public struct MTLIndirectCommandBufferExecutionRange - { + public struct MTLIndirectCommandBufferExecutionRange { public uint Location; public uint Length; diff --git a/src/Metal/MTLArgumentEncoder.cs b/src/Metal/MTLArgumentEncoder.cs index 021d89204685..19eedb5c37be 100644 --- a/src/Metal/MTLArgumentEncoder.cs +++ b/src/Metal/MTLArgumentEncoder.cs @@ -10,14 +10,14 @@ namespace Metal { public static partial class MTLArgumentEncoder_Extensions { #if NET - public static void SetBuffers (this IMTLArgumentEncoder encoder, IMTLBuffer[] buffers, nuint[] offsets, NSRange range) + public static void SetBuffers (this IMTLArgumentEncoder encoder, IMTLBuffer [] buffers, nuint [] offsets, NSRange range) { if (buffers is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (buffers)); if (offsets is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (offsets)); - var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr[buffers.Length] : new IntPtr [buffers.Length]; + var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr [buffers.Length] : new IntPtr [buffers.Length]; // get all intptr from the array to pass to the lower level call for (var i = 0; i < buffers.Length; i++) { bufferPtrArray [i] = buffers [i].Handle; diff --git a/src/Metal/MTLArrays.cs b/src/Metal/MTLArrays.cs index 0152d4b7f357..8d073882b350 100644 --- a/src/Metal/MTLArrays.cs +++ b/src/Metal/MTLArrays.cs @@ -94,8 +94,7 @@ public MTLPipelineBufferDescriptor this [nuint index] { #if IOS public partial class MTLTileRenderPipelineColorAttachmentDescriptorArray { - public MTLTileRenderPipelineColorAttachmentDescriptor this [nuint index] - { + public MTLTileRenderPipelineColorAttachmentDescriptor this [nuint index] { get { return GetObject (index); } diff --git a/src/Metal/MTLComputeCommandEncoder.cs b/src/Metal/MTLComputeCommandEncoder.cs index d8d38c414c1e..ac6351703dbb 100644 --- a/src/Metal/MTLComputeCommandEncoder.cs +++ b/src/Metal/MTLComputeCommandEncoder.cs @@ -12,14 +12,14 @@ namespace Metal { // add some extension methods to make the API of the protocol nicer public static class IMTLComputeCommandEncoderExtensions { - public static void SetBuffers (this IMTLComputeCommandEncoder table, IMTLBuffer[] buffers, nuint[] offsets, NSRange range) + public static void SetBuffers (this IMTLComputeCommandEncoder table, IMTLBuffer [] buffers, nuint [] offsets, NSRange range) { if (buffers is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (buffers)); if (offsets is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (offsets)); - var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr[buffers.Length] : new IntPtr [buffers.Length]; + var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr [buffers.Length] : new IntPtr [buffers.Length]; // get all intptr from the array to pass to the lower level call for (var i = 0; i < buffers.Length; i++) { bufferPtrArray [i] = buffers [i].Handle; diff --git a/src/Metal/MTLRasterizationRateLayerDescriptor.cs b/src/Metal/MTLRasterizationRateLayerDescriptor.cs index 1c893a8c2682..ac0fb739b845 100644 --- a/src/Metal/MTLRasterizationRateLayerDescriptor.cs +++ b/src/Metal/MTLRasterizationRateLayerDescriptor.cs @@ -9,8 +9,7 @@ #nullable enable namespace Metal { - public partial class MTLRasterizationRateLayerDescriptor - { + public partial class MTLRasterizationRateLayerDescriptor { #if NET [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("ios13.0")] @@ -19,10 +18,10 @@ public partial class MTLRasterizationRateLayerDescriptor #else [MacCatalyst (15,0)] #endif - public double[] HorizontalSampleStorage { + public double [] HorizontalSampleStorage { get { - var width = (int)SampleCount.Width; - var floatArray = new double[width]; + var width = (int) SampleCount.Width; + var floatArray = new double [width]; Marshal.Copy (_HorizontalSampleStorage, floatArray, 0, width); return floatArray; } @@ -36,10 +35,10 @@ public double[] HorizontalSampleStorage { #else [MacCatalyst (15,0)] #endif - public double[] VerticalSampleStorage { + public double [] VerticalSampleStorage { get { - var height = (int)SampleCount.Height; - var floatArray = new double[height]; + var height = (int) SampleCount.Height; + var floatArray = new double [height]; Marshal.Copy (_VerticalSampleStorage, floatArray, 0, height); return floatArray; } @@ -53,7 +52,7 @@ public double[] VerticalSampleStorage { #else [MacCatalyst (15,0)] #endif - static public MTLRasterizationRateLayerDescriptor Create (MTLSize sampleCount, float[] horizontal, float[] vertical) + static public MTLRasterizationRateLayerDescriptor Create (MTLSize sampleCount, float [] horizontal, float [] vertical) { if (horizontal is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (horizontal)); diff --git a/src/Metal/MTLResourceStateCommandEncoder.cs b/src/Metal/MTLResourceStateCommandEncoder.cs index 428fc8ba235b..d79726e4ecfa 100644 --- a/src/Metal/MTLResourceStateCommandEncoder.cs +++ b/src/Metal/MTLResourceStateCommandEncoder.cs @@ -32,7 +32,7 @@ public static partial class MTLResourceStateCommandEncoder_Extensions { [NoMac] [NoTV] #endif - public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTexture texture, MTLSparseTextureMappingMode mode, MTLRegion[] regions, nuint[] mipLevels, nuint[] slices) + public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTexture texture, MTLSparseTextureMappingMode mode, MTLRegion [] regions, nuint [] mipLevels, nuint [] slices) { if (texture is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (texture)); @@ -43,14 +43,14 @@ public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTextur if (slices is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (slices)); - var regionsHandle = GCHandle.Alloc (regions, GCHandleType.Pinned); - var mipLevelsHandle = GCHandle.Alloc (mipLevels, GCHandleType.Pinned); - var slicesHandle = GCHandle.Alloc (slices, GCHandleType.Pinned); + var regionsHandle = GCHandle.Alloc (regions, GCHandleType.Pinned); + var mipLevelsHandle = GCHandle.Alloc (mipLevels, GCHandleType.Pinned); + var slicesHandle = GCHandle.Alloc (slices, GCHandleType.Pinned); try { var regionsPtr = regionsHandle.AddrOfPinnedObject (); var mipLevelsPtr = mipLevelsHandle.AddrOfPinnedObject (); var slicesPtr = slicesHandle.AddrOfPinnedObject (); - This.Update (texture, mode, regionsPtr, mipLevelsPtr, slicesPtr, (nuint)regions.Length); + This.Update (texture, mode, regionsPtr, mipLevelsPtr, slicesPtr, (nuint) regions.Length); } finally { regionsHandle.Free (); mipLevelsHandle.Free (); diff --git a/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs b/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs index 03409a877687..a350281ee0c4 100644 --- a/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs +++ b/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs @@ -12,10 +12,10 @@ namespace MetalPerformanceShadersGraph { /// This enum is used to select how to initialize a new instance of a . #if NET - [SupportedOSPlatform ("ios17.0")] - [SupportedOSPlatform ("maccatalyst17.0")] - [SupportedOSPlatform ("macos14.0")] - [SupportedOSPlatform ("tvos17.0")] + [SupportedOSPlatform ("ios17.0")] + [SupportedOSPlatform ("maccatalyst17.0")] + [SupportedOSPlatform ("macos14.0")] + [SupportedOSPlatform ("tvos17.0")] #else [TV (17, 0), Mac (14, 0), iOS (17, 0), MacCatalyst (17, 0)] #endif diff --git a/src/MetricKit/MXMetaData.cs b/src/MetricKit/MXMetaData.cs index 38ab71eda339..e0df3dcfdecc 100644 --- a/src/MetricKit/MXMetaData.cs +++ b/src/MetricKit/MXMetaData.cs @@ -22,7 +22,7 @@ public partial class MXMetaData { #endif public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14,0)) + if (SystemVersion.CheckiOS (14, 0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/MetricKit/MXMetric.cs b/src/MetricKit/MXMetric.cs index 1aa2230fe4fd..342b2ef0fb04 100644 --- a/src/MetricKit/MXMetric.cs +++ b/src/MetricKit/MXMetric.cs @@ -14,7 +14,7 @@ public partial class MXMetric { public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14,0)) + if (SystemVersion.CheckiOS (14, 0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/MetricKit/MXMetricPayload.cs b/src/MetricKit/MXMetricPayload.cs index 567f5b71f77b..bc4d54a1a0fa 100644 --- a/src/MetricKit/MXMetricPayload.cs +++ b/src/MetricKit/MXMetricPayload.cs @@ -14,7 +14,7 @@ public partial class MXMetricPayload { public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14,0)) + if (SystemVersion.CheckiOS (14, 0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs b/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs index 01d69a593730..a207c9d05efa 100644 --- a/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs +++ b/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs @@ -22,8 +22,7 @@ #endif namespace NearbyInteraction { - public partial class NIAlgorithmConvergenceStatusReasonValues - { + public partial class NIAlgorithmConvergenceStatusReasonValues { #if NET [SupportedOSPlatform ("ios16.0")] [SupportedOSPlatform ("maccatalyst16.0")] diff --git a/src/NearbyInteraction/NINearbyObject.cs b/src/NearbyInteraction/NINearbyObject.cs index 18f691c36940..658e36c83126 100644 --- a/src/NearbyInteraction/NINearbyObject.cs +++ b/src/NearbyInteraction/NINearbyObject.cs @@ -25,22 +25,21 @@ #if __IOS__ namespace NearbyInteraction { - partial class NINearbyObject - { + partial class NINearbyObject { static Vector3? _DirectionNotAvailable; // TODO: https://github.com/xamarin/maccore/issues/2274 // We do not have generator support to trampoline Vector3 -> vector_float3 for Fields - [Field ("NINearbyObjectDirectionNotAvailable", "NearbyInteraction")] + [Field ("NINearbyObjectDirectionNotAvailable", "NearbyInteraction")] public static Vector3 DirectionNotAvailable { get { if (_DirectionNotAvailable is null) { unsafe { - Vector3 *pointer = (Vector3 *) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectDirectionNotAvailable"); + Vector3* pointer = (Vector3*) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectDirectionNotAvailable"); _DirectionNotAvailable = *pointer; } } - return (Vector3)_DirectionNotAvailable; + return (Vector3) _DirectionNotAvailable; } } @@ -55,18 +54,18 @@ public static Vector3 DirectionNotAvailable { [iOS (16,0), MacCatalyst (16,0)] #endif // NET // Following similar strategy found here: https://github.com/xamarin/maccore/issues/2274 - [Field ("NINearbyObjectWorldTransformNotAvailable", "NearbyInteraction")] + [Field ("NINearbyObjectWorldTransformNotAvailable", "NearbyInteraction")] public static MatrixFloat4x4 WorldTransformNotAvailable { get { if (_WorldTransformNotAvailable is null) { unsafe { - MatrixFloat4x4 *pointer = (MatrixFloat4x4 *) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectWorldTransformNotAvailable"); + MatrixFloat4x4* pointer = (MatrixFloat4x4*) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectWorldTransformNotAvailable"); if (pointer is null) throw new PlatformNotSupportedException ("This property is not supported on this version of the OS"); _WorldTransformNotAvailable = *pointer; } } - return (MatrixFloat4x4)_WorldTransformNotAvailable; + return (MatrixFloat4x4) _WorldTransformNotAvailable; } } } diff --git a/src/Network/NWConnection.cs b/src/Network/NWConnection.cs index 5fd4ce6c4ad2..21677dfbdd19 100644 --- a/src/Network/NWConnection.cs +++ b/src/Network/NWConnection.cs @@ -55,7 +55,7 @@ namespace Network { public class NWConnection : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWConnection (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWConnection (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWConnection (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWConnectionGroup.cs b/src/Network/NWConnectionGroup.cs index e2388e91882b..893b191e7af3 100644 --- a/src/Network/NWConnectionGroup.cs +++ b/src/Network/NWConnectionGroup.cs @@ -298,7 +298,7 @@ public void SetStateChangedHandler (NWConnectionGroupStateChangedDelegate handle } #if NET - delegate* unmanaged trampoline= &TrampolineStateChangedHandler; + delegate* unmanaged trampoline = &TrampolineStateChangedHandler; using var block = new BlockLiteral (trampoline, handler, typeof (NWConnectionGroup), nameof (TrampolineStateChangedHandler)); #else using var block = new BlockLiteral (); diff --git a/src/Network/NWEndpoint.cs b/src/Network/NWEndpoint.cs index ccb21c14341a..1f2298edbd08 100644 --- a/src/Network/NWEndpoint.cs +++ b/src/Network/NWEndpoint.cs @@ -35,7 +35,7 @@ namespace Network { public class NWEndpoint : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWEstablishmentReport.cs b/src/Network/NWEstablishmentReport.cs index f04b6fcb2a6d..6fa5da127fec 100644 --- a/src/Network/NWEstablishmentReport.cs +++ b/src/Network/NWEstablishmentReport.cs @@ -98,7 +98,7 @@ public void EnumerateResolutions (Action trampoline = &TrampolineResolutionEnumeratorHandler; - using var block = new BlockLiteral (trampoline, handler, typeof (NWEstablishmentReport),nameof (TrampolineResolutionEnumeratorHandler)); + using var block = new BlockLiteral (trampoline, handler, typeof (NWEstablishmentReport), nameof (TrampolineResolutionEnumeratorHandler)); #else using var block = new BlockLiteral (); block.SetupBlockUnsafe (static_ResolutionEnumeratorHandler, handler); diff --git a/src/Network/NWEthernetChannel.cs b/src/Network/NWEthernetChannel.cs index 1011665380b6..c761c8ea0668 100644 --- a/src/Network/NWEthernetChannel.cs +++ b/src/Network/NWEthernetChannel.cs @@ -18,10 +18,10 @@ using Foundation; using CoreFoundation; -using OS_nw_ethernet_channel=System.IntPtr; -using OS_nw_interface=System.IntPtr; -using OS_dispatch_data=System.IntPtr; -using OS_nw_parameters=System.IntPtr; +using OS_nw_ethernet_channel = System.IntPtr; +using OS_nw_interface = System.IntPtr; +using OS_dispatch_data = System.IntPtr; +using OS_nw_parameters = System.IntPtr; #if !NET @@ -48,7 +48,7 @@ namespace Network { public class NWEthernetChannel : NativeObject { [Preserve (Conditional = true)] - internal NWEthernetChannel (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWEthernetChannel (NativeHandle handle, bool owns) : base (handle, owns) { } [DllImport (Constants.NetworkLibrary)] static extern OS_nw_ethernet_channel nw_ethernet_channel_create (ushort ether_type, OS_nw_interface networkInterface); @@ -89,13 +89,13 @@ public NWEthernetChannel (ushort ethernetType, NWInterface networkInterface) [Mac (13,0)] #endif public NWEthernetChannel (ushort ethernetType, NWInterface networkInterface, NWParameters parameters) => - InitializeHandle (nw_ethernet_channel_create_with_parameters (ethernetType, + InitializeHandle (nw_ethernet_channel_create_with_parameters (ethernetType, networkInterface.GetNonNullHandle (nameof (networkInterface)), parameters.GetNonNullHandle (nameof (parameters)))); [DllImport (Constants.NetworkLibrary)] static extern void nw_ethernet_channel_start (OS_nw_ethernet_channel ethernet_channel); - public void Start () => nw_ethernet_channel_start (GetCheckedHandle ()); + public void Start () => nw_ethernet_channel_start (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] static extern void nw_ethernet_channel_cancel (OS_nw_ethernet_channel ethernet_channel); @@ -160,7 +160,7 @@ public void Send (ReadOnlySpan content, ushort vlanTag, string remoteAddre } [DllImport (Constants.NetworkLibrary)] - unsafe static extern void nw_ethernet_channel_set_receive_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral *handler); + unsafe static extern void nw_ethernet_channel_set_receive_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral* handler); #if !NET delegate void nw_ethernet_channel_receive_handler_t (IntPtr block, OS_dispatch_data content, ushort vlan_tag, IntPtr local_address, IntPtr remote_address); @@ -206,7 +206,7 @@ public void SetReceiveHandler (NWEthernetChannelReceiveDelegate handler) } [DllImport (Constants.NetworkLibrary)] - unsafe static extern void nw_ethernet_channel_set_state_changed_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral *handler); + unsafe static extern void nw_ethernet_channel_set_state_changed_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral* handler); #if !NET delegate void nw_ethernet_channel_state_changed_handler_t (IntPtr block, NWEthernetChannelState state, IntPtr error); @@ -243,7 +243,7 @@ public void SetStateChangesHandler (Action handler) #endif nw_ethernet_channel_set_state_changed_handler (GetCheckedHandle (), &block); } - } + } #if NET [SupportedOSPlatform ("macos13.0")] @@ -262,7 +262,7 @@ public void SetStateChangesHandler (Action handler) #else [Mac (13,0)] #endif - public uint MaximumPayloadSize => nw_ethernet_channel_get_maximum_payload_size (GetCheckedHandle ()); + public uint MaximumPayloadSize => nw_ethernet_channel_get_maximum_payload_size (GetCheckedHandle ()); } } #endif diff --git a/src/Network/NWInterface.cs b/src/Network/NWInterface.cs index b37d41851a4d..5edce0ce0f53 100644 --- a/src/Network/NWInterface.cs +++ b/src/Network/NWInterface.cs @@ -33,7 +33,7 @@ namespace Network { public class NWInterface : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWInterface (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWInterface (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWInterface (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWParameters.cs b/src/Network/NWParameters.cs index 5e562febdd81..c12df72e7be5 100644 --- a/src/Network/NWParameters.cs +++ b/src/Network/NWParameters.cs @@ -36,7 +36,7 @@ namespace Network { public class NWParameters : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWParameters (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWParameters (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWParameters (NativeHandle handle, bool owns) : base (handle, owns) { } #endif @@ -222,7 +222,7 @@ public unsafe static NWParameters CreateUdp (Action? configur [NoiOS] #endif [DllImport (Constants.NetworkLibrary)] - unsafe static extern IntPtr nw_parameters_create_custom_ip (byte custom_ip_protocol_number, BlockLiteral *configure_ip); + unsafe static extern IntPtr nw_parameters_create_custom_ip (byte custom_ip_protocol_number, BlockLiteral* configure_ip); #if NET [SupportedOSPlatform ("macos")] diff --git a/src/Network/NWPath.cs b/src/Network/NWPath.cs index 84c4e1f5595c..8e8ccd3026b2 100644 --- a/src/Network/NWPath.cs +++ b/src/Network/NWPath.cs @@ -32,7 +32,7 @@ namespace Network { public class NWPath : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWPath (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWPath (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWPath (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWPrivacyContext.cs b/src/Network/NWPrivacyContext.cs index eef58bb15bfb..8a8eb745d2a9 100644 --- a/src/Network/NWPrivacyContext.cs +++ b/src/Network/NWPrivacyContext.cs @@ -31,7 +31,7 @@ public class NWPrivacyContext : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolDefinition.cs b/src/Network/NWProtocolDefinition.cs index f96c8cccceb6..95816b3cdda1 100644 --- a/src/Network/NWProtocolDefinition.cs +++ b/src/Network/NWProtocolDefinition.cs @@ -33,7 +33,7 @@ namespace Network { public class NWProtocolDefinition : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolFramerOptions.cs b/src/Network/NWProtocolFramerOptions.cs index 7b49cca2d57d..eacf836029b3 100644 --- a/src/Network/NWProtocolFramerOptions.cs +++ b/src/Network/NWProtocolFramerOptions.cs @@ -22,7 +22,7 @@ using OS_nw_protocol_options = System.IntPtr; using NativeHandle = System.IntPtr; #else -using OS_nw_protocol_options=ObjCRuntime.NativeHandle; +using OS_nw_protocol_options = ObjCRuntime.NativeHandle; #endif namespace Network { diff --git a/src/Network/NWProtocolMetadata.cs b/src/Network/NWProtocolMetadata.cs index 93dbc81c74d4..e36314084129 100644 --- a/src/Network/NWProtocolMetadata.cs +++ b/src/Network/NWProtocolMetadata.cs @@ -58,7 +58,7 @@ public static NWProtocolMetadata CreateUdpMetadata () [Preserve (Conditional = true)] #if NET - internal NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolOptions.cs b/src/Network/NWProtocolOptions.cs index c3d8267019ca..14c6f2692767 100644 --- a/src/Network/NWProtocolOptions.cs +++ b/src/Network/NWProtocolOptions.cs @@ -34,7 +34,7 @@ namespace Network { public class NWProtocolOptions : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolStack.cs b/src/Network/NWProtocolStack.cs index d43e247558eb..8aaacdab0041 100644 --- a/src/Network/NWProtocolStack.cs +++ b/src/Network/NWProtocolStack.cs @@ -36,7 +36,7 @@ namespace Network { public class NWProtocolStack : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProxyConfig.cs b/src/Network/NWProxyConfig.cs index 86c631dd7b37..57a790831af6 100644 --- a/src/Network/NWProxyConfig.cs +++ b/src/Network/NWProxyConfig.cs @@ -29,7 +29,7 @@ namespace Network { public class NWProxyConfig : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWRelayHop.cs b/src/Network/NWRelayHop.cs index d56f895f324a..c2c4018c9bb2 100644 --- a/src/Network/NWRelayHop.cs +++ b/src/Network/NWRelayHop.cs @@ -28,7 +28,7 @@ namespace Network { public class NWRelayHop : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWResolverConfig.cs b/src/Network/NWResolverConfig.cs index 0f0b69bec429..247554347975 100644 --- a/src/Network/NWResolverConfig.cs +++ b/src/Network/NWResolverConfig.cs @@ -30,7 +30,7 @@ public class NWResolverConfig : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/ObjCRuntime/BackingField.cs b/src/ObjCRuntime/BackingField.cs index 8f85291feda5..88fcae65964e 100644 --- a/src/ObjCRuntime/BackingField.cs +++ b/src/ObjCRuntime/BackingField.cs @@ -46,8 +46,7 @@ namespace ObjCRuntime { - static class BackingField - { + static class BackingField { public static T Get (ref T value, IntPtr handle, Converter c) where T : class, INativeObject, IDisposable { diff --git a/src/ObjCRuntime/BindAs.cs b/src/ObjCRuntime/BindAs.cs index 2722caa1cd4a..35b10aede41c 100644 --- a/src/ObjCRuntime/BindAs.cs +++ b/src/ObjCRuntime/BindAs.cs @@ -37,7 +37,7 @@ static T Identity (T obj) return obj; } - unsafe static T[]? ConvertNSArrayToManagedArray (IntPtr nsarray, delegate* convert) where T: struct + unsafe static T []? ConvertNSArrayToManagedArray (IntPtr nsarray, delegate* convert) where T : struct { if (nsarray == IntPtr.Zero) return null; @@ -45,7 +45,7 @@ static T Identity (T obj) return ConvertNSArrayToManagedArray2 (nsarray, convert, &Identity); } - unsafe static IntPtr ConvertManagedArrayToNSArray (T[]? array, delegate* convert) where T: struct + unsafe static IntPtr ConvertManagedArrayToNSArray (T []? array, delegate* convert) where T : struct { if (array is null) return IntPtr.Zero; @@ -53,7 +53,7 @@ unsafe static IntPtr ConvertManagedArrayToNSArray (T[]? array, delegate* (array, &Identity, convert); } - unsafe static T[]? ConvertNSArrayToManagedArray2 (IntPtr nsarray, delegate* convert1, delegate* convert2) where T: struct + unsafe static T []? ConvertNSArrayToManagedArray2 (IntPtr nsarray, delegate* convert1, delegate* convert2) where T : struct { if (nsarray == IntPtr.Zero) return null; @@ -61,7 +61,7 @@ unsafe static IntPtr ConvertManagedArrayToNSArray (T[]? array, delegate* (nsarray, (ptr) => convert2 (convert1 (ptr))); } - unsafe static IntPtr ConvertManagedArrayToNSArray2 (T[]? array, delegate* convert1, delegate* convert2) where T: struct + unsafe static IntPtr ConvertManagedArrayToNSArray2 (T []? array, delegate* convert1, delegate* convert2) where T : struct { if (array is null) return IntPtr.Zero; @@ -90,14 +90,14 @@ unsafe static IntPtr ConvertManagedArrayToNSArray2 (T[]? array, delegate* (IntPtr handle, delegate* convert) where T: struct + unsafe static T? CreateNullable (IntPtr handle, delegate* convert) where T : struct { if (handle == IntPtr.Zero) return null; return convert (handle); } - unsafe static T? CreateNullable2 (IntPtr handle, delegate* convert1, delegate* convert2) where T: struct + unsafe static T? CreateNullable2 (IntPtr handle, delegate* convert1, delegate* convert2) where T : struct { if (handle == IntPtr.Zero) return null; diff --git a/src/ObjCRuntime/Blocks.cs b/src/ObjCRuntime/Blocks.cs index cb3b4091fbe3..2c3389e1c9a9 100644 --- a/src/ObjCRuntime/Blocks.cs +++ b/src/ObjCRuntime/Blocks.cs @@ -410,7 +410,7 @@ public object Target { } #if NET - public T GetDelegateForBlock () where T: System.MulticastDelegate + public T GetDelegateForBlock () where T : System.MulticastDelegate #else public T GetDelegateForBlock () where T : class #endif @@ -419,7 +419,7 @@ public T GetDelegateForBlock () where T : class } #if NET - public unsafe static T GetTarget (IntPtr block) where T: System.MulticastDelegate + public unsafe static T GetTarget (IntPtr block) where T : System.MulticastDelegate #else public unsafe static T GetTarget (IntPtr block) where T : class /* /* requires C# 7.3+: System.MulticastDelegate */ #endif @@ -443,9 +443,9 @@ public static bool IsManagedBlock (IntPtr block) // This method doesn't necessarily work with NativeAOT, but this is covered by the exception, because the managed static registrar is required for NativeAOT. // // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.Interfaces' in call to 'System.Type.GetInterfaces()'. The return value of method 'System.Reflection.MemberInfo.DeclaringType.get' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - [UnconditionalSuppressMessage("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] // IL2062: Value passed to parameter 'interfaceType' of method 'System.Type.GetInterfaceMap(Type)' can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - [UnconditionalSuppressMessage("", "IL2062", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2062", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif static Type GetDelegateProxyType (MethodInfo minfo, uint token_ref, out MethodInfo baseMethod) { @@ -499,7 +499,7 @@ static Type GetDelegateProxyType (MethodInfo minfo, uint token_ref, out MethodIn [BindingImpl (BindingImplOptions.Optimizable)] unsafe static IntPtr GetBlockForFunctionPointer (MethodInfo delegateInvokeMethod, object @delegate, string signature) { - void* invokeFunctionPointer = (void *) delegateInvokeMethod.MethodHandle.GetFunctionPointer (); + void* invokeFunctionPointer = (void*) delegateInvokeMethod.MethodHandle.GetFunctionPointer (); if (signature is null) { if (!Runtime.DynamicRegistrationSupported) throw ErrorHelper.CreateError (8026, $"BlockLiteral.GetBlockForDelegate with a null signature is not supported when the dynamic registrar has been linked away (delegate type: {@delegate.GetType ().FullName})."); @@ -547,7 +547,7 @@ static IntPtr CreateBlockForDelegate (Delegate @delegate, Delegate delegateProxy // // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicFields' in call to 'System.Type.GetField(String, BindingFlags)'. The return value of method 'ObjCRuntime.BlockLiteral.GetDelegateProxyType(MethodInfo, UInt32, MethodInfo&)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Type.GetMethod(String, BindingFlags)'. The return value of method 'ObjCRuntime.BlockLiteral.GetDelegateProxyType(MethodInfo, UInt32, MethodInfo&)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to." - [UnconditionalSuppressMessage("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif internal static IntPtr GetBlockForDelegate (MethodInfo minfo, object @delegate, uint token_ref, string signature) { diff --git a/src/ObjCRuntime/Class.cs b/src/ObjCRuntime/Class.cs index 4135e6d8cb9d..1bfa062aebbb 100644 --- a/src/ObjCRuntime/Class.cs +++ b/src/ObjCRuntime/Class.cs @@ -537,7 +537,7 @@ internal static unsafe int FindMapIndex (Runtime.MTClassMap* array, int lo, int // // IL2026: Using member 'System.Reflection.Module.ResolveMethod(Int32)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Trimming changes metadata tokens. // IL2026: Using member 'System.Reflection.Module.ResolveType(Int32)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Trimming changes metadata tokens. - [UnconditionalSuppressMessage("", "IL2026", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2026", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif static MemberInfo? ResolveTokenNonManagedStatic (Assembly assembly, Module? module, uint token) { diff --git a/src/ObjCRuntime/DelayedRegistrationAttribute.cs b/src/ObjCRuntime/DelayedRegistrationAttribute.cs index 097d486714f2..c1b57b383a01 100644 --- a/src/ObjCRuntime/DelayedRegistrationAttribute.cs +++ b/src/ObjCRuntime/DelayedRegistrationAttribute.cs @@ -29,8 +29,7 @@ namespace ObjCRuntime { [AttributeUsage (AttributeTargets.Assembly)] - public abstract class DelayedRegistrationAttribute : Attribute - { + public abstract class DelayedRegistrationAttribute : Attribute { public abstract bool Delay { get; } } } diff --git a/src/ObjCRuntime/Dlfcn.cs b/src/ObjCRuntime/Dlfcn.cs index a1b10999b496..725be061da61 100644 --- a/src/ObjCRuntime/Dlfcn.cs +++ b/src/ObjCRuntime/Dlfcn.cs @@ -56,8 +56,7 @@ static public class LibC { static public readonly IntPtr Handle = Dlfcn._dlopen (Constants.libcLibrary, 0); } #if HAS_OPENGLES - static public class OpenGLES - { + static public class OpenGLES { static public readonly IntPtr Handle = Dlfcn._dlopen (Constants.OpenGLESLibrary, 0); } #endif diff --git a/src/ObjCRuntime/INativeObject.cs b/src/ObjCRuntime/INativeObject.cs index f464c21fd741..aa4823b9642f 100644 --- a/src/ObjCRuntime/INativeObject.cs +++ b/src/ObjCRuntime/INativeObject.cs @@ -21,7 +21,7 @@ NativeHandle Handle { // The method will be implemented via custom linker step if the managed static registrar is used // for classes which have an (NativeHandle, bool) or (IntPtr, bool) constructor. // This method will be made public when the managed static registrar is used. - [MethodImpl(MethodImplOptions.NoInlining)] + [MethodImpl (MethodImplOptions.NoInlining)] internal static virtual INativeObject? _Xamarin_ConstructINativeObject (NativeHandle handle, bool owns) => null; #endif } diff --git a/src/ObjCRuntime/NativeHandle.cs b/src/ObjCRuntime/NativeHandle.cs index d9f1453b2e1b..9844e9d25e03 100644 --- a/src/ObjCRuntime/NativeHandle.cs +++ b/src/ObjCRuntime/NativeHandle.cs @@ -72,10 +72,10 @@ public static implicit operator NativeHandle (IntPtr value) public unsafe static explicit operator void* (NativeHandle value) { - return (void *) (IntPtr) value; + return (void*) (IntPtr) value; } - public unsafe static explicit operator NativeHandle (void * value) + public unsafe static explicit operator NativeHandle (void* value) { return new NativeHandle ((IntPtr) value); } diff --git a/src/ObjCRuntime/PlatformAvailability.cs b/src/ObjCRuntime/PlatformAvailability.cs index 41887c7773b8..9f455bfdcd26 100644 --- a/src/ObjCRuntime/PlatformAvailability.cs +++ b/src/ObjCRuntime/PlatformAvailability.cs @@ -568,7 +568,7 @@ public MacAttribute (byte major, byte minor, PlatformArchitecture arch) public MacAttribute (byte major, byte minor, byte subminor) #if NET - : base ((Platform)((ulong)major << 48 | (ulong)minor << 40 | (ulong)subminor << 32)) + : base ((Platform) ((ulong) major << 48 | (ulong) minor << 40 | (ulong) subminor << 32)) #else : this (major, minor, subminor, false) #endif diff --git a/src/ObjCRuntime/RegistrarHelper.cs b/src/ObjCRuntime/RegistrarHelper.cs index f5ba5b46b689..c145d6e8f844 100644 --- a/src/ObjCRuntime/RegistrarHelper.cs +++ b/src/ObjCRuntime/RegistrarHelper.cs @@ -69,7 +69,7 @@ internal static void Initialize () wrapper_types = new Dictionary (RuntimeTypeHandleEqualityComparer); } - static NativeHandle CreateCFArray (params string[]? values) + static NativeHandle CreateCFArray (params string []? values) { if (values is null) return NativeHandle.Zero; @@ -252,9 +252,9 @@ static NativeHandle ManagedArrayToNSArray (object array, bool retain) return NativeHandle.Zero; NSObject rv; - if (array is NSObject[] nsobjs) { + if (array is NSObject [] nsobjs) { rv = NSArray.FromNSObjects (nsobjs); - } else if (array is INativeObject[] inativeobjs) { + } else if (array is INativeObject [] inativeobjs) { rv = NSArray.FromNSObjects (inativeobjs); } else { throw new InvalidOperationException ($"Can't convert {array.GetType ()} to an NSArray."); // FIXME: better error @@ -265,7 +265,7 @@ static NativeHandle ManagedArrayToNSArray (object array, bool retain) return Runtime.RetainAndAutoreleaseNSObject (rv); } - unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string[]? value, ref string[]? copy) + unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string []? value, ref string []? copy) { if (ptr is not null) { value = NSArray.StringArrayFromHandle (*ptr); @@ -275,7 +275,7 @@ unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string[]? copy = value; } - unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string[] value, string[] copy, bool isOut) + unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string [] value, string [] copy, bool isOut) { if (ptr is null) return; @@ -301,7 +301,7 @@ unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string[] value *ptr = rv; } - unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T[]? value, ref T[]? copy) where T: class, INativeObject + unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T []? value, ref T []? copy) where T : class, INativeObject { if (ptr is not null) { value = NSArray.ArrayFromHandle (*ptr); @@ -311,7 +311,7 @@ unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T[]? value, re copy = value; } - unsafe static void NSArray_managed_to_native (IntPtr* ptr, T[] value, T[] copy, bool isOut) where T: class, INativeObject + unsafe static void NSArray_managed_to_native (IntPtr* ptr, T [] value, T [] copy, bool isOut) where T : class, INativeObject { if (ptr is null) { #if TRACE @@ -340,7 +340,7 @@ unsafe static void NSArray_managed_to_native (IntPtr* ptr, T[] value, T[] cop *ptr = rv; } - unsafe static void NSObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy) where T: NSObject + unsafe static void NSObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy) where T : NSObject { if (ptr is not null) { value = Runtime.GetNSObject (*ptr, owns: false); @@ -371,7 +371,7 @@ unsafe static void NSObject_managed_to_native (IntPtr* ptr, NSObject value, NSOb *ptr = rv; } - unsafe static void string_native_to_managed (NativeHandle *ptr, ref string? value, ref string? copy) + unsafe static void string_native_to_managed (NativeHandle* ptr, ref string? value, ref string? copy) { if (ptr is not null) { value = CFString.FromHandle (*ptr); @@ -381,7 +381,7 @@ unsafe static void string_native_to_managed (NativeHandle *ptr, ref string? valu copy = value; } - unsafe static void string_managed_to_native (NativeHandle *ptr, string value, string copy, bool isOut) + unsafe static void string_managed_to_native (NativeHandle* ptr, string value, string copy, bool isOut) { if (ptr is null) { #if TRACE @@ -402,7 +402,7 @@ unsafe static void string_managed_to_native (NativeHandle *ptr, string value, st *ptr = rv; } - unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy, RuntimeTypeHandle implementationType) where T: class, INativeObject + unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy, RuntimeTypeHandle implementationType) where T : class, INativeObject { if (ptr is not null) { value = Runtime.GetINativeObject (*ptr, implementation: Type.GetTypeFromHandle (implementationType), forced_type: false, owns: false); @@ -412,7 +412,7 @@ unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value copy = value; } - unsafe static void INativeObject_managed_to_native (IntPtr *ptr, INativeObject value, INativeObject copy, bool isOut) + unsafe static void INativeObject_managed_to_native (IntPtr* ptr, INativeObject value, INativeObject copy, bool isOut) { if (ptr is null) { #if TRACE diff --git a/src/ObjCRuntime/RequiredFrameworkAttribute.cs b/src/ObjCRuntime/RequiredFrameworkAttribute.cs index afc789075980..ac1b8cc56505 100644 --- a/src/ObjCRuntime/RequiredFrameworkAttribute.cs +++ b/src/ObjCRuntime/RequiredFrameworkAttribute.cs @@ -29,11 +29,10 @@ namespace ObjCRuntime { - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public class RequiredFrameworkAttribute : Attribute - { + [AttributeUsage (AttributeTargets.Assembly, AllowMultiple = true)] + public class RequiredFrameworkAttribute : Attribute { public string Name { get; private set; } - + public RequiredFrameworkAttribute (string name) { Name = name; diff --git a/src/ObjCRuntime/Runtime.CoreCLR.cs b/src/ObjCRuntime/Runtime.CoreCLR.cs index 3de830102738..f7a1f4cdf369 100644 --- a/src/ObjCRuntime/Runtime.CoreCLR.cs +++ b/src/ObjCRuntime/Runtime.CoreCLR.cs @@ -37,7 +37,7 @@ using Xamarin.Bundler; -using MonoObjectPtr=System.IntPtr; +using MonoObjectPtr = System.IntPtr; namespace ObjCRuntime { @@ -98,7 +98,7 @@ static void log_coreclr (string message) // Define VERBOSE_LOG at the top of this file to get all printfs [System.Diagnostics.Conditional ("VERBOSE_LOG")] - static void log_coreclr_render (string message, params object?[] argumentsToRender) + static void log_coreclr_render (string message, params object? [] argumentsToRender) { var args = new string [argumentsToRender.Length]; for (var i = 0; i < args.Length; i++) { @@ -212,7 +212,7 @@ internal static GCHandle CreateTrackingGCHandle (NSObject obj, IntPtr handle) unsafe { TrackedObjectInfo* tracked_info; fixed (void* ptr = info) - tracked_info = (TrackedObjectInfo *) ptr; + tracked_info = (TrackedObjectInfo*) ptr; tracked_info->Handle = handle; tracked_info->Flags = obj.FlagsInternal; obj.tracked_object_info = tracked_info; @@ -264,7 +264,7 @@ internal static void RegisterToggleReferenceCoreCLR (NSObject obj, IntPtr handle } // Returns a retained MonoObject. Caller must release. - [UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "This method is only called to retrieve the assembly where the entry point is, and the entry point is not trimmed away, so this is safe.")] + [UnconditionalSuppressMessage ("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "This method is only called to retrieve the assembly where the entry point is, and the entry point is not trimmed away, so this is safe.")] static IntPtr FindAssembly (IntPtr assembly_name) { if (IsNativeAOT) @@ -306,7 +306,7 @@ static unsafe void SetPendingException (MonoObject* exception_obj) ObjectiveCMarshal.SetMessageSendPendingException (exc); } - unsafe static sbyte IsClassOfType (MonoObject *typeobj, TypeLookup match) + unsafe static sbyte IsClassOfType (MonoObject* typeobj, TypeLookup match) { var rv = IsClassOfType ((Type?) GetMonoObjectTarget (typeobj), match); return (sbyte) (rv ? 1 : 0); @@ -459,7 +459,7 @@ static IntPtr GetMonoObjectImpl (object obj) return null; unsafe { - MonoObject *monoobj = (MonoObject *) mobj; + MonoObject* monoobj = (MonoObject*) mobj; return GetGCHandleTarget (monoobj->GCHandle); } } @@ -469,7 +469,7 @@ static IntPtr GetMonoObjectImpl (object obj) static extern void xamarin_bridge_log_monoobject (IntPtr mono_object, string stack_trace); #endif - static IntPtr MarshalStructure (T value) where T: unmanaged + static IntPtr MarshalStructure (T value) where T : unmanaged { var destination = Marshal.AllocHGlobal (Marshal.SizeOf ()); @@ -564,10 +564,10 @@ static byte GetFlagsForNSObject (IntPtr gchandle) return (byte) obj.FlagsInternal; } - static unsafe MonoObject* GetMethodDeclaringType (MonoObject *mobj) + static unsafe MonoObject* GetMethodDeclaringType (MonoObject* mobj) { var method = (MethodBase) GetMonoObjectTarget (mobj)!; - return (MonoObject *) GetMonoObject (method.DeclaringType); + return (MonoObject*) GetMonoObject (method.DeclaringType); } static IntPtr ObjectGetType (MonoObjectPtr mobj) @@ -611,16 +611,16 @@ static unsafe IntPtr GetMethodSignature (MonoObject* methodobj) var parameterCount = parameters.Length; var rv = Marshal.AllocHGlobal (sizeof (MonoMethodSignature) + sizeof (MonoObjectPtr) * parameterCount); - MonoMethodSignature* signature = (MonoMethodSignature *) rv; + MonoMethodSignature* signature = (MonoMethodSignature*) rv; signature->Method = methodobj; xamarin_mono_object_retain (methodobj); signature->ParameterCount = parameterCount; - signature->ReturnType = (MonoObject *) GetMonoObject (GetMethodReturnType (method)); + signature->ReturnType = (MonoObject*) GetMonoObject (GetMethodReturnType (method)); MonoObject** mparams = &signature->Parameters; for (var i = 0; i < parameterCount; i++) { var p = parameters [i]; - mparams [i] = (MonoObject *) GetMonoObject (p.ParameterType); + mparams [i] = (MonoObject*) GetMonoObject (p.ParameterType); } return rv; @@ -638,14 +638,14 @@ static unsafe IntPtr GetMethodSignature (MonoObject* methodobj) return null; } - unsafe static IntPtr ClassGetNamespace (MonoObject *typeobj) + unsafe static IntPtr ClassGetNamespace (MonoObject* typeobj) { var type = (Type?) GetMonoObjectTarget (typeobj); var rv = type?.Namespace; return Marshal.StringToHGlobalAuto (rv); } - unsafe static IntPtr ClassGetName (MonoObject *typeobj) + unsafe static IntPtr ClassGetName (MonoObject* typeobj) { var type = (Type?) GetMonoObjectTarget (typeobj); var rv = type?.Name; @@ -658,7 +658,7 @@ unsafe static IntPtr ClassGetName (MonoObject *typeobj) var type = (Type?) GetMonoObjectTarget (typeobj); if (type?.IsByRef == true) type = type.GetElementType (); - return (MonoObject *) GetMonoObject (type); + return (MonoObject*) GetMonoObject (type); } static unsafe int SizeOf (MonoObject* typeobj) @@ -682,7 +682,7 @@ static int SizeOf (Type type) var method = (MethodBase) GetMonoObjectTarget (methodobj)!; var instance = GetMonoObjectTarget (instanceobj)!; var rv = InvokeMethod (method, instance, native_parameters); - return (MonoObject *) GetMonoObject (rv); + return (MonoObject*) GetMonoObject (rv); } // Return value: NULL or a MonoObject* that must be released with xamarin_mono_object_safe_release. @@ -744,7 +744,7 @@ static int SizeOf (Type type) log_coreclr ($" IsClass/IsInterface/IsNullable IsByRef: {isByRef} IsOut: {p.IsOut} ParameterType: {paramType}"); if (nativeParam != IntPtr.Zero) { unsafe { - MonoObject* mono_obj = (MonoObject *) nativeParam; + MonoObject* mono_obj = (MonoObject*) nativeParam; // dereference if it's a byref type if (isByRef) mono_obj = *(MonoObject**) mono_obj; @@ -788,7 +788,7 @@ static int SizeOf (Type type) try { rv = method.Invoke (instance, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, parameters, null); - } catch (TargetInvocationException tie) { + } catch (TargetInvocationException tie) { var ex = tie.InnerException ?? tie; // This will re-throw the original exception and preserve the stacktrace. ExceptionDispatchInfo.Capture (ex).Throw (); @@ -855,7 +855,7 @@ static unsafe IntPtr StringToUtf8 (MonoObject* obj) static unsafe MonoObject* NewString (IntPtr text) { - return (MonoObject *) GetMonoObject (Marshal.PtrToStringAuto (text)); + return (MonoObject*) GetMonoObject (Marshal.PtrToStringAuto (text)); } static unsafe MonoObject* CreateArray (MonoObject* typeobj, ulong elements) @@ -874,14 +874,14 @@ static unsafe ulong GetArrayLength (MonoObject* obj) return (ulong) array.Length; } - static unsafe void SetArrayObjectValue (MonoObject *arrayobj, ulong index, MonoObject *mobj) + static unsafe void SetArrayObjectValue (MonoObject* arrayobj, ulong index, MonoObject* mobj) { var array = (Array) GetMonoObjectTarget (arrayobj)!; var obj = GetMonoObjectTarget (mobj); array.SetValue (obj, (long) index); } - static unsafe void SetArrayStructValue (MonoObject *arrayobj, ulong index, MonoObject *typeobj, IntPtr valueptr) + static unsafe void SetArrayStructValue (MonoObject* arrayobj, ulong index, MonoObject* typeobj, IntPtr valueptr) { var array = (Array) GetMonoObjectTarget (arrayobj)!; var elementType = (Type) GetMonoObjectTarget (typeobj)!; @@ -893,14 +893,14 @@ static unsafe void SetArrayStructValue (MonoObject *arrayobj, ulong index, MonoO { var array = (Array) GetMonoObjectTarget (arrayobj)!; var obj = array.GetValue ((long) index); - return (MonoObject *) GetMonoObject (obj); + return (MonoObject*) GetMonoObject (obj); } static unsafe MonoObject* Box (MonoObject* typeobj, IntPtr value) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = Box (type, value); - return (MonoObject *) GetMonoObject (rv); + return (MonoObject*) GetMonoObject (rv); } static object? Box (Type type, IntPtr value) @@ -948,21 +948,21 @@ static bool IsNullable (Type type) return false; } - unsafe static sbyte IsByRef (MonoObject *typeobj) + unsafe static sbyte IsByRef (MonoObject* typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsByRef; return (sbyte) (rv ? 1 : 0); } - unsafe static sbyte IsValueType (MonoObject *typeobj) + unsafe static sbyte IsValueType (MonoObject* typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsValueType; return (sbyte) (rv ? 1 : 0); } - unsafe static sbyte IsEnum (MonoObject *typeobj) + unsafe static sbyte IsEnum (MonoObject* typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsEnum; diff --git a/src/ObjCRuntime/Runtime.cs b/src/ObjCRuntime/Runtime.cs index 66aedf65af84..138e94b76e5a 100644 --- a/src/ObjCRuntime/Runtime.cs +++ b/src/ObjCRuntime/Runtime.cs @@ -177,8 +177,8 @@ internal enum InitializationFlags : int { /* unused = 0x08,*/ IsSimulator = 0x10, #if NET - IsCoreCLR = 0x20, - IsNativeAOT = 0x40, + IsCoreCLR = 0x20, + IsNativeAOT = 0x40, #endif } @@ -226,8 +226,7 @@ public bool IsSimulator { internal static unsafe InitializationOptions* options; #if NET - public static class ClassHandles - { + public static class ClassHandles { static NativeHandle unused; internal static unsafe void InitializeClassHandles (IntPtr* map) { @@ -238,7 +237,7 @@ internal static unsafe void InitializeClassHandles (IntPtr* map) // Rewriter uses those. // In the case of NO class handle rewriting, // this is a no-op - fixed (NativeHandle *ptr = &unused) { + fixed (NativeHandle* ptr = &unused) { SetHandle (-1, ptr, map); } } @@ -248,9 +247,9 @@ internal static unsafe void SetHandle (int index, NativeHandle* handle, IntPtr* { if (index < 0) return; - + var nativeHandle = map [index]; - *handle = (NativeHandle)nativeHandle; + *handle = (NativeHandle) nativeHandle; } } #endif @@ -297,10 +296,10 @@ internal static bool Initialized { [DllImport (Constants.libcLibrary)] unsafe static extern int _NSGetExecutablePath (byte* buf, int* bufsize); - unsafe static int _NSGetExecutablePath (byte[] buf, ref int bufsize) + unsafe static int _NSGetExecutablePath (byte [] buf, ref int bufsize) { fixed (byte* bufptr = buf) - return _NSGetExecutablePath (bufptr, (int *) Unsafe.AsPointer (ref bufsize)); + return _NSGetExecutablePath (bufptr, (int*) Unsafe.AsPointer (ref bufsize)); } #endif @@ -460,8 +459,7 @@ static bool ThreadPoolDispatcher (Func callback) static bool OnAssemblyRegistration (AssemblyName assembly_name) { if (AssemblyRegistration is not null) { - var args = new AssemblyRegistrationEventArgs - { + var args = new AssemblyRegistrationEventArgs { Register = true, AssemblyName = assembly_name }; @@ -786,14 +784,13 @@ public static void RegisterAssembly (Assembly a) var attributes = a.GetCustomAttributes (typeof (RequiredFrameworkAttribute), false); foreach (var attribute in attributes) { - var requiredFramework = (RequiredFrameworkAttribute)attribute; + var requiredFramework = (RequiredFrameworkAttribute) attribute; string libPath; string libName = requiredFramework.Name; if (libName.Contains (".dylib")) { libPath = ResourcesPath!; - } - else { + } else { libPath = FrameworksPath!; libPath = Path.Combine (libPath, libName); libName = libName.Replace (".frameworks", ""); @@ -802,7 +799,7 @@ public static void RegisterAssembly (Assembly a) if (Dlfcn.dlopen (libPath, 0) == IntPtr.Zero) throw new Exception ($"Unable to load required framework: '{requiredFramework.Name}'", - new Exception (Dlfcn.dlerror())); + new Exception (Dlfcn.dlerror ())); } attributes = a.GetCustomAttributes (typeof (DelayedRegistrationAttribute), false); @@ -1607,7 +1604,7 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM // If type is an NSObject, we prefer the NSObject lookup table if (instance is null && type != typeof (NSObject) && type.IsSubclassOf (typeof (NSObject))) { - instance = (T?)(INativeObject?) RegistrarHelper.ConstructNSObject (type, nativeHandle); + instance = (T?) (INativeObject?) RegistrarHelper.ConstructNSObject (type, nativeHandle); if (instance is not null && owns) { Runtime.TryReleaseINativeObject (instance); } @@ -2146,7 +2143,7 @@ static Type LookupINativeObjectImplementation (IntPtr ptr, Type target_type, Typ // For other registrars other than managed-static the generic parameter of ConstructNSObject is used // only to cast the return value so we can safely pass NSObject here to satisfy the constraints of the // generic parameter. - var rv = (T?)(INativeObject?) ConstructNSObject (ptr, implementation, MissingCtorResolution.ThrowConstructor1NotFound, sel, method_handle); + var rv = (T?) (INativeObject?) ConstructNSObject (ptr, implementation, MissingCtorResolution.ThrowConstructor1NotFound, sel, method_handle); if (owns) TryReleaseINativeObject (rv); return rv; diff --git a/src/ObjCRuntime/Runtime.mac.cs b/src/ObjCRuntime/Runtime.mac.cs index d8630d44ee69..56b55d9e03b8 100644 --- a/src/ObjCRuntime/Runtime.mac.cs +++ b/src/ObjCRuntime/Runtime.mac.cs @@ -54,9 +54,9 @@ public static string? FrameworksPath { public static string? ResourcesPath { get; set; } - + delegate void initialize_func (); - unsafe delegate sbyte *get_sbyteptr_func (); + unsafe delegate sbyte* get_sbyteptr_func (); #if !NET // There's a different implementation for other platforms + .NET macOS in Runtime.cs static volatile bool originalWorkingDirectoryIsSet; diff --git a/src/PassKit/PKCompat.cs b/src/PassKit/PKCompat.cs index d8e889f5785b..de76bf7fdb6f 100644 --- a/src/PassKit/PKCompat.cs +++ b/src/PassKit/PKCompat.cs @@ -87,7 +87,7 @@ public unsafe virtual void AuthorizeDisbursement (global::System.Action> AuthorizeDisbursementAsync () + public unsafe virtual Task> AuthorizeDisbursementAsync () { throw new InvalidOperationException (Constants.RemovedFromPassKit); } @@ -125,8 +125,7 @@ protected override void Dispose (bool disposing) #endif // NET [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("This class is removed.")] - public partial interface IPKDisbursementAuthorizationControllerDelegate : INativeObject, IDisposable - { + public partial interface IPKDisbursementAuthorizationControllerDelegate : INativeObject, IDisposable { void DidAuthorize (PKDisbursementAuthorizationController controller, PKDisbursementVoucher disbursementVoucher); void DidFinish (PKDisbursementAuthorizationController controller); } diff --git a/src/PdfKit/Enums.cs b/src/PdfKit/Enums.cs index cd3ff0ac0476..45cba05bb9cf 100644 --- a/src/PdfKit/Enums.cs +++ b/src/PdfKit/Enums.cs @@ -39,37 +39,37 @@ namespace PdfKit { [Native] [TV (18, 2)] public enum PdfActionNamedName : long { - None = 0, - NextPage = 1, + None = 0, + NextPage = 1, PreviousPage = 2, - FirstPage = 3, - LastPage = 4, - GoBack = 5, - GoForward = 6, - GoToPage = 7, - Find = 8, - Print = 9, - ZoomIn = 10, - ZoomOut = 11 + FirstPage = 3, + LastPage = 4, + GoBack = 5, + GoForward = 6, + GoToPage = 7, + Find = 8, + Print = 9, + ZoomIn = 10, + ZoomOut = 11 } [Native] [TV (18, 2)] public enum PdfWidgetControlType : long { - Unknown = -1, - PushButton = 0, + Unknown = -1, + PushButton = 0, RadioButton = 1, - CheckBox = 2 + CheckBox = 2 } [Native] [TV (18, 2)] public enum PdfLineStyle : long { - None = 0, - Square = 1, - Circle = 2, - Diamond = 3, - OpenArrow = 4, + None = 0, + Square = 1, + Circle = 2, + Diamond = 3, + OpenArrow = 4, ClosedArrow = 5 } @@ -79,28 +79,28 @@ public enum PdfMarkupType : long { Highlight = 0, StrikeOut = 1, Underline = 2, - Redact = 3, + Redact = 3, } [Native] [TV (18, 2)] public enum PdfTextAnnotationIconType : long { - Comment = 0, - Key = 1, - Note = 2, - Help = 3, + Comment = 0, + Key = 1, + Note = 2, + Help = 3, NewParagraph = 4, - Paragraph = 5, - Insert = 6 + Paragraph = 5, + Insert = 6 } [Native] [TV (18, 2)] public enum PdfBorderStyle : long { - Solid = 0, - Dashed = 1, - Beveled = 2, - Inset = 3, + Solid = 0, + Dashed = 1, + Beveled = 2, + Inset = 3, Underline = 4 } @@ -110,16 +110,16 @@ public enum PdfBorderStyle : long { [Unavailable (PlatformName.MacCatalyst)] [Native] public enum PdfPrintScalingMode : long { - None = 0, - ToFit = 1, + None = 0, + ToFit = 1, DownToFit = 2 } [Native] [TV (18, 2)] public enum PdfDocumentPermissions : long { - None = 0, - User = 1, + None = 0, + User = 1, Owner = 2 } @@ -127,36 +127,36 @@ public enum PdfDocumentPermissions : long { [TV (18, 2)] public enum PdfDisplayBox : long { Media = 0, - Crop = 1, + Crop = 1, Bleed = 2, - Trim = 3, - Art = 4 + Trim = 3, + Art = 4 } [Native] [TV (18, 2)] public enum PdfDisplayMode : long { - SinglePage = 0, + SinglePage = 0, SinglePageContinuous = 1, - TwoUp = 2, - TwoUpContinuous = 3 + TwoUp = 2, + TwoUpContinuous = 3 } [Flags] [Native] [TV (18, 2)] public enum PdfAreaOfInterest : long { - NoArea = 0, - PageArea = 1 << 0, - TextArea = 1 << 1, + NoArea = 0, + PageArea = 1 << 0, + TextArea = 1 << 1, AnnotationArea = 1 << 2, - LinkArea = 1 << 3, - ControlArea = 1 << 4, - TextFieldArea = 1 << 5, - IconArea = 1 << 6, - PopupArea = 1 << 7, - ImageArea = 1 << 8, - [iOS (15,0), MacCatalyst (15,0)] + LinkArea = 1 << 3, + ControlArea = 1 << 4, + TextFieldArea = 1 << 5, + IconArea = 1 << 6, + PopupArea = 1 << 7, + ImageArea = 1 << 8, + [iOS (15, 0), MacCatalyst (15, 0)] AnyArea = Int64.MaxValue, } diff --git a/src/PhotosUI/PHEnums.cs b/src/PhotosUI/PHEnums.cs index 8753917b1c49..5673e478f07b 100644 --- a/src/PhotosUI/PHEnums.cs +++ b/src/PhotosUI/PHEnums.cs @@ -14,7 +14,9 @@ public enum PHLivePhotoViewPlaybackStyle : long { } #if MONOMAC - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] [Native] public enum PHLivePhotoViewContentMode : long { AspectFit, diff --git a/src/QuickLook/Thumbnail.cs b/src/QuickLook/Thumbnail.cs index fa43d8107ead..8f7f0f0d2c23 100644 --- a/src/QuickLook/Thumbnail.cs +++ b/src/QuickLook/Thumbnail.cs @@ -52,7 +52,7 @@ public static partial class QLThumbnailImage { #else [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use the QuickLookThumbnailing framework instead for creating thumbnails for files.")] #endif - [DllImport(Constants.QuickLookLibrary)] + [DllImport (Constants.QuickLookLibrary)] extern static /* CGImageRef */ IntPtr QLThumbnailImageCreate (/* CFAllocatorRef */ IntPtr allocator, /* CFUrlRef */ IntPtr url, CGSize maxThumbnailSize, /* CFDictionaryRef */ IntPtr options); #if NET @@ -76,12 +76,12 @@ public static partial class QLThumbnailImage { dictionary.LowlevelSetObject ((NSNumber) scaleFactor, OptionScaleFactorKey.Handle); dictionary.LowlevelSetObject (iconMode ? CFBoolean.TrueHandle : CFBoolean.FalseHandle, OptionIconModeKey.Handle); } - + var handle = QLThumbnailImageCreate (IntPtr.Zero, url.Handle, maxThumbnailSize, dictionary.GetHandle ()); GC.KeepAlive (dictionary); if (handle != IntPtr.Zero) return new CGImage (handle, true); - + return null; } } diff --git a/src/SceneKit/Defs.cs b/src/SceneKit/Defs.cs index 8f1d6da893bf..8ebb75bc6fdc 100644 --- a/src/SceneKit/Defs.cs +++ b/src/SceneKit/Defs.cs @@ -276,10 +276,12 @@ public enum SCNAntialiasingMode : ulong { Multisampling2X, Multisampling4X, #if MONOMAC || __MACCATALYST__ - [NoiOS][NoTV] + [NoiOS] + [NoTV] [NoMacCatalyst] Multisampling8X, - [NoiOS][NoTV] + [NoiOS] + [NoTV] [NoMacCatalyst] Multisampling16X, #endif @@ -361,11 +363,17 @@ public enum SCNRenderingApi : ulong { [NoMac] OpenGLES2, #else - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] OpenGLLegacy, - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] OpenGLCore32, - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] OpenGLCore41, #endif } diff --git a/src/SceneKit/SCNMatrix4_dotnet.cs b/src/SceneKit/SCNMatrix4_dotnet.cs index ffb1efc0484d..6f685e707d19 100644 --- a/src/SceneKit/SCNMatrix4_dotnet.cs +++ b/src/SceneKit/SCNMatrix4_dotnet.cs @@ -53,7 +53,7 @@ namespace SceneKit { /// [Serializable] public struct SCNMatrix4 : IEquatable { -#region Fields + #region Fields /* * SCNMatrix4 is defined like this for iOS, tvOS and watchOS: @@ -104,9 +104,9 @@ public struct SCNMatrix4 : IEquatable { /// public readonly static SCNMatrix4 Identity = new SCNMatrix4 (SCNVector4.UnitX, SCNVector4.UnitY, SCNVector4.UnitZ, SCNVector4.UnitW); -#endregion + #endregion -#region Constructors + #region Constructors /// /// Constructs a new instance. @@ -162,11 +162,11 @@ public SCNMatrix4 (CoreAnimation.CATransform3D transform) Column3 = new SCNVector4 ((pfloat) transform.M41, (pfloat) transform.M42, (pfloat) transform.M43, (pfloat) transform.M44); } -#endregion + #endregion -#region Public Members + #region Public Members -#region Properties + #region Properties /// /// The determinant of this matrix @@ -315,11 +315,11 @@ public SCNVector4 Row3 { /// public pfloat M44 { get { return Column3.W; } set { Column3.W = value; } } -#endregion + #endregion -#region Instance + #region Instance -#region public void Invert() + #region public void Invert() /// /// Converts this instance into its inverse. @@ -329,9 +329,9 @@ public void Invert () this = SCNMatrix4.Invert (this); } -#endregion + #endregion -#region public void Transpose() + #region public void Transpose() /// /// Converts this instance into its transpose. @@ -341,13 +341,13 @@ public void Transpose () this = SCNMatrix4.Transpose (this); } -#endregion + #endregion -#endregion + #endregion -#region Static + #region Static -#region CreateFromColumns + #region CreateFromColumns public static SCNMatrix4 CreateFromColumns (SCNVector4 column0, SCNVector4 column1, SCNVector4 column2, SCNVector4 column3) { @@ -368,9 +368,9 @@ public static void CreateFromColumns (SCNVector4 column0, SCNVector4 column1, SC result.Column3 = column3; } -#endregion + #endregion -#region CreateFromAxisAngle + #region CreateFromAxisAngle /// /// Build a rotation matrix from the specified axis/angle rotation. @@ -424,9 +424,9 @@ static void CreateFromAxisAngle (float x, float y, float z, float angle, out SCN var m33 = t * z * z + cos; result = new SCNMatrix4 ( - m11, m21, m31, 0.0f, - m12, m22, m32, 0.0f, - m13, m23, m33, 0.0f, + m11, m21, m31, 0.0f, + m12, m22, m32, 0.0f, + m13, m23, m33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } @@ -455,9 +455,9 @@ static void CreateFromAxisAngle (double x, double y, double z, double angle, out var m33 = (pfloat) (t * z * z + cos); result = new SCNMatrix4 ( - m11, m21, m31, 0.0f, - m12, m22, m32, 0.0f, - m13, m23, m33, 0.0f, + m11, m21, m31, 0.0f, + m12, m22, m32, 0.0f, + m13, m23, m33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } @@ -474,9 +474,9 @@ public static SCNMatrix4 CreateFromAxisAngle (SCNVector3 axis, pfloat angle) return result; } -#endregion + #endregion -#region CreateRotation[XYZ] + #region CreateRotation[XYZ] /// /// Builds a rotation matrix for a rotation around the x-axis. @@ -489,10 +489,10 @@ public static void CreateRotationX (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - 1, 0, 0, 0, - 0, cos, -sin, 0, - 0, sin, cos, 0, - 0, 0, 0, 1); + 1, 0, 0, 0, + 0, cos, -sin, 0, + 0, sin, cos, 0, + 0, 0, 0, 1); } /// @@ -518,10 +518,10 @@ public static void CreateRotationY (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - cos, 0, sin, 0, - 0, 1, 0, 0, - -sin, 0, cos, 0, - 0, 0, 0, 1); + cos, 0, sin, 0, + 0, 1, 0, 0, + -sin, 0, cos, 0, + 0, 0, 0, 1); } /// @@ -547,10 +547,10 @@ public static void CreateRotationZ (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - cos, -sin, 0, 0, - sin, cos, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); + cos, -sin, 0, 0, + sin, cos, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); } /// @@ -565,9 +565,9 @@ public static SCNMatrix4 CreateRotationZ (pfloat angle) return result; } -#endregion + #endregion -#region CreateTranslation + #region CreateTranslation /// /// Creates a translation matrix. @@ -621,9 +621,9 @@ public static SCNMatrix4 CreateTranslation (SCNVector3 vector) return result; } -#endregion + #endregion -#region CreateOrthographic + #region CreateOrthographic /// /// Creates an orthographic projection matrix. @@ -653,9 +653,9 @@ public static SCNMatrix4 CreateOrthographic (pfloat width, pfloat height, pfloat return result; } -#endregion + #endregion -#region CreateOrthographicOffCenter + #region CreateOrthographicOffCenter /// /// Creates an orthographic projection matrix. @@ -702,9 +702,9 @@ public static SCNMatrix4 CreateOrthographicOffCenter (pfloat left, pfloat right, return result; } -#endregion + #endregion -#region CreatePerspectiveFieldOfView + #region CreatePerspectiveFieldOfView /// /// Creates a perspective projection matrix. @@ -770,9 +770,9 @@ public static SCNMatrix4 CreatePerspectiveFieldOfView (pfloat fovy, pfloat aspec return result; } -#endregion + #endregion -#region CreatePerspectiveOffCenter + #region CreatePerspectiveOffCenter /// /// Creates a perspective projection matrix. @@ -809,10 +809,10 @@ public static void CreatePerspectiveOffCenter (pfloat left, pfloat right, pfloat pfloat d = -(2.0f * zFar * zNear) / (zFar - zNear); result = new SCNMatrix4 ( - x, 0, a, 0, - 0, y, b, 0, - 0, 0, c, d, - 0, 0, -1, 0); + x, 0, a, 0, + 0, y, b, 0, + 0, 0, c, d, + 0, 0, -1, 0); } /// @@ -840,9 +840,9 @@ public static SCNMatrix4 CreatePerspectiveOffCenter (pfloat left, pfloat right, return result; } -#endregion + #endregion -#region Scale Functions + #region Scale Functions /// /// Build a scaling matrix @@ -880,9 +880,9 @@ public static SCNMatrix4 Scale (pfloat x, pfloat y, pfloat z) 0, 0, 0, 1); } -#endregion + #endregion -#region Rotation Functions + #region Rotation Functions /// /// Build a rotation matrix from a quaternion @@ -913,9 +913,9 @@ public static SCNMatrix4 Rotate (Quaterniond q) CreateFromAxisAngle (axis, angle, out result); return result; } -#endregion + #endregion -#region Camera Helper Functions + #region Camera Helper Functions /// /// Build a world space to camera space matrix @@ -931,9 +931,9 @@ public static SCNMatrix4 LookAt (SCNVector3 eye, SCNVector3 target, SCNVector3 u SCNVector3 y = SCNVector3.Normalize (SCNVector3.Cross (z, x)); SCNMatrix4 rot = new SCNMatrix4 ( - x.X, x.Y, x.Z, 0.0f, - y.X, y.Y, y.Z, 0.0f, - z.X, z.Y, z.Z, 0.0f, + x.X, x.Y, x.Z, 0.0f, + y.X, y.Y, y.Z, 0.0f, + z.X, z.Y, z.Z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); SCNMatrix4 trans = SCNMatrix4.CreateTranslation (-eye); @@ -959,9 +959,9 @@ public static SCNMatrix4 LookAt (pfloat eyeX, pfloat eyeY, pfloat eyeZ, pfloat t return LookAt (new SCNVector3 (eyeX, eyeY, eyeZ), new SCNVector3 (targetX, targetY, targetZ), new SCNVector3 (upX, upY, upZ)); } -#endregion + #endregion -#region Multiply Functions + #region Multiply Functions #if XAMCORE_5_0 /// @@ -987,7 +987,7 @@ public static SCNMatrix4 LookAt (pfloat eyeX, pfloat eyeY, pfloat eyeZ, pfloat t #if XAMCORE_5_0 public static SCNMatrix4 Mult (SCNMatrix4 firstTransformation, SCNMatrix4 secondTransformation) #else - public static SCNMatrix4 Mult(SCNMatrix4 left, SCNMatrix4 right) + public static SCNMatrix4 Mult (SCNMatrix4 left, SCNMatrix4 right) #endif { SCNMatrix4 result; @@ -1024,7 +1024,7 @@ public static SCNMatrix4 Mult(SCNMatrix4 left, SCNMatrix4 right) #if XAMCORE_5_0 public static void Mult (ref SCNMatrix4 firstTransformation, ref SCNMatrix4 secondTransformation, out SCNMatrix4 result) #else - public static void Mult(ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) + public static void Mult (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) #endif { // the matrices are reversed: https://github.com/xamarin/xamarin-macios/issues/15094#issuecomment-1139699662 @@ -1038,7 +1038,7 @@ public static void Mult(ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix // Multiply two matrices in the order you'd expect (left * right). static void MatrixMultiply (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) { - result = new SCNMatrix4( + result = new SCNMatrix4 ( left.Column0.X * right.Column0.X + left.Column1.X * right.Column0.Y + left.Column2.X * right.Column0.Z + left.Column3.X * right.Column0.W, left.Column0.X * right.Column1.X + left.Column1.X * right.Column1.Y + left.Column2.X * right.Column1.Z + left.Column3.X * right.Column1.W, left.Column0.X * right.Column2.X + left.Column1.X * right.Column2.Y + left.Column2.X * right.Column2.Z + left.Column3.X * right.Column2.W, @@ -1060,9 +1060,9 @@ static void MatrixMultiply (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMa left.Column0.W * right.Column3.X + left.Column1.W * right.Column3.Y + left.Column2.W * right.Column3.Z + left.Column3.W * right.Column3.W); } -#endregion + #endregion -#region Invert Functions + #region Invert Functions static bool InvertSoftware (SCNMatrix4 matrix, out SCNMatrix4 result) { @@ -1094,9 +1094,9 @@ static bool InvertSoftware (SCNMatrix4 matrix, out SCNMatrix4 result) #endif { result = new SCNMatrix4 (pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN); + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN); return false; } @@ -1154,9 +1154,9 @@ public static SCNMatrix4 Invert (SCNMatrix4 matrix) return inverse; } -#endregion + #endregion -#region Transpose + #region Transpose /// /// Calculate the transpose of the given matrix @@ -1179,11 +1179,11 @@ public static void Transpose (ref SCNMatrix4 mat, out SCNMatrix4 result) result = new SCNMatrix4 (mat.Column0, mat.Column1, mat.Column2, mat.Column3); } -#endregion + #endregion -#endregion + #endregion -#region Operators + #region Operators /// /// Matrix multiplication @@ -1218,11 +1218,11 @@ public static void Transpose (ref SCNMatrix4 mat, out SCNMatrix4 result) return !left.Equals (right); } -#endregion + #endregion -#region Overrides + #region Overrides -#region public override string ToString() + #region public override string ToString() /// /// Returns a System.String that represents the current SCNMatrix4. @@ -1233,9 +1233,9 @@ public override string ToString () return String.Format ("{0}\n{1}\n{2}\n{3}", Row0, Row1, Row2, Row3); } -#endregion + #endregion -#region public override int GetHashCode() + #region public override int GetHashCode() /// /// Returns the hashcode for this instance. @@ -1243,12 +1243,12 @@ public override string ToString () /// A System.Int32 containing the unique hashcode for this instance. public override int GetHashCode () { - return HashCode.Combine(Column0, Column1, Column2, Column3); + return HashCode.Combine (Column0, Column1, Column2, Column3); } -#endregion + #endregion -#region public override bool Equals(object obj) + #region public override bool Equals(object obj) /// /// Indicates whether this instance and a specified object are equal. @@ -1263,13 +1263,13 @@ public override bool Equals (object? obj) return this.Equals ((SCNMatrix4) obj); } -#endregion + #endregion -#endregion + #endregion -#endregion + #endregion -#region IEquatable Members + #region IEquatable Members /// Indicates whether the current matrix is equal to another matrix. /// An matrix to compare with this matrix. @@ -1283,17 +1283,17 @@ public bool Equals (SCNMatrix4 other) Column3 == other.Column3; } -#endregion + #endregion static void ToAxisAngle (Quaternion q, out Vector3 axis, out float angle) { if (q.W > 1.0f) - q = Quaternion.Normalize (q); + q = Quaternion.Normalize (q); angle = 2.0f * (float) System.Math.Acos (q.W); // angle var den = (float) System.Math.Sqrt (1.0 - q.W * q.W); if (den > 0.0001f) { - axis = new Vector3(q.X, q.Y, q.Z) / den; + axis = new Vector3 (q.X, q.Y, q.Z) / den; } else { // This occurs when the angle is zero. // Not a problem: just set an arbitrary normalized axis. diff --git a/src/SceneKit/SCNQuaternion.cs b/src/SceneKit/SCNQuaternion.cs index 24c45a7529e1..a71754c5f07c 100644 --- a/src/SceneKit/SCNQuaternion.cs +++ b/src/SceneKit/SCNQuaternion.cs @@ -60,10 +60,10 @@ namespace SceneKit { /// Represents a Quaternion. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -102,7 +102,7 @@ public SCNQuaternion (pfloat x, pfloat y, pfloat z, pfloat w) public SCNQuaternion (ref Matrix3 matrix) { #if NET - double scale = System.Math.Pow (matrix.GetDeterminant (), 1.0d / 3.0d); + double scale = System.Math.Pow (matrix.GetDeterminant (), 1.0d / 3.0d); #else double scale = System.Math.Pow (matrix.Determinant, 1.0d / 3.0d); #endif @@ -121,10 +121,10 @@ public SCNQuaternion (ref Matrix3 matrix) } #if NET - public SCNQuaternion (Quaternion quaternion) - : this (quaternion.X, quaternion.Y, quaternion.Z, quaternion.W) - { - } + public SCNQuaternion (Quaternion quaternion) + : this (quaternion.X, quaternion.Y, quaternion.Z, quaternion.W) + { + } #else public SCNQuaternion (Quaternion openTkQuaternion) : this (new SCNVector3 (openTkQuaternion.XYZ), openTkQuaternion.W) { diff --git a/src/SceneKit/SCNVector3.cs b/src/SceneKit/SCNVector3.cs index 19c4abf1c243..5242ae663659 100644 --- a/src/SceneKit/SCNVector3.cs +++ b/src/SceneKit/SCNVector3.cs @@ -61,10 +61,10 @@ namespace SceneKit { /// The Vector3 structure is suitable for interoperation with unmanaged code requiring three consecutive floats. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -771,17 +771,17 @@ public static SCNVector3 TransformVector (SCNVector3 vec, SCNMatrix4 mat) public static void TransformVector (ref SCNVector3 vec, ref SCNMatrix4 mat, out SCNVector3 result) { #if NET - result.X = vec.X * mat.Row0.X + - vec.Y * mat.Row0.Y + - vec.Z * mat.Row0.Z; + result.X = vec.X * mat.Row0.X + + vec.Y * mat.Row0.Y + + vec.Z * mat.Row0.Z; - result.Y = vec.X * mat.Row1.X + - vec.Y * mat.Row1.Y + - vec.Z * mat.Row1.Z; + result.Y = vec.X * mat.Row1.X + + vec.Y * mat.Row1.Y + + vec.Z * mat.Row1.Z; - result.Z = vec.X * mat.Row2.X + - vec.Y * mat.Row2.Y + - vec.Z * mat.Row2.Z; + result.Z = vec.X * mat.Row2.X + + vec.Y * mat.Row2.Y + + vec.Z * mat.Row2.Z; #else result.X = vec.X * mat.Row0.X + vec.Y * mat.Row1.X + @@ -803,7 +803,7 @@ public static void TransformVector (ref SCNVector3 vec, ref SCNMatrix4 mat, out /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// - /// The column-based normal to transform + /// The column-based normal to transform /// The desired transformation /// The transformed normal #else @@ -828,7 +828,7 @@ public static SCNVector3 TransformNormal (SCNVector3 norm, SCNMatrix4 mat) /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// - /// The column-based normal to transform + /// The column-based normal to transform /// The desired transformation /// The transformed normal #else @@ -853,7 +853,7 @@ public static void TransformNormal (ref SCNVector3 norm, ref SCNMatrix4 mat, out /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// - /// The column-based normal to transform + /// The column-based normal to transform /// The inverse of the desired transformation /// The transformed normal #else @@ -878,7 +878,7 @@ public static SCNVector3 TransformNormalInverse (SCNVector3 norm, SCNMatrix4 inv /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// - /// The column-based normal to transform + /// The column-based normal to transform /// The inverse of the desired transformation /// The transformed normal #else @@ -894,17 +894,17 @@ public static SCNVector3 TransformNormalInverse (SCNVector3 norm, SCNMatrix4 inv public static void TransformNormalInverse (ref SCNVector3 norm, ref SCNMatrix4 invMat, out SCNVector3 result) { #if NET - result.X = norm.X * invMat.Column0.X + - norm.Y * invMat.Column0.Y + - norm.Z * invMat.Column0.Z; + result.X = norm.X * invMat.Column0.X + + norm.Y * invMat.Column0.Y + + norm.Z * invMat.Column0.Z; - result.Y = norm.X * invMat.Column1.X + - norm.Y * invMat.Column1.Y + - norm.Z * invMat.Column1.Z; + result.Y = norm.X * invMat.Column1.X + + norm.Y * invMat.Column1.Y + + norm.Z * invMat.Column1.Z; - result.Z = norm.X * invMat.Column2.X + - norm.Y * invMat.Column2.Y + - norm.Z * invMat.Column2.Z; + result.Z = norm.X * invMat.Column2.X + + norm.Y * invMat.Column2.Y + + norm.Z * invMat.Column2.Z; #else result.X = norm.X * invMat.Row0.X + norm.Y * invMat.Row0.Y + @@ -922,7 +922,7 @@ public static void TransformNormalInverse (ref SCNVector3 norm, ref SCNMatrix4 i #if NET /// Transform a Position by the given Matrix - /// The column-based position to transform + /// The column-based position to transform /// The desired transformation /// The transformed position #else @@ -939,7 +939,7 @@ public static SCNVector3 TransformPosition (SCNVector3 pos, SCNMatrix4 mat) #if NET /// Transform a Position by the given Matrix - /// The column-based position to transform + /// The column-based position to transform /// The desired transformation /// The transformed position #else @@ -951,20 +951,20 @@ public static SCNVector3 TransformPosition (SCNVector3 pos, SCNMatrix4 mat) public static void TransformPosition (ref SCNVector3 pos, ref SCNMatrix4 mat, out SCNVector3 result) { #if NET - result.X = mat.Row0.X * pos.X + - mat.Row0.Y * pos.Y + - mat.Row0.Z * pos.Z + - mat.Row0.W; - - result.Y = mat.Row1.X * pos.X + - mat.Row1.Y * pos.Y + - mat.Row1.Z * pos.Z + - mat.Row1.W; - - result.Z = mat.Row2.X * pos.X + - mat.Row2.Y * pos.Y + - mat.Row2.Z * pos.Z + - mat.Row2.W; + result.X = mat.Row0.X * pos.X + + mat.Row0.Y * pos.Y + + mat.Row0.Z * pos.Z + + mat.Row0.W; + + result.Y = mat.Row1.X * pos.X + + mat.Row1.Y * pos.Y + + mat.Row1.Z * pos.Z + + mat.Row1.W; + + result.Z = mat.Row2.X * pos.X + + mat.Row2.Y * pos.Y + + mat.Row2.Z * pos.Z + + mat.Row2.W; #else result.X = pos.X * mat.Row0.X + pos.Y * mat.Row1.X + @@ -985,7 +985,7 @@ public static void TransformPosition (ref SCNVector3 pos, ref SCNMatrix4 mat, ou #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -1002,7 +1002,7 @@ public static SCNVector4 Transform (SCNVector3 vec, SCNMatrix4 mat) #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else diff --git a/src/SceneKit/SCNVector4.cs b/src/SceneKit/SCNVector4.cs index e28a85ffbe38..5e95a1576bd9 100644 --- a/src/SceneKit/SCNVector4.cs +++ b/src/SceneKit/SCNVector4.cs @@ -60,10 +60,10 @@ namespace SceneKit { /// The Vector4 structure is suitable for interoperation with unmanaged code requiring four consecutive floats. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -836,7 +836,7 @@ public static void BaryCentric (ref SCNVector4 a, ref SCNVector4 b, ref SCNVecto #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -853,7 +853,7 @@ public static SCNVector4 Transform (SCNVector4 vec, SCNMatrix4 mat) #if NET /// Transform a Vector by the given Matrix. - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -865,25 +865,25 @@ public static SCNVector4 Transform (SCNVector4 vec, SCNMatrix4 mat) public static void Transform (ref SCNVector4 vec, ref SCNMatrix4 mat, out SCNVector4 result) { #if NET - result.X = vec.X * mat.Column0.X + - vec.Y * mat.Column1.X + - vec.Z * mat.Column2.X + - vec.W * mat.Column3.X; - - result.Y = vec.X * mat.Column0.Y + - vec.Y * mat.Column1.Y + - vec.Z * mat.Column2.Y + - vec.W * mat.Column3.Y; - - result.Z = vec.X * mat.Column0.Z + - vec.Y * mat.Column1.Z + - vec.Z * mat.Column2.Z + - vec.W * mat.Column3.Z; - - result.W = vec.X * mat.Column0.W + - vec.Y * mat.Column1.W + - vec.Z * mat.Column2.W + - vec.W * mat.Column3.W; + result.X = vec.X * mat.Column0.X + + vec.Y * mat.Column1.X + + vec.Z * mat.Column2.X + + vec.W * mat.Column3.X; + + result.Y = vec.X * mat.Column0.Y + + vec.Y * mat.Column1.Y + + vec.Z * mat.Column2.Y + + vec.W * mat.Column3.Y; + + result.Z = vec.X * mat.Column0.Z + + vec.Y * mat.Column1.Z + + vec.Z * mat.Column2.Z + + vec.W * mat.Column3.Z; + + result.W = vec.X * mat.Column0.W + + vec.Y * mat.Column1.W + + vec.Z * mat.Column2.W + + vec.W * mat.Column3.W; #else result.X = vec.X * mat.Row0.X + vec.Y * mat.Row1.X + diff --git a/src/Security/Authorization.cs b/src/Security/Authorization.cs index 3b62567fedb2..da53d2a4d823 100644 --- a/src/Security/Authorization.cs +++ b/src/Security/Authorization.cs @@ -48,21 +48,21 @@ namespace Security { #endif // Untyped enum in ObjC public enum AuthorizationStatus { - Success = 0, - InvalidSet = -60001, - InvalidRef = -60002, - InvalidTag = -60003, - InvalidPointer = -60004, - Denied = -60005, - Canceled = -60006, - InteractionNotAllowed = -60007, - Internal = -60008, - ExternalizeNotAllowed = -60009, - InternalizeNotAllowed = -60010, - InvalidFlags = -60011, - ToolExecuteFailure = -60031, - ToolEnvironmentError = -60032, - BadAddress = -60033, + Success = 0, + InvalidSet = -60001, + InvalidRef = -60002, + InvalidTag = -60003, + InvalidPointer = -60004, + Denied = -60005, + Canceled = -60006, + InteractionNotAllowed = -60007, + Internal = -60008, + ExternalizeNotAllowed = -60009, + InternalizeNotAllowed = -60010, + InvalidFlags = -60011, + ToolExecuteFailure = -60031, + ToolEnvironmentError = -60032, + BadAddress = -60033, } #if NET @@ -115,7 +115,7 @@ public class AuthorizationParameters { public class AuthorizationEnvironment { public string? Username; public string? Password; - public bool AddToSharedCredentialPool; + public bool AddToSharedCredentialPool; } #if NET @@ -140,7 +140,7 @@ struct AuthorizationItem { #endif unsafe struct AuthorizationItemSet { public int /* UInt32 */ count; - public AuthorizationItem * /* AuthorizationItem* */ ptrToAuthorization; + public AuthorizationItem* /* AuthorizationItem* */ ptrToAuthorization; } #if NET @@ -151,7 +151,7 @@ unsafe struct AuthorizationItemSet { #endif public unsafe class Authorization : DisposableObject { [DllImport (Constants.SecurityLibrary)] - unsafe extern static int /* OSStatus = int */ AuthorizationCreate (AuthorizationItemSet *rights, AuthorizationItemSet *environment, AuthorizationFlags flags, IntPtr* auth); + unsafe extern static int /* OSStatus = int */ AuthorizationCreate (AuthorizationItemSet* rights, AuthorizationItemSet* environment, AuthorizationFlags flags, IntPtr* auth); #if NET [SupportedOSPlatform ("maccatalyst")] @@ -170,7 +170,7 @@ public unsafe class Authorization : DisposableObject { [DllImport (Constants.SecurityLibrary)] extern static int /* OSStatus = int */ AuthorizationFree (IntPtr handle, AuthorizationFlags flags); - + [Preserve (Conditional = true)] internal Authorization (NativeHandle handle, bool owns) : base (handle, owns) @@ -186,7 +186,7 @@ internal Authorization (NativeHandle handle, bool owns) #endif public int ExecuteWithPrivileges (string pathToTool, AuthorizationFlags flags, string []? args) { - string?[]? arguments = args!; + string? []? arguments = args!; if (arguments is not null) { // The arguments array must be null-terminated, so make sure that's the case @@ -213,19 +213,19 @@ protected override void Dispose (bool disposing) { Dispose (0, disposing); } - + public virtual void Dispose (AuthorizationFlags flags, bool disposing) { if (Handle != IntPtr.Zero && Owns) AuthorizationFree (Handle, flags); base.Dispose (disposing); } - + public static Authorization? Create (AuthorizationFlags flags) { return Create (null, null, flags); } - + static void EncodeString (ref AuthorizationItem item, string key, string? value) { item.name = Marshal.StringToHGlobalAuto (key); @@ -234,32 +234,32 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) item.valueLen = value.Length; } } - + public static Authorization? Create (AuthorizationParameters? parameters, AuthorizationEnvironment? environment, AuthorizationFlags flags) { AuthorizationItemSet pars = new AuthorizationItemSet (); - AuthorizationItemSet *ppars = null; - AuthorizationItem *pitems = null; + AuthorizationItemSet* ppars = null; + AuthorizationItem* pitems = null; AuthorizationItemSet env = new AuthorizationItemSet (); - AuthorizationItemSet *penv = null; - AuthorizationItem *eitems = null; + AuthorizationItemSet* penv = null; + AuthorizationItem* eitems = null; int code; IntPtr auth; try { unsafe { - if (parameters is not null){ + if (parameters is not null) { ppars = &pars; - pars.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 2); + pars.ptrToAuthorization = (AuthorizationItem*) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 2); if (parameters.PathToSystemPrivilegeTool is not null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "system.privilege.admin", parameters.PathToSystemPrivilegeTool); if (parameters.IconPath is not null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "icon", parameters.IconPath); } - if (environment is not null || (parameters is not null && parameters.Prompt is not null)){ + if (environment is not null || (parameters is not null && parameters.Prompt is not null)) { penv = &env; - env.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 4); - if (environment is not null){ + env.ptrToAuthorization = (AuthorizationItem*) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 4); + if (environment is not null) { if (environment.Username is not null) EncodeString (ref env.ptrToAuthorization [env.count++], "username", environment.Username); if (environment.Password is not null) @@ -267,7 +267,7 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) if (environment.AddToSharedCredentialPool) EncodeString (ref env.ptrToAuthorization [env.count++], "shared", null); } - if (parameters is not null){ + if (parameters is not null) { if (parameters.Prompt is not null) EncodeString (ref env.ptrToAuthorization [env.count++], "prompt", parameters.Prompt); } @@ -278,20 +278,20 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) return new Authorization (auth, true); } } finally { - if (ppars is not null){ - for (int i = 0; i < pars.count; i++){ + if (ppars is not null) { + for (int i = 0; i < pars.count; i++) { Marshal.FreeHGlobal (pars.ptrToAuthorization [i].name); Marshal.FreeHGlobal (pars.ptrToAuthorization [i].value); } - Marshal.FreeHGlobal ((IntPtr)pars.ptrToAuthorization); + Marshal.FreeHGlobal ((IntPtr) pars.ptrToAuthorization); } - if (penv is not null){ - for (int i = 0; i < env.count; i++){ + if (penv is not null) { + for (int i = 0; i < env.count; i++) { Marshal.FreeHGlobal (env.ptrToAuthorization [i].name); if (env.ptrToAuthorization [i].value != IntPtr.Zero) Marshal.FreeHGlobal (env.ptrToAuthorization [i].value); } - Marshal.FreeHGlobal ((IntPtr)env.ptrToAuthorization); + Marshal.FreeHGlobal ((IntPtr) env.ptrToAuthorization); } } } diff --git a/src/Security/Enums.cs b/src/Security/Enums.cs index e8266599bef3..5db43f766fcd 100644 --- a/src/Security/Enums.cs +++ b/src/Security/Enums.cs @@ -316,7 +316,7 @@ public enum SecStatusCode { InvalidCRLAuthority = -67827, /* The CRL authority was not valid. */ #if MONOMAC [Obsolete ("Use InvalidCRLAuthority.")] - InvaldCRLAuthority = InvalidCRLAuthority, + InvaldCRLAuthority = InvalidCRLAuthority, #endif InvalidCRLEncoding = -67828, /* The CRL encoding was not valid. */ InvalidCRLType = -67829, /* The CRL type was not valid. */ @@ -345,7 +345,7 @@ public enum SecStatusCode { InvalidTupleCredentials = -67852, /* The tuple credentials are not valid. */ #if MONOMAC [Obsolete ("Use InvalidTupleCredentials.")] - InvalidTupleCredendtials = InvalidTupleCredentials, + InvalidTupleCredendtials = InvalidTupleCredentials, #endif InvalidEncoding = -67853, /* The encoding was not valid. */ InvalidValidityPeriod = -67854, /* The validity period was not valid. */ diff --git a/src/Security/Items.cs b/src/Security/Items.cs index 6f49c0e74dfb..5c7fb45b6de7 100644 --- a/src/Security/Items.cs +++ b/src/Security/Items.cs @@ -338,11 +338,11 @@ public static SecStatusCode Update (SecRecord query, SecRecord newAttributes) extern static SecStatusCode SecKeychainAddGenericPassword ( IntPtr keychain, int serviceNameLength, - byte[]? serviceName, + byte []? serviceName, int accountNameLength, - byte[]? accountName, + byte []? accountName, int passwordLength, - byte[] passwordData, + byte [] passwordData, IntPtr itemRef); #if NET @@ -370,18 +370,18 @@ unsafe extern static SecStatusCode SecKeychainFindGenericPassword ( extern static SecStatusCode SecKeychainAddInternetPassword ( IntPtr keychain, int serverNameLength, - byte[]? serverName, + byte []? serverName, int securityDomainLength, - byte[]? securityDomain, + byte []? securityDomain, int accountNameLength, - byte[]? accountName, + byte []? accountName, int pathLength, - byte[]? path, + byte []? path, short port, IntPtr protocol, IntPtr authenticationType, int passwordLength, - byte[] passwordData, + byte [] passwordData, IntPtr itemRef); #if NET @@ -418,30 +418,30 @@ unsafe extern static SecStatusCode SecKeychainFindInternetPassword ( public static SecStatusCode AddInternetPassword ( string serverName, string accountName, - byte[] password, + byte [] password, SecProtocol protocolType = SecProtocol.Http, short port = 0, string? path = null, SecAuthenticationType authenticationType = SecAuthenticationType.Default, string? securityDomain = null) { - byte[]? serverNameBytes = null; - byte[]? securityDomainBytes = null; - byte[]? accountNameBytes = null; - byte[]? pathBytes = null; - + byte []? serverNameBytes = null; + byte []? securityDomainBytes = null; + byte []? accountNameBytes = null; + byte []? pathBytes = null; + if (!String.IsNullOrEmpty (serverName)) serverNameBytes = System.Text.Encoding.UTF8.GetBytes (serverName); - + if (!String.IsNullOrEmpty (securityDomain)) securityDomainBytes = System.Text.Encoding.UTF8.GetBytes (securityDomain); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - + if (!String.IsNullOrEmpty (path)) pathBytes = System.Text.Encoding.UTF8.GetBytes (path); - + return SecKeychainAddInternetPassword ( IntPtr.Zero, serverNameBytes?.Length ?? 0, @@ -459,12 +459,12 @@ public static SecStatusCode AddInternetPassword ( password!, IntPtr.Zero); } - - - public static SecStatusCode FindInternetPassword( + + + public static SecStatusCode FindInternetPassword ( string serverName, string accountName, - out byte[]? password, + out byte []? password, SecProtocol protocolType = SecProtocol.Http, short port = 0, string? path = null, @@ -472,36 +472,36 @@ public static SecStatusCode FindInternetPassword( string? securityDomain = null) { password = null; - - byte[]? serverBytes = null; - byte[]? securityDomainBytes = null; - byte[]? accountNameBytes = null; - byte[]? pathBytes = null; + + byte []? serverBytes = null; + byte []? securityDomainBytes = null; + byte []? accountNameBytes = null; + byte []? pathBytes = null; IntPtr passwordPtr = IntPtr.Zero; - + try { if (!String.IsNullOrEmpty (serverName)) serverBytes = System.Text.Encoding.UTF8.GetBytes (serverName); - + if (!String.IsNullOrEmpty (securityDomain)) securityDomainBytes = System.Text.Encoding.UTF8.GetBytes (securityDomain); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - - if (!String.IsNullOrEmpty(path)) + + if (!String.IsNullOrEmpty (path)) pathBytes = System.Text.Encoding.UTF8.GetBytes (path); - + int passwordLength = 0; - + SecStatusCode code; unsafe { fixed (byte* serverBytesPtr = serverBytes) { fixed (byte* securityDomainBytesPtr = securityDomainBytes) { fixed (byte* accountNameBytesPtr = accountNameBytes) { fixed (byte* pathBytesPtr = pathBytes) { - code = SecKeychainFindInternetPassword( + code = SecKeychainFindInternetPassword ( IntPtr.Zero, serverBytes?.Length ?? 0, serverBytesPtr, @@ -512,8 +512,8 @@ public static SecStatusCode FindInternetPassword( pathBytes?.Length ?? 0, pathBytesPtr, port, - SecProtocolKeys.FromSecProtocol(protocolType), - KeysAuthenticationType.FromSecAuthenticationType(authenticationType), + SecProtocolKeys.FromSecProtocol (protocolType), + KeysAuthenticationType.FromSecAuthenticationType (authenticationType), &passwordLength, &passwordPtr, IntPtr.Zero); @@ -522,32 +522,32 @@ public static SecStatusCode FindInternetPassword( } } } - + if (code == SecStatusCode.Success && passwordLength > 0) { - password = new byte[passwordLength]; - Marshal.Copy(passwordPtr, password, 0, passwordLength); + password = new byte [passwordLength]; + Marshal.Copy (passwordPtr, password, 0, passwordLength); } - + return code; - + } finally { if (passwordPtr != IntPtr.Zero) - SecKeychainItemFreeContent(IntPtr.Zero, passwordPtr); + SecKeychainItemFreeContent (IntPtr.Zero, passwordPtr); } } - public static SecStatusCode AddGenericPassword (string serviceName, string accountName, byte[] password) + public static SecStatusCode AddGenericPassword (string serviceName, string accountName, byte [] password) { - byte[]? serviceNameBytes = null; - byte[]? accountNameBytes = null; - + byte []? serviceNameBytes = null; + byte []? accountNameBytes = null; + if (!String.IsNullOrEmpty (serviceName)) serviceNameBytes = System.Text.Encoding.UTF8.GetBytes (serviceName); if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - return SecKeychainAddGenericPassword( + return SecKeychainAddGenericPassword ( IntPtr.Zero, serviceNameBytes?.Length ?? 0, serviceNameBytes, @@ -559,30 +559,30 @@ public static SecStatusCode AddGenericPassword (string serviceName, string accou ); } - public static SecStatusCode FindGenericPassword (string serviceName, string accountName, out byte[]? password) + public static SecStatusCode FindGenericPassword (string serviceName, string accountName, out byte []? password) { password = null; - byte[]? serviceNameBytes = null; - byte[]? accountNameBytes = null; - + byte []? serviceNameBytes = null; + byte []? accountNameBytes = null; + IntPtr passwordPtr = IntPtr.Zero; - + try { - + if (!String.IsNullOrEmpty (serviceName)) serviceNameBytes = System.Text.Encoding.UTF8.GetBytes (serviceName); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - + int passwordLength = 0; - + SecStatusCode code; unsafe { fixed (byte* serviceNameBytesPtr = serviceNameBytes) { fixed (byte* accountNameBytesPtr = accountNameBytes) { - code = SecKeychainFindGenericPassword( + code = SecKeychainFindGenericPassword ( IntPtr.Zero, serviceNameBytes?.Length ?? 0, serviceNameBytesPtr, @@ -595,17 +595,17 @@ public static SecStatusCode FindGenericPassword (string serviceName, string acco } } } - - if (code == SecStatusCode.Success && passwordLength > 0){ - password = new byte[passwordLength]; - Marshal.Copy(passwordPtr, password, 0, passwordLength); + + if (code == SecStatusCode.Success && passwordLength > 0) { + password = new byte [passwordLength]; + Marshal.Copy (passwordPtr, password, 0, passwordLength); } - + return code; - + } finally { if (passwordPtr != IntPtr.Zero) - SecKeychainItemFreeContent(IntPtr.Zero, passwordPtr); + SecKeychainItemFreeContent (IntPtr.Zero, passwordPtr); } } #else diff --git a/src/Security/SecCertificate2.cs b/src/Security/SecCertificate2.cs index 1ca0f1ba97e4..2f48736262d9 100644 --- a/src/Security/SecCertificate2.cs +++ b/src/Security/SecCertificate2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecCertificate2 : NativeObject { [Preserve (Conditional = true)] #if NET - internal SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) {} + internal SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) { } #else public SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Security/SecIdentity2.cs b/src/Security/SecIdentity2.cs index 6db4f0df505b..0bc7f441890c 100644 --- a/src/Security/SecIdentity2.cs +++ b/src/Security/SecIdentity2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecIdentity2 : NativeObject { #if NET [Preserve (Conditional = true)] - internal SecIdentity2 (NativeHandle handle, bool owns) : base (handle, owns) {} + internal SecIdentity2 (NativeHandle handle, bool owns) : base (handle, owns) { } #else internal SecIdentity2 (NativeHandle handle) : base (handle, false) { } [Preserve (Conditional = true)] diff --git a/src/Security/SecSharedCredential.cs b/src/Security/SecSharedCredential.cs index 3749b610945e..149ac4d5d322 100644 --- a/src/Security/SecSharedCredential.cs +++ b/src/Security/SecSharedCredential.cs @@ -17,12 +17,12 @@ public static partial class SecSharedCredential { [DllImport (Constants.SecurityLibrary)] unsafe extern static void SecAddSharedWebCredential (IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, IntPtr /* CFStringRef */ password, BlockLiteral* /* void (^completionHandler)( CFErrorRef error) ) */ completionHandler); - + #if !NET [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)] internal delegate void DActionArity1V12 (IntPtr block, IntPtr obj); #endif - + // This class bridges native block invocations that call into C# static internal class ActionTrampoline { #if !NET @@ -32,14 +32,15 @@ static internal class ActionTrampoline { #else [UnmanagedCallersOnly] #endif - internal static unsafe void Invoke (IntPtr block, IntPtr obj) { - var descriptor = (BlockLiteral *) block; + internal static unsafe void Invoke (IntPtr block, IntPtr obj) + { + var descriptor = (BlockLiteral*) block; var del = (global::System.Action) (descriptor->Target); if (del is not null) { - del ( Runtime.GetNSObject (obj)); + del (Runtime.GetNSObject (obj)); } - } - } + } + } [BindingImpl (BindingImplOptions.Optimizable)] public static void AddSharedWebCredential (string domainName, string account, string password, Action handler) @@ -78,7 +79,7 @@ public static void AddSharedWebCredential (string domainName, string account, st [Deprecated (PlatformName.MacOSX, 11,0)] #endif [DllImport (Constants.SecurityLibrary)] - unsafe extern static void SecRequestSharedWebCredential ( IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, + unsafe extern static void SecRequestSharedWebCredential (IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, BlockLiteral* /* void (^completionHandler)( CFArrayRef credentials, CFErrorRef error) */ completionHandler); #if !NET @@ -98,11 +99,12 @@ static internal class ArrayErrorActionTrampoline { #else [UnmanagedCallersOnly] #endif - internal static unsafe void Invoke (IntPtr block, IntPtr array, IntPtr err) { - var descriptor = (BlockLiteral *) block; + internal static unsafe void Invoke (IntPtr block, IntPtr array, IntPtr err) + { + var descriptor = (BlockLiteral*) block; var del = (global::System.Action) (descriptor->Target); if (del is not null) - del ( Runtime.GetNSObject (array), Runtime.GetNSObject (err)); + del (Runtime.GetNSObject (array), Runtime.GetNSObject (err)); } } @@ -126,7 +128,7 @@ public static void RequestSharedWebCredential (string domainName, string account [Deprecated (PlatformName.MacOSX, 11,0, message: "Use 'ASAuthorizationPasswordRequest' instead.")] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public static void RequestSharedWebCredential (string domainName, string account, Action handler) + public static void RequestSharedWebCredential (string domainName, string account, Action handler) { Action onComplete = (NSArray a, NSError e) => { var creds = new SecSharedCredentialInfo [a.Count]; diff --git a/src/Security/SecTrust2.cs b/src/Security/SecTrust2.cs index fec07746c4eb..50f338b88ab3 100644 --- a/src/Security/SecTrust2.cs +++ b/src/Security/SecTrust2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecTrust2 : NativeObject { [Preserve (Conditional = true)] #if NET - internal SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) {} + internal SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) { } #else public SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Simd/MathHelper.cs b/src/Simd/MathHelper.cs index 2f2e0a93470b..5739adfe867a 100644 --- a/src/Simd/MathHelper.cs +++ b/src/Simd/MathHelper.cs @@ -16,8 +16,7 @@ static class MathHelper { /// internal static float InverseSqrtFast (float x) { - unsafe - { + unsafe { float xhalf = 0.5f * x; int i = *(int*) &x; // Read bits as integer. i = 0x5f375a86 - (i >> 1); // Make an initial guess for Newton-Raphson approximation diff --git a/src/Simd/MatrixFloat3x3RM.cs b/src/Simd/MatrixFloat3x3RM.cs index a4cc13c99fe1..66aa43926348 100644 --- a/src/Simd/MatrixFloat3x3RM.cs +++ b/src/Simd/MatrixFloat3x3RM.cs @@ -25,12 +25,10 @@ // This type does not come from the CoreGraphics framework #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [NativeName ("GLKMatrix3")] [StructLayout (LayoutKind.Sequential)] - public struct RMatrix3 : IEquatable - { + public struct RMatrix3 : IEquatable { public float M11; public float M12; public float M13; @@ -123,7 +121,7 @@ public RMatrix3 ( break; } - throw new IndexOutOfRangeException(); + throw new IndexOutOfRangeException (); } set { switch (row) { @@ -150,7 +148,7 @@ public RMatrix3 ( break; } - throw new IndexOutOfRangeException(); + throw new IndexOutOfRangeException (); } } @@ -292,17 +290,17 @@ public override string ToString () public override int GetHashCode () { - var hash = new HashCode(); - hash.Add(M11); - hash.Add(M12); - hash.Add(M13); - hash.Add(M21); - hash.Add(M22); - hash.Add(M23); - hash.Add(M31); - hash.Add(M32); - hash.Add(M33); - return hash.ToHashCode(); + var hash = new HashCode (); + hash.Add (M11); + hash.Add (M12); + hash.Add (M13); + hash.Add (M21); + hash.Add (M22); + hash.Add (M23); + hash.Add (M31); + hash.Add (M32); + hash.Add (M33); + return hash.ToHashCode (); } public override bool Equals (object? obj) diff --git a/src/Simd/MatrixFloat4x3.cs b/src/Simd/MatrixFloat4x3.cs index cdb52fb94a5a..f06a7c0154ad 100644 --- a/src/Simd/MatrixFloat4x3.cs +++ b/src/Simd/MatrixFloat4x3.cs @@ -16,7 +16,7 @@ using System.Runtime.Versioning; #if NET -using VectorFloat4=global::System.Numerics.Vector4; +using VectorFloat4 = global::System.Numerics.Vector4; #else using VectorFloat4 = global::OpenTK.Vector4; #endif diff --git a/src/Simd/QuaternionDouble.cs b/src/Simd/QuaternionDouble.cs index d5725590a524..a64edbe59ba6 100644 --- a/src/Simd/QuaternionDouble.cs +++ b/src/Simd/QuaternionDouble.cs @@ -20,11 +20,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/quaternion.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NQuaterniond : IEquatable - { + public struct NQuaterniond : IEquatable { public double X; public double Y; public double Z; @@ -46,8 +44,7 @@ public NQuaterniond (NVector3d vectorPart, double scalarPart) W = scalarPart; } - internal NVector3d Xyz - { + internal NVector3d Xyz { get => new NVector3d (X, Y, Z); set { X = value.X; @@ -66,7 +63,7 @@ public override string ToString () => $"({X}, {Y}, {Z}, {W})"; public override int GetHashCode () => - HashCode.Combine(X, Y, Z, W); + HashCode.Combine (X, Y, Z, W); public override bool Equals (object? obj) { @@ -100,7 +97,7 @@ internal NVector4d ToAxisAngle () { NQuaterniond q = this; if (q.W > 1.0f) - q.Normalize(); + q.Normalize (); NVector4d result = new NVector4d (); diff --git a/src/Simd/VectorDouble2.cs b/src/Simd/VectorDouble2.cs index 8f2c57e77309..b33768c141ee 100644 --- a/src/Simd/VectorDouble2.cs +++ b/src/Simd/VectorDouble2.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector2d : IEquatable - { + public struct NVector2d : IEquatable { public double X; public double Y; @@ -47,7 +45,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y); + return HashCode.Combine (X, Y); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorDouble4.cs b/src/Simd/VectorDouble4.cs index 2a8459dd8c7a..5aa60c8c370a 100644 --- a/src/Simd/VectorDouble4.cs +++ b/src/Simd/VectorDouble4.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector4d : IEquatable - { + public struct NVector4d : IEquatable { public double X; public double Y; public double Z; @@ -34,8 +32,7 @@ public NVector4d (double x, double y, double z, double w) W = w; } - internal NVector3d Xyz - { + internal NVector3d Xyz { get => new NVector3d (X, Y, Z); set { X = value.X; @@ -61,7 +58,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y, Z, W); + return HashCode.Combine (X, Y, Z, W); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt2.cs b/src/Simd/VectorInt2.cs index e1682e07a5d3..5802b10cd0ee 100644 --- a/src/Simd/VectorInt2.cs +++ b/src/Simd/VectorInt2.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector2i : IEquatable - { + public struct NVector2i : IEquatable { public int X; public int Y; @@ -47,7 +45,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y); + return HashCode.Combine (X, Y); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt3.cs b/src/Simd/VectorInt3.cs index 40ae57929c98..a1a811c2b0fb 100644 --- a/src/Simd/VectorInt3.cs +++ b/src/Simd/VectorInt3.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector3i : IEquatable - { + public struct NVector3i : IEquatable { public int X; public int Y; public int Z; @@ -51,7 +49,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y, Z); + return HashCode.Combine (X, Y, Z); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt4.cs b/src/Simd/VectorInt4.cs index a4ddc37c4397..26336605fb02 100644 --- a/src/Simd/VectorInt4.cs +++ b/src/Simd/VectorInt4.cs @@ -16,11 +16,9 @@ #if NET // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector4i : IEquatable - { + public struct NVector4i : IEquatable { public int X; public int Y; public int Z; @@ -51,7 +49,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y, Z, W); + return HashCode.Combine (X, Y, Z, W); } public override bool Equals (object? obj) diff --git a/src/StoreKit/SKOverlayAppClipConfiguration.cs b/src/StoreKit/SKOverlayAppClipConfiguration.cs index 4fe5fbdd9871..7f431db6a955 100644 --- a/src/StoreKit/SKOverlayAppClipConfiguration.cs +++ b/src/StoreKit/SKOverlayAppClipConfiguration.cs @@ -10,10 +10,9 @@ namespace StoreKit { #if !COREBUILD - public partial class SKOverlayAppClipConfiguration - { - public NSObject? this[string i] { - get => GetAdditionalValue (i); + public partial class SKOverlayAppClipConfiguration { + public NSObject? this [string i] { + get => GetAdditionalValue (i); set => SetAdditionalValue (value, i); } } diff --git a/src/StoreKit/SKOverlayAppConfiguration.cs b/src/StoreKit/SKOverlayAppConfiguration.cs index 937f5b6b5e87..81d3da2f8c83 100644 --- a/src/StoreKit/SKOverlayAppConfiguration.cs +++ b/src/StoreKit/SKOverlayAppConfiguration.cs @@ -10,10 +10,9 @@ namespace StoreKit { #if !COREBUILD - public partial class SKOverlayAppConfiguration - { - public NSObject? this[string i] { - get => GetAdditionalValue (i); + public partial class SKOverlayAppConfiguration { + public NSObject? this [string i] { + get => GetAdditionalValue (i); set => SetAdditionalValue (value, i); } } diff --git a/src/System.Net.Http/CFNetworkHandler.cs b/src/System.Net.Http/CFNetworkHandler.cs index b94bf44140e2..521c50886157 100644 --- a/src/System.Net.Http/CFNetworkHandler.cs +++ b/src/System.Net.Http/CFNetworkHandler.cs @@ -36,7 +36,7 @@ #if NET using CFNetwork; using CoreFoundation; -using CF=CoreFoundation; +using CF = CoreFoundation; #else using CoreServices; using CoreFoundation; diff --git a/src/UIKit/NSLayoutManager.cs b/src/UIKit/NSLayoutManager.cs index 530730812d64..3c04a9069a0c 100644 --- a/src/UIKit/NSLayoutManager.cs +++ b/src/UIKit/NSLayoutManager.cs @@ -19,7 +19,7 @@ using ObjCRuntime; #if MONOMAC -using UIFont=AppKit.NSFont; +using UIFont = AppKit.NSFont; #endif #if MONOMAC diff --git a/src/UIKit/UIActionSheet.cs b/src/UIKit/UIActionSheet.cs index 285586845534..494a237b948f 100644 --- a/src/UIKit/UIActionSheet.cs +++ b/src/UIKit/UIActionSheet.cs @@ -41,7 +41,7 @@ public UIActionSheet (string title, IUIActionSheetDelegate del, string cancelTit return; } - foreach (string b in other){ + foreach (string b in other) { if (b is not null) AddButton (b); } @@ -49,7 +49,7 @@ public UIActionSheet (string title, IUIActionSheetDelegate del, string cancelTit if (cancelTitle is not null) CancelButtonIndex = AddButton (cancelTitle); } - + #if !NET [Obsolete ("Use overload with a IUIActionSheetDelegate parameter")] public UIActionSheet (string title, UIActionSheetDelegate del) @@ -59,10 +59,10 @@ public UIActionSheet (string title, UIActionSheetDelegate del) #endif public UIActionSheet (string title, IUIActionSheetDelegate del) - : this (title, del, null, null, (string) null) {} + : this (title, del, null, null, (string) null) { } public UIActionSheet (string title) - : this (title, null, null, null, (string) null) {} + : this (title, null, null, null, (string) null) { } public void Add (string name) { @@ -75,7 +75,7 @@ public IEnumerator GetEnumerator () yield return ButtonTitle (i); } } - + } #endif // IOS diff --git a/src/UIKit/UIAppearance.cs b/src/UIKit/UIAppearance.cs index da6d4b9a0b68..481eaa9ca64c 100644 --- a/src/UIKit/UIAppearance.cs +++ b/src/UIKit/UIAppearance.cs @@ -76,7 +76,7 @@ static IntPtr [] TypesToPointers (Type [] whenFoundIn) public static IntPtr GetAppearance (IntPtr class_ptr, params Type [] whenFoundIn) { using (var array = NSArray.FromIntPtrs (TypesToPointers (whenFoundIn))) { - return Messaging.IntPtr_objc_msgSend_IntPtr (class_ptr, + return Messaging.IntPtr_objc_msgSend_IntPtr (class_ptr, Selector.GetHandle (UIAppearance.selAppearanceWhenContainedInInstancesOfClasses), array.Handle); } } @@ -90,7 +90,7 @@ public static IntPtr GetAppearance (IntPtr class_ptr, UITraitCollection traits, throw new ArgumentNullException ("traits"); using (var array = NSArray.FromIntPtrs (TypesToPointers (whenFoundIn))) { - return Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, + return Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, Selector.GetHandle (UIAppearance.selAppearanceForTraitCollectionWhenContainedInInstancesOfClasses), traits.Handle, array.Handle); } diff --git a/src/UIKit/UIButton.cs b/src/UIKit/UIButton.cs index 21bdc132fa36..b389b49c995a 100644 --- a/src/UIKit/UIButton.cs +++ b/src/UIKit/UIButton.cs @@ -15,7 +15,7 @@ public partial class UIButton { public UIButton (UIButtonType type) #if NET - : base (ObjCRuntime.Messaging.NativeHandle_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int)type)) + : base (ObjCRuntime.Messaging.NativeHandle_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int) type)) #else : base (ObjCRuntime.Messaging.IntPtr_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int) type)) #endif diff --git a/src/UIKit/UIDevice.cs b/src/UIKit/UIDevice.cs index afe3d44476c2..cdbfe560d04a 100644 --- a/src/UIKit/UIDevice.cs +++ b/src/UIKit/UIDevice.cs @@ -15,7 +15,7 @@ public partial class UIDevice { public bool CheckSystemVersion (int major, int minor) { #if __MACCATALYST__ - return Runtime.CheckSystemVersion (major, minor, Runtime.iOSSupportVersion); + return Runtime.CheckSystemVersion (major, minor, Runtime.iOSSupportVersion); #else return Runtime.CheckSystemVersion (major, minor, SystemVersion); #endif diff --git a/src/UIKit/UIDocumentBrowserViewController.cs b/src/UIKit/UIDocumentBrowserViewController.cs index 74668099e54b..8781942e7b66 100644 --- a/src/UIKit/UIDocumentBrowserViewController.cs +++ b/src/UIKit/UIDocumentBrowserViewController.cs @@ -31,10 +31,10 @@ namespace UIKit { - public partial class UIDocumentBrowserViewController - { + public partial class UIDocumentBrowserViewController { - static bool CheckSystemVersion () { + static bool CheckSystemVersion () + { #if IOS return SystemVersion.CheckiOS (12, 0); #else diff --git a/src/UIKit/UIImage.cs b/src/UIKit/UIImage.cs index 76fb5eadee3e..4b93d0387ef2 100644 --- a/src/UIKit/UIImage.cs +++ b/src/UIKit/UIImage.cs @@ -32,11 +32,11 @@ partial class UIImage { public void SaveToPhotosAlbum (SaveStatus status) { UIImageStatusDispatcher? dis = null; - UIApplication.EnsureUIThread (); + UIApplication.EnsureUIThread (); if (status is not null) dis = new UIImageStatusDispatcher (status); - + UIImageWriteToSavedPhotosAlbum (Handle, dis is not null ? dis.Handle : IntPtr.Zero, dis is not null ? Selector.GetHandle (UIImageStatusDispatcher.callbackSelector) : IntPtr.Zero, IntPtr.Zero); } #endif @@ -155,7 +155,7 @@ public DataWrapper (IntPtr buffer, uint len) internal class UIImageStatusDispatcher : NSObject { public const string callbackSelector = "Xamarin_Internal__image:didFinishSavingWithError:contextInfo:"; UIImage.SaveStatus status; - + public UIImageStatusDispatcher (UIImage.SaveStatus status) { IsDirectBinding = false; diff --git a/src/UIKit/UINavigationBar.cs b/src/UIKit/UINavigationBar.cs index 516a22786811..0e5579a415df 100644 --- a/src/UIKit/UINavigationBar.cs +++ b/src/UIKit/UINavigationBar.cs @@ -23,12 +23,12 @@ public virtual UITextAttributes GetTitleTextAttributes () { return new UITextAttributes (_TitleTextAttributes); } - + public virtual void SetTitleTextAttributes (UITextAttributes attributes) { if (attributes is null) throw new ArgumentNullException ("attributes"); - + _TitleTextAttributes = attributes.ToDictionary (); } } diff --git a/src/UIKit/UIPasteboard.cs b/src/UIKit/UIPasteboard.cs index 9c9307db7074..c55b53c0a80c 100644 --- a/src/UIKit/UIPasteboard.cs +++ b/src/UIKit/UIPasteboard.cs @@ -25,16 +25,16 @@ UIImage [] GetImageArray (IntPtr handle) var obj = Runtime.GetNSObject (array.ValueAt (i)); var data = obj as NSData; UIImage img; - + if (data is not null) { img = new UIImage (data); } else { img = (UIImage) obj; } - + ret [i] = img; } - + return ret; } } @@ -46,11 +46,11 @@ UIImage [] GetImageArray (IntPtr handle) // API and not make users change their code. [CompilerGenerated] - public virtual UIImage[] Images { + public virtual UIImage [] Images { [Export ("images", ArgumentSemantic.Copy)] get { global::UIKit.UIApplication.EnsureUIThread (); - UIImage[] ret; + UIImage [] ret; if (IsDirectBinding) { ret = GetImageArray (ObjCRuntime.Messaging.IntPtr_objc_msgSend (this.Handle, Selector.GetHandle (selImages))); } else { @@ -58,12 +58,12 @@ public virtual UIImage[] Images { } return ret; } - + [Export ("setImages:", ArgumentSemantic.Copy)] set { global::UIKit.UIApplication.EnsureUIThread (); var nsa_value = NSArray.FromNSObjects (value); - + if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (selSetImages_), nsa_value.Handle); } else { diff --git a/src/UIKit/UIPickerView.cs b/src/UIKit/UIPickerView.cs index dd24a6ea2397..8dce0b97fcc4 100644 --- a/src/UIKit/UIPickerView.cs +++ b/src/UIKit/UIPickerView.cs @@ -2,7 +2,7 @@ using System; -using Foundation; +using Foundation; using CoreGraphics; using ObjCRuntime; diff --git a/src/UIKit/UIPopoverPresentationController.cs b/src/UIKit/UIPopoverPresentationController.cs index 61eb25a88b38..826a0e5ba8a6 100644 --- a/src/UIKit/UIPopoverPresentationController.cs +++ b/src/UIKit/UIPopoverPresentationController.cs @@ -22,7 +22,7 @@ public virtual Type PopoverBackgroundViewType { return Class.Lookup (p); } set { - PopoverBackgroundViewClass = (value is null) ? IntPtr.Zero : + PopoverBackgroundViewClass = (value is null) ? IntPtr.Zero : Class.GetHandle (value); } } diff --git a/src/UIKit/UIStringDrawing.cs b/src/UIKit/UIStringDrawing.cs index 1fad3f3ebc22..6720e7845b79 100644 --- a/src/UIKit/UIStringDrawing.cs +++ b/src/UIKit/UIStringDrawing.cs @@ -8,7 +8,7 @@ using ObjCRuntime; namespace UIKit { - public unsafe static partial class UIStringDrawing { + public unsafe static partial class UIStringDrawing { #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] diff --git a/src/UIKit/UITextAttributes.cs b/src/UIKit/UITextAttributes.cs index 68cee22e67ad..b831b39010b3 100644 --- a/src/UIKit/UITextAttributes.cs +++ b/src/UIKit/UITextAttributes.cs @@ -25,14 +25,14 @@ public class UITextAttributes { public UITextAttributes () { } - + internal UITextAttributes (NSDictionary dict) { if (dict is null) return; - + NSObject val; - + if (dict.TryGetValue (UITextAttributesConstants.Font, out val)) Font = val as UIFont; if (dict.TryGetValue (UITextAttributesConstants.TextColor, out val)) @@ -45,7 +45,7 @@ internal UITextAttributes (NSDictionary dict) TextShadowOffset = value.UIOffsetValue; } } - + internal NSDictionary ToDictionary () { int n = 0; @@ -67,27 +67,27 @@ internal NSDictionary ToDictionary () var keys = new NSObject [n]; var values = new NSObject [n]; n = 0; - if (font is not null){ + if (font is not null) { keys [n] = UITextAttributesConstants.Font; values [n] = font; n++; } - if (text_color is not null){ + if (text_color is not null) { keys [n] = UITextAttributesConstants.TextColor; values [n] = text_color; n++; } - if (text_shadow_color is not null){ + if (text_shadow_color is not null) { keys [n] = UITextAttributesConstants.TextShadowColor; values [n] = text_shadow_color; n++; } - if (text_shadow_offset.Horizontal != 0 || text_shadow_offset.Vertical != 0){ + if (text_shadow_offset.Horizontal != 0 || text_shadow_offset.Vertical != 0) { keys [n] = UITextAttributesConstants.TextShadowOffset; values [n] = NSValue.FromUIOffset (text_shadow_offset); } using (NSArray avalues = NSArray.FromObjects (values), - akeys = NSArray.FromObjects (keys)){ + akeys = NSArray.FromObjects (keys)) { return NSDictionary.FromObjectsAndKeysInternal (avalues, akeys); } } diff --git a/src/UIKit/UIToolbar.cs b/src/UIKit/UIToolbar.cs index 605190d7b70d..fdeb2256aeb9 100644 --- a/src/UIKit/UIToolbar.cs +++ b/src/UIKit/UIToolbar.cs @@ -12,20 +12,20 @@ namespace UIKit { public partial class UIToolbar : UIView { - + // note: we cannot autogenerate this overload and still update the (same) __mt_Items_var local // previously we 'lost' the managed reference to the array and this caused bug #410 // http://bugzilla.xamarin.com/show_bug.cgi?id=410 [Export ("setItems:animated:")] - public virtual void SetItems (UIBarButtonItem[] items, bool animated) + public virtual void SetItems (UIBarButtonItem [] items, bool animated) { if (items is null) throw new ArgumentNullException ("items"); - + // must be identical the [get|set]_Items var nsa_items = NSArray.FromNSObjects (items); - + #if NET if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_bool (this.Handle, Selector.GetHandle ("setItems:animated:"), nsa_items.Handle, animated ? (byte) 1 : (byte) 0); diff --git a/src/UIKit/UIVideo.cs b/src/UIKit/UIVideo.cs index 64bc283fb7fb..82a8d14c1c01 100644 --- a/src/UIKit/UIVideo.cs +++ b/src/UIKit/UIVideo.cs @@ -22,7 +22,7 @@ namespace UIKit { internal class UIVideoStatusDispatcher : NSObject { public const string callbackSelector = "Xamarin_Internal__video:didFinishSavingWithError:contextInfo:"; UIVideo.SaveStatus status; - + public UIVideoStatusDispatcher (UIVideo.SaveStatus status) { this.status = status; @@ -38,13 +38,13 @@ public void Callback (string str, NSError err, IntPtr ctx) DangerousRelease (); } } - + public static class UIVideo { public delegate void SaveStatus (string path, NSError error); - + [DllImport (Constants.UIKitLibrary)] extern static /* BOOL */ byte UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (/* NSString* */ IntPtr videoPath); - + public static bool IsCompatibleWithSavedPhotosAlbum (string path) { UIApplication.EnsureUIThread (); @@ -63,11 +63,11 @@ public static void SaveToPhotosAlbum (string path, SaveStatus status) throw new ArgumentNullException ("status"); UIApplication.EnsureUIThread (); var dis = new UIVideoStatusDispatcher (status); - + using (var ns = new NSString (path)) UISaveVideoAtPathToSavedPhotosAlbum (ns.Handle, dis.Handle, Selector.GetHandle (UIVideoStatusDispatcher.callbackSelector), IntPtr.Zero); } - + } } diff --git a/src/VideoToolbox/VTCompressionSession.cs b/src/VideoToolbox/VTCompressionSession.cs index deb4485ce60f..83dd6febe765 100644 --- a/src/VideoToolbox/VTCompressionSession.cs +++ b/src/VideoToolbox/VTCompressionSession.cs @@ -179,7 +179,7 @@ unsafe extern static VTStatus VTCompressionSessionCreate ( VTVideoEncoderSpecification? encoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. NSDictionary? sourceImageBufferAttributes, // Undocumented options, probably always null #if NET - delegate* unmanaged staticCback) + delegate* unmanaged staticCback) #else CompressionOutputCallback? staticCback) #endif diff --git a/src/VideoToolbox/VTDecompressionSession.cs b/src/VideoToolbox/VTDecompressionSession.cs index 3424ff153749..802d6abc3795 100644 --- a/src/VideoToolbox/VTDecompressionSession.cs +++ b/src/VideoToolbox/VTDecompressionSession.cs @@ -201,8 +201,8 @@ public static VTDecompressionSession Create (CMVideoFormatDescription formatDesc public static VTDecompressionSession? Create (VTDecompressionOutputCallback outputCallback, CMVideoFormatDescription formatDescription, #if NET - VTVideoDecoderSpecification? decoderSpecification = null, // hardware acceleration is default behavior on iOS. no opt-in required. - CVPixelBufferAttributes? destinationImageBufferAttributes = null) + VTVideoDecoderSpecification? decoderSpecification = null, // hardware acceleration is default behavior on iOS. no opt-in required. + CVPixelBufferAttributes? destinationImageBufferAttributes = null) #else VTVideoDecoderSpecification? decoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. CVPixelBufferAttributes? destinationImageBufferAttributes) @@ -222,7 +222,7 @@ public static VTDecompressionSession Create (CMVideoFormatDescription formatDesc VTVideoDecoderSpecification? decoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. NSDictionary? destinationImageBufferAttributes, #if NET - delegate* unmanaged cback) + delegate* unmanaged cback) #else IntPtr cback) #endif diff --git a/src/VideoToolbox/VTRawProcessingSession.cs b/src/VideoToolbox/VTRawProcessingSession.cs index 410529239c7a..7663da13a70c 100644 --- a/src/VideoToolbox/VTRawProcessingSession.cs +++ b/src/VideoToolbox/VTRawProcessingSession.cs @@ -111,7 +111,7 @@ public static nint GetTypeId () [DllImport (Constants.VideoToolboxLibrary)] unsafe static extern VTStatus VTRAWProcessingSessionSetParameterChangedHander ( IntPtr /* VTRAWProcessingSessionRef */ session, - BlockLiteral * /* VTRAWProcessingParameterChangeHandler */ parameterChangeHandler + BlockLiteral* /* VTRAWProcessingParameterChangeHandler */ parameterChangeHandler ); /// Provide a callback that will be called when the VTRawProcessingPlugin changes the set of processing parameters. @@ -145,7 +145,7 @@ unsafe static extern VTStatus VTRAWProcessingSessionProcessFrame ( IntPtr /* VTRAWProcessingSessionRef */ session, IntPtr /* CVPixelBufferRef */ inputPixelBuffer, IntPtr /* CM_NULLABLE CFDictionaryRef */ frameOptions, - BlockLiteral * /* VTRAWProcessingOutputHandler */ outputHandler + BlockLiteral* /* VTRAWProcessingOutputHandler */ outputHandler ); /// Use this function to submit RAW frames for processing using sequence and frame level parameters. diff --git a/src/WebKit/WKPreferences.cs b/src/WebKit/WKPreferences.cs index d498c8262456..b016487cc737 100644 --- a/src/WebKit/WKPreferences.cs +++ b/src/WebKit/WKPreferences.cs @@ -28,7 +28,7 @@ public bool TextInteractionEnabled { #elif MONOMAC if (SystemVersion.CheckmacOS (12, 0)) #endif - return _NewGetTextInteractionEnabled (); + return _NewGetTextInteractionEnabled (); else return _OldTextInteractionEnabled; } diff --git a/src/accessorysetupkit.cs b/src/accessorysetupkit.cs index d7338d289dcd..0739adb6305d 100644 --- a/src/accessorysetupkit.cs +++ b/src/accessorysetupkit.cs @@ -11,16 +11,16 @@ namespace AccessorySetupKit { [Native] [iOS (18, 0)] public enum ASAccessoryState : long { - Unauthorized = 0, - AwaitingAuthorization = 10, - Authorized = 20, + Unauthorized = 0, + AwaitingAuthorization = 10, + Authorized = 20, } [Flags] [Native] [iOS (18, 0)] public enum ASAccessoryRenameOptions : ulong { - Ssid = 1U << 0, + Ssid = 1U << 0, } [Flags] @@ -73,19 +73,19 @@ interface ASAccessory { [Native] [iOS (18, 0)] public enum ASAccessoryEventType : long { - Unknown = 0, - Activated = 10, - Invalidated = 11, - MigrationComplete = 20, - AccessoryAdded = 30, - AccessoryRemoved = 31, - AccessoryChanged = 32, - PickerDidPresent = 40, - PickerDidDismiss = 50, + Unknown = 0, + Activated = 10, + Invalidated = 11, + MigrationComplete = 20, + AccessoryAdded = 30, + AccessoryRemoved = 31, + AccessoryChanged = 32, + PickerDidPresent = 40, + PickerDidDismiss = 50, PickerSetupBridging = 60, - PickerSetupFailed = 70, - PickerSetupPairing = 80, - PickerSetupRename = 90, + PickerSetupFailed = 70, + PickerSetupPairing = 80, + PickerSetupRename = 90, } [BaseType (typeof (NSObject))] @@ -202,18 +202,18 @@ interface ASDiscoveryDescriptor { [iOS (18, 0)] [ErrorDomain ("ASErrorDomain")] enum ASErrorCode : long { - Success = 0, - Unknown = 1, - ActivationFailed = 100, - ConnectionFailed = 150, - DiscoveryTimeout = 200, - ExtensionNotFound = 300, - Invalidated = 400, - InvalidRequest = 450, + Success = 0, + Unknown = 1, + ActivationFailed = 100, + ConnectionFailed = 150, + DiscoveryTimeout = 200, + ExtensionNotFound = 300, + Invalidated = 400, + InvalidRequest = 450, PickerAlreadyActive = 500, - PickerRestricted = 550, - UserCancelled = 700, - UserRestricted = 750, + PickerRestricted = 550, + UserCancelled = 700, + UserRestricted = 750, } [BaseType (typeof (NSObject))] diff --git a/src/appkit.cs b/src/appkit.cs index 7320ec7c35a6..1a5346eefab9 100644 --- a/src/appkit.cs +++ b/src/appkit.cs @@ -15040,7 +15040,7 @@ partial interface NSSpellChecker { bool IsAutomaticTextCompletionEnabled { get; } #if NET - [Async (ResultTypeName="NSSpellCheckerCandidates")] + [Async (ResultTypeName = "NSSpellCheckerCandidates")] #else [Async (ResultTypeName = "NSSpellCheckerCanidates")] #endif @@ -19847,7 +19847,7 @@ NSTextContentType ContentType { // This came from the NSTextFinderClient protocol in legacy Xamarin, but NSTextView doesn't really implement that protocol, // so when it was removed for .NET, we still need to expose the API from NSTextFinderClient that NSTextView actually has. [Export ("selectedRanges", ArgumentSemantic.Copy)] - NSArray SelectedRanges { get; set; } + NSArray SelectedRanges { get; set; } #endif [NoiOS] diff --git a/src/authenticationservices.cs b/src/authenticationservices.cs index 27bdb45f578f..1516e3f1d7bb 100644 --- a/src/authenticationservices.cs +++ b/src/authenticationservices.cs @@ -630,7 +630,8 @@ interface IASAuthorizationControllerDelegate { } [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1048,7 +1049,8 @@ interface IASWebAuthenticationSessionRequestDelegate { } [NoTV] [NoiOS] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1162,7 +1164,8 @@ interface IASAccountAuthenticationModificationControllerDelegate { } [iOS (14, 0)] [NoTV, NoMac] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/avfoundation.cs b/src/avfoundation.cs index 29f1b1c94063..3479fca03b7e 100644 --- a/src/avfoundation.cs +++ b/src/avfoundation.cs @@ -1336,17 +1336,17 @@ interface AVAudio3DMixing { #if NET [Abstract] - [TV (13,0), iOS (13,0)] + [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] [Export ("sourceMode", ArgumentSemantic.Assign)] AVAudio3DMixingSourceMode SourceMode { get; set; } [Abstract] - [TV (13,0), iOS (13,0)] + [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] [Export ("pointSourceInHeadMode", ArgumentSemantic.Assign)] AVAudio3DMixingPointSourceInHeadMode PointSourceInHeadMode { get; set; } - + #else [TV (13, 0), iOS (13, 0)] [Export ("sourceMode", ArgumentSemantic.Assign)] @@ -8858,7 +8858,7 @@ interface AVAssetExportSession { [Export ("supportedFileTypes")] #if NET - string [] SupportedFileTypes { get; } + string [] SupportedFileTypes { get; } #else NSObject [] SupportedFileTypes { get; } #endif @@ -11857,7 +11857,7 @@ interface AVCaptureDeviceDiscoverySession { #else [Static] [Export ("discoverySessionWithDeviceTypes:mediaType:position:")] - AVCaptureDeviceDiscoverySession Create ([BindAs (typeof (AVCaptureDeviceType[]))] NSString[] deviceTypes, [NullAllowed] [BindAs (typeof (AVMediaTypes))] NSString mediaType, AVCaptureDevicePosition position); + AVCaptureDeviceDiscoverySession Create ([BindAs (typeof (AVCaptureDeviceType []))] NSString [] deviceTypes, [NullAllowed][BindAs (typeof (AVMediaTypes))] NSString mediaType, AVCaptureDevicePosition position); #endif [Export ("devices")] diff --git a/src/backgroundassets.cs b/src/backgroundassets.cs index d5dc0fb046f5..4ae0a5a877d8 100644 --- a/src/backgroundassets.cs +++ b/src/backgroundassets.cs @@ -127,7 +127,8 @@ interface IBADownloadManagerDelegate { } [NoTV, Mac (13, 0), iOS (16, 0), MacCatalyst (16, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/browserenginekit.cs b/src/browserenginekit.cs index e5788e8b1abf..53ac4c0f7be8 100644 --- a/src/browserenginekit.cs +++ b/src/browserenginekit.cs @@ -52,11 +52,10 @@ using OS_xpc_object = Foundation.NSObject; namespace BrowserEngineKit { - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BELayerHierarchyHandle : NSSecureCoding - { + interface BELayerHierarchyHandle : NSSecureCoding { [Static] [Export ("handleWithXPCRepresentation:error:")] [return: NullAllowed] @@ -66,11 +65,10 @@ interface BELayerHierarchyHandle : NSSecureCoding OS_xpc_object CreateXpcRepresentation (); } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BELayerHierarchy - { + interface BELayerHierarchy { [Static] [Export ("layerHierarchyWithError:")] [return: NullAllowed] @@ -86,19 +84,17 @@ interface BELayerHierarchy void Invalidate (); } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIView))] - interface BELayerHierarchyHostingView - { + interface BELayerHierarchyHostingView { [Export ("handle", ArgumentSemantic.Strong), NullAllowed] BELayerHierarchyHandle LayerHierarchyHandle { get; set; } } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding - { + interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding { [Static] [Export ("coordinatorWithError:")] [return: NullAllowed] @@ -123,11 +119,10 @@ interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding void Commit (); } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(UIContextMenuConfiguration))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (UIContextMenuConfiguration))] [DisableDefaultCtor] - interface BEContextMenuConfiguration - { + interface BEContextMenuConfiguration { [DesignatedInitializer] [Export ("init")] NativeHandle Constructor (); @@ -136,13 +131,12 @@ interface BEContextMenuConfiguration bool Fulfill ([NullAllowed] UIContextMenuConfiguration configuration); } - delegate bool BEDragInteractionDelegateGetDragItemsCallback (UIDragItem[] items); + delegate bool BEDragInteractionDelegateGetDragItemsCallback (UIDragItem [] items); - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIDragInteractionDelegate))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BEDragInteractionDelegate - { + interface BEDragInteractionDelegate { [Export ("dragInteraction:prepareDragSession:completion:")] void PrepareDragSession (BEDragInteraction dragInteraction, IUIDragSession session, Func completion); @@ -150,12 +144,11 @@ interface BEDragInteractionDelegate void GetDragItems (BEDragInteraction dragInteraction, IUIDragSession session, CGPoint point, BEDragInteractionDelegateGetDragItemsCallback completion); } - interface IBEDragInteractionDelegate {} + interface IBEDragInteractionDelegate { } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIDragInteraction))] - interface BEDragInteraction - { + interface BEDragInteraction { [Wrap ("WeakDelegate")] [NullAllowed] IBEDragInteractionDelegate Delegate { get; } @@ -168,11 +161,10 @@ interface BEDragInteraction NativeHandle Constructor (IBEDragInteractionDelegate @delegate); } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIScrollViewDelegate))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BEScrollViewDelegate - { + interface BEScrollViewDelegate { [Export ("scrollView:handleScrollUpdate:completion:")] void HandleScrollUpdate (BEScrollView scrollView, BEScrollViewScrollUpdate scrollUpdate, Action completion); @@ -181,12 +173,11 @@ interface BEScrollViewDelegate BEScrollView GetParentScrollView (BEScrollView scrollView); } - interface IBEScrollViewDelegate {} + interface IBEScrollViewDelegate { } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(UIScrollView))] - interface BEScrollView - { + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (UIScrollView))] + interface BEScrollView { [Wrap ("WeakDelegate")] [NullAllowed] IBEScrollViewDelegate Delegate { get; set; } @@ -195,21 +186,19 @@ interface BEScrollView NSObject WeakDelegate { get; set; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BEScrollViewScrollUpdatePhase : long - { + public enum BEScrollViewScrollUpdatePhase : long { Began, Changed, Ended, Cancelled, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEScrollViewScrollUpdate - { + interface BEScrollViewScrollUpdate { [Export ("timestamp")] double Timestamp { get; } @@ -225,11 +214,10 @@ interface BEScrollViewScrollUpdate delegate void BEWebContentProcessCreateCallback ([NullAllowed] BEWebContentProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEWebContentProcess - { + interface BEWebContentProcess { [Static] [Export ("webContentProcessWithInterruptionHandler:completion:")] [Async] @@ -257,7 +245,7 @@ interface BEWebContentProcess IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error); // Inlined from the CapabilityInvalidationHandler (BEWebContentProcess) category - [NoTV, NoMac, iOS (17,6), MacCatalyst (17, 6)] + [NoTV, NoMac, iOS (17, 6), MacCatalyst (17, 6)] [Export ("grantCapability:error:invalidationHandler:")] [return: NullAllowed] IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error, Action invalidationHandler); @@ -265,11 +253,10 @@ interface BEWebContentProcess delegate void BENetworkingProcessCreateCallback ([NullAllowed] BENetworkingProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BENetworkingProcess - { + interface BENetworkingProcess { [Static] [Export ("networkProcessWithInterruptionHandler:completion:")] [Async] @@ -302,11 +289,10 @@ interface BENetworkingProcess delegate void BERenderingProcessCreateCallback ([NullAllowed] BERenderingProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14, 3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BERenderingProcess - { + interface BERenderingProcess { [Static] [Export ("renderingProcessWithInterruptionHandler:completion:")] [Async] @@ -334,25 +320,24 @@ interface BERenderingProcess IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error); // Inlined from the CapabilityInvalidationHandler (BERenderingProcess) category - [NoTV, NoMac, iOS (17,6), MacCatalyst (17, 6)] + [NoTV, NoMac, iOS (17, 6), MacCatalyst (17, 6)] [Export ("grantCapability:error:invalidationHandler:")] [return: NullAllowed] IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error, Action invalidationHandler); } // Headers say this is available on macOS 14.3, but the BETextInput type isn't, so just remove this type from macOS as well. - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (NSObject))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BETextInputDelegate - { + interface BETextInputDelegate { [Abstract] [Export ("shouldDeferEventHandlingToSystemForTextInput:context:")] bool ShouldDeferEventHandlingToSystem (IBETextInput textInput, BEKeyEntryContext keyEventContext); [Abstract] [Export ("textInput:setCandidateSuggestions:")] - void SetCandidateSuggestions (IBETextInput textInput, [NullAllowed] BETextSuggestion[] suggestions); + void SetCandidateSuggestions (IBETextInput textInput, [NullAllowed] BETextSuggestion [] suggestions); [Abstract] [Export ("selectionWillChangeForTextInput:")] @@ -371,21 +356,19 @@ interface BETextInputDelegate void InvalidateTextEntryContext (IBETextInput textInput); } - interface IBETextInputDelegate {} + interface IBETextInputDelegate { } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BEKeyPressState : long - { + public enum BEKeyPressState : long { Down = 1, Up = 2, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEKeyEntry - { + interface BEKeyEntry { [Export ("key")] UIKey Key { get; } @@ -399,10 +382,9 @@ interface BEKeyEntry double Timestamp { get; } } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BEGestureType : long - { + public enum BEGestureType : long { Loupe = 0, OneFingerTap = 1, DoubleTapAndHold = 2, @@ -415,10 +397,9 @@ public enum BEGestureType : long ForceTouch = 15, } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BESelectionTouchPhase : long - { + public enum BESelectionTouchPhase : long { Started, Moved, Ended, @@ -428,51 +409,46 @@ public enum BESelectionTouchPhase : long } [Flags] - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BESelectionFlags : ulong - { + public enum BESelectionFlags : ulong { None = 0x0, WordIsNearTap = 1uL << 0, SelectionFlipped = 1uL << 1, PhraseBoundaryChanged = 1uL << 2, } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextAlternatives - { + interface BETextAlternatives { [Export ("primaryString")] string PrimaryString { get; } [Export ("alternativeStrings")] - string[] AlternativeStrings { get; } + string [] AlternativeStrings { get; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Flags] [Native] - public enum BETextReplacementOptions : ulong - { + public enum BETextReplacementOptions : ulong { None = 0x0, AddUnderline = 1uL << 0, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Flags] [Native] - public enum BEKeyModifierFlags : long - { + public enum BEKeyModifierFlags : long { None, Shift, CapsLock, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEResponderEditActions : UIResponderStandardEditActions - { + interface BEResponderEditActions : UIResponderStandardEditActions { [Export ("share:")] void Share ([NullAllowed] NSObject sender); @@ -498,10 +474,9 @@ interface BEResponderEditActions : UIResponderStandardEditActions void TransliterateChinese ([NullAllowed] NSObject sender); } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BETextSelectionDirectionNavigation - { + interface BETextSelectionDirectionNavigation { [Abstract] [Export ("moveInLayoutDirection:")] void MoveInLayoutDirection (UITextLayoutDirection direction); @@ -519,10 +494,9 @@ interface BETextSelectionDirectionNavigation void ExtendInStorageDirection (UITextStorageDirection direction, UITextGranularity granularity); } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEExtendedTextInputTraits : UITextInputTraits - { + interface BEExtendedTextInputTraits : UITextInputTraits { [Export ("singleLineDocument")] bool SingleLineDocument { [Bind ("isSingleLineDocument")] get; } @@ -539,17 +513,16 @@ interface BEExtendedTextInputTraits : UITextInputTraits UIColor SelectionHighlightColor { get; } } - interface IBEExtendedTextInputTraits {} + interface IBEExtendedTextInputTraits { } delegate void BETextInputHandleKeyEntryCallback (BEKeyEntry entry, bool handled); - delegate void BETextInputReplaceTextCallback (UITextSelectionRect[] rects); + delegate void BETextInputReplaceTextCallback (UITextSelectionRect [] rects); delegate void BETextInputRequestTextContextForAutocorrectionCallback (BETextDocumentContext context); - delegate void BETextInputRequestTextRectsCallback (UITextSelectionRect[] rects); + delegate void BETextInputRequestTextRectsCallback (UITextSelectionRect [] rects); - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BEResponderEditActions - { + interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BEResponderEditActions { [Wrap ("WeakAsyncInputDelegate"), Abstract] [NullAllowed] IBETextInputDelegate AsyncInputDelegate { get; set; } @@ -677,7 +650,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Abstract] [Export ("selectionRectsForRange:")] - UITextSelectionRect[] GetSelectionRects (UITextRange range); + UITextSelectionRect [] GetSelectionRects (UITextRange range); [Abstract] [Export ("selectWordForReplacement")] @@ -766,7 +739,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Abstract] [return: NullAllowed] [Export ("alternativesForSelectedText")] - BETextAlternatives[] GetAlternativesForSelectedText (); + BETextAlternatives [] GetAlternativesForSelectedText (); [Abstract] [Export ("addTextAlternatives:")] @@ -776,7 +749,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Export ("insertTextAlternatives:")] void InsertTextAlternatives (BETextAlternatives alternatives); - [iOS (18,0), MacCatalyst (18, 0), TV (18, 0)] + [iOS (18, 0), MacCatalyst (18, 0), TV (18, 0)] [Export ("removeTextAlternatives")] void RemoveTextAlternatives (); @@ -824,18 +797,17 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Export ("cancelAutoscroll")] void CancelAutoscroll (); - [iOS (18,0), MacCatalyst (18, 0), TV (18, 0)] + [iOS (18, 0), MacCatalyst (18, 0), TV (18, 0)] [Export ("keyboardWillDismiss")] void KeyboardWillDismiss (); } - interface IBETextInput {} + interface IBETextInput { } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextSuggestion - { + interface BETextSuggestion { [Export ("initWithInputText:")] NativeHandle Constructor (string inputText); @@ -843,19 +815,17 @@ interface BETextSuggestion string InputText { get; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(BETextSuggestion))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (BETextSuggestion))] [DisableDefaultCtor] - interface BEAutoFillTextSuggestion - { + interface BEAutoFillTextSuggestion { [Export ("contents", ArgumentSemantic.Copy)] NSDictionary Contents { get; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] - interface BETextInteraction : UIInteraction - { + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] + interface BETextInteraction : UIInteraction { [Wrap ("WeakDelegate")] [NullAllowed] IBETextInteractionDelegate Delegate { get; set; } @@ -916,11 +886,10 @@ interface BETextInteraction : UIInteraction } // Headers say this is available on macOS 14.3, but the BETextInteraction type isn't, so just remove this type from macOS as well. - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (NSObject))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BETextInteractionDelegate - { + interface BETextInteractionDelegate { [Abstract] [Export ("systemWillChangeSelectionForInteraction:")] void SystemWillChangeSelection (BETextInteraction textInteraction); @@ -930,13 +899,12 @@ interface BETextInteractionDelegate void SystemDidChangeSelection (BETextInteraction textInteraction); } - interface IBETextInteractionDelegate {} + interface IBETextInteractionDelegate { } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEKeyEntryContext - { + interface BEKeyEntryContext { [Export ("keyEntry", ArgumentSemantic.Strong)] BEKeyEntry KeyEntry { get; } @@ -955,10 +923,9 @@ interface BEKeyEntryContext } [Flags] - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BETextDocumentRequestOptions : long - { + public enum BETextDocumentRequestOptions : long { None = 0x0, Text = 1L << 0, AttributedText = 1L << 1, @@ -967,11 +934,10 @@ public enum BETextDocumentRequestOptions : long AutocorrectedRanges = 1L << 7, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextDocumentRequest - { + interface BETextDocumentRequest { [Export ("options", ArgumentSemantic.Assign)] BETextDocumentRequestOptions Options { get; set; } @@ -982,11 +948,10 @@ interface BETextDocumentRequest nint GranularityCount { get; set; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextDocumentContext - { + interface BETextDocumentContext { [Export ("initWithSelectedText:contextBefore:contextAfter:markedText:selectedRangeInMarkedText:")] NativeHandle Constructor ([NullAllowed] string selectedText, [NullAllowed] string contextBefore, [NullAllowed] string contextAfter, [NullAllowed] string markedText, NSRange selectedRangeInMarkedText); @@ -997,13 +962,12 @@ interface BETextDocumentContext void AddTextRect (CGRect rect, NSRange range); [Export ("autocorrectedRanges", ArgumentSemantic.Copy)] - NSValue[] AutocorrectedRanges { get; set; } + NSValue [] AutocorrectedRanges { get; set; } } - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEProcessCapabilityGrant - { + interface BEProcessCapabilityGrant { [Abstract] [Export ("invalidate")] bool Invalidate (); @@ -1013,13 +977,12 @@ interface BEProcessCapabilityGrant bool Valid { [Bind ("isValid")] get; } } - interface IBEProcessCapabilityGrant {} + interface IBEProcessCapabilityGrant { } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEMediaEnvironment - { + interface BEMediaEnvironment { [Export ("initWithWebPageURL:")] [DesignatedInitializer] NativeHandle Constructor (NSUrl url); @@ -1041,11 +1004,10 @@ interface BEMediaEnvironment AVCaptureSession MakeCaptureSession ([NullAllowed] out NSError error); } - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEProcessCapability - { + interface BEProcessCapability { [NoMac] [Static] [Export ("mediaPlaybackAndCaptureWithEnvironment:")] @@ -1067,11 +1029,10 @@ interface BEProcessCapability IBEProcessCapabilityGrant Request ([NullAllowed] out NSError error); } - [TV (17, 5), Mac (14, 5), iOS (17,5), MacCatalyst (17, 5)] - [BaseType (typeof(NSObject))] + [TV (17, 5), Mac (14, 5), iOS (17, 5), MacCatalyst (17, 5)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEWebAppManifest - { + interface BEWebAppManifest { [Export ("initWithJSONData:manifestURL:")] [DesignatedInitializer] NativeHandle Constructor (NSData jsonData, NSUrl manifestUrl); @@ -1085,8 +1046,7 @@ interface BEWebAppManifest [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Native] - public enum BEAccessibilityPressedState : long - { + public enum BEAccessibilityPressedState : long { Undefined = 0, False, True, @@ -1096,8 +1056,7 @@ public enum BEAccessibilityPressedState : long [Flags] [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Native] - public enum BEAccessibilityContainerType : ulong - { + public enum BEAccessibilityContainerType : ulong { None = 0x0, Landmark = 1uL << 0, Table = 1uL << 1, @@ -1116,8 +1075,7 @@ public enum BEAccessibilityContainerType : ulong [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Category] [BaseType (typeof (NSObject))] - interface NSObject_BEAccessibility - { + interface NSObject_BEAccessibility { [Export ("browserAccessibilityCurrentStatus")] [return: NullAllowed] string GetBrowserAccessibilityCurrentStatus (); @@ -1225,14 +1183,12 @@ public enum BEAccessibilityNotification : long { [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] - interface BEAccessibilityTextMarker : NSCopying, NSSecureCoding - { + interface BEAccessibilityTextMarker : NSCopying, NSSecureCoding { } [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] - interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding - { + interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding { [Export ("startMarker", ArgumentSemantic.Strong)] BEAccessibilityTextMarker StartMarker { get; set; } @@ -1242,8 +1198,7 @@ interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEAccessibilityTextMarkerSupport - { + interface BEAccessibilityTextMarkerSupport { [Abstract] [Export ("accessibilityBoundsForTextMarkerRange:")] CGRect GetAccessibilityBounds (BEAccessibilityTextMarkerRange range); @@ -1305,8 +1260,7 @@ interface BEAccessibilityTextMarkerSupport [NoTV, NoMac, iOS (18, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEDownloadMonitorLocation - { + interface BEDownloadMonitorLocation { [Export ("url")] NSUrl Url { get; } @@ -1321,8 +1275,7 @@ interface BEDownloadMonitorLocation [NoTV, NoMac, iOS (18, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEDownloadMonitor - { + interface BEDownloadMonitor { [Export ("initWithSourceURL:destinationURL:observedProgress:liveActivityAccessToken:")] NativeHandle Constructor (NSUrl sourceUrl, NSUrl destinationUrl, NSProgress observedProgress, NSData liveActivityAccessToken); diff --git a/src/contactsui.cs b/src/contactsui.cs index 21e5fb594382..e4bafaa3c6aa 100644 --- a/src/contactsui.cs +++ b/src/contactsui.cs @@ -69,11 +69,12 @@ interface CNContactPickerViewController { interface ICNContactPickerDelegate { } #if MONOMAC - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface CNContactPickerDelegate - { + [BaseType (typeof (NSObject))] + interface CNContactPickerDelegate { [Export ("contactPicker:didSelectContact:")] void ContactSelected (CNContactPicker picker, CNContact contact); diff --git a/src/coreanimation.cs b/src/coreanimation.cs index 929bd78831e8..701e61be1182 100644 --- a/src/coreanimation.cs +++ b/src/coreanimation.cs @@ -1272,7 +1272,8 @@ interface CALayerDelegate { /// /// /// Apple documentation for CAEAGLLayer - [NoMac][NoMacCatalyst] + [NoMac] + [NoMacCatalyst] [Deprecated (PlatformName.TvOS, 12, 0, message: "Use 'CAMetalLayer' instead.")] [Deprecated (PlatformName.iOS, 12, 0, message: "Use 'CAMetalLayer' instead.")] [BaseType (typeof (CALayer))] @@ -1301,7 +1302,7 @@ interface CAAction { /// [BaseType (typeof (NSObject) #if NET - , Delegates = new string [] {"WeakDelegate"}, Events = new Type [] { typeof (CAAnimationDelegate) } + , Delegates = new string [] { "WeakDelegate" }, Events = new Type [] { typeof (CAAnimationDelegate) } #endif )] interface CAAnimation : CAAction, CAMediaTiming, NSSecureCoding, NSMutableCopying, SCNAnimationProtocol { diff --git a/src/coredata.cs b/src/coredata.cs index 5b807e12de6c..6fd01dfced52 100644 --- a/src/coredata.cs +++ b/src/coredata.cs @@ -624,7 +624,7 @@ interface NSFetchedResultsController { string GetSectionIndexTitle (string sectionName); [Export ("sectionIndexTitles")] - string[] SectionIndexTitles { get; } + string [] SectionIndexTitles { get; } #endif [Static] @@ -895,7 +895,7 @@ interface NSManagedObject : NSFetchRequestResult { #if XAMCORE_5_0 NSDictionary GetCommittedValues ([NullAllowed] string[] keys); #elif NET - NSDictionary GetCommittedValues ([NullAllowed] string[] keys); + NSDictionary GetCommittedValues ([NullAllowed] string [] keys); #else NSDictionary CommittedValuesForKeys ([NullAllowed] string [] keys); #endif @@ -1271,7 +1271,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { [Static, Export ("mergedModelFromBundles:")] [return: NullAllowed] #if NET - NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles); + NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle [] bundles); #else NSManagedObjectModel MergedModelFromBundles ([NullAllowed] NSBundle [] bundles); #endif @@ -1337,7 +1337,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { #if XAMCORE_5_0 NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles, NSDictionary metadata); #elif NET - NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles, NSDictionary metadata); + NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle [] bundles, NSDictionary metadata); #else NSManagedObjectModel MergedModelFromBundles ([NullAllowed] NSBundle [] bundles, NSDictionary metadata); #endif @@ -1347,7 +1347,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { #if XAMCORE_5_0 NSManagedObjectModel GetModelByMerging (NSManagedObjectModel[] models, NSDictionary metadata); #elif NET - NSManagedObjectModel GetModelByMerging (NSManagedObjectModel[] models, NSDictionary metadata); + NSManagedObjectModel GetModelByMerging (NSManagedObjectModel [] models, NSDictionary metadata); #else NSManagedObjectModel ModelByMergingModels (NSManagedObjectModel [] models, NSDictionary metadata); #endif @@ -1395,7 +1395,7 @@ interface NSMappingModel { [Static, Export ("mappingModelFromBundles:forSourceModel:destinationModel:")] [return: NullAllowed] #if NET - NSMappingModel GetMappingModel ([NullAllowed] NSBundle[] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); + NSMappingModel GetMappingModel ([NullAllowed] NSBundle [] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); #else NSMappingModel MappingModelFromBundles ([NullAllowed] NSBundle [] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); #endif @@ -2386,7 +2386,7 @@ interface NSAsynchronousFetchResult { [Export ("finalResult", ArgumentSemantic.Retain)] [NullAllowed] #if NET - INSFetchRequestResult[] FinalResult { get; } + INSFetchRequestResult [] FinalResult { get; } #else NSObject [] FinalResult { get; } #endif diff --git a/src/corehaptics.cs b/src/corehaptics.cs index dd6df1f4d4a5..150be43b5014 100644 --- a/src/corehaptics.cs +++ b/src/corehaptics.cs @@ -22,7 +22,7 @@ namespace CoreHaptics { // we are not binding the API on Mac OS X yet due to an issue on Apples side: https://github.com/xamarin/maccore/issues/1951 #if MONOMAC || TV - interface AVAudioSession {} + interface AVAudioSession { } #endif [iOS (13, 0), TV (14, 0)] diff --git a/src/coreimage.cs b/src/coreimage.cs index be8db0eee89f..1a2bb50e4a2f 100644 --- a/src/coreimage.cs +++ b/src/coreimage.cs @@ -256,14 +256,16 @@ interface CIContext { CIContext Create (); #if HAS_OPENGLES - [NoMac][NoMacCatalyst] + [NoMac] + [NoMacCatalyst] [Deprecated (PlatformName.iOS, 12, 0)] [Deprecated (PlatformName.TvOS, 12, 0)] [Static] [Export ("contextWithEAGLContext:")] CIContext FromContext (EAGLContext eaglContext); - [NoMac][NoMacCatalyst] + [NoMac] + [NoMacCatalyst] [Deprecated (PlatformName.iOS, 12, 0)] [Deprecated (PlatformName.TvOS, 12, 0)] [Static] diff --git a/src/corelocation.cs b/src/corelocation.cs index 07b38a503d6e..f728e652bfee 100644 --- a/src/corelocation.cs +++ b/src/corelocation.cs @@ -58,7 +58,7 @@ public enum CLProximity : long { [ErrorDomain ("CLLocationPushServiceErrorDomain")] #if NET // Apple fixed this in Xcode 13.1 - [iOS (15,0), NoTV, NoMacCatalyst, NoMac] + [iOS (15, 0), NoTV, NoMacCatalyst, NoMac] #else [iOS (15, 0), NoTV, MacCatalyst (15, 0), NoMac] #endif @@ -1064,7 +1064,7 @@ interface CLBeaconIdentityConstraint : NSCopying, NSSecureCoding { } #if NET // Apple fixed this in Xcode 13.1 - [iOS (15,0), NoTV, NoMacCatalyst, NoMac] + [iOS (15, 0), NoTV, NoMacCatalyst, NoMac] #else [iOS (15, 0), NoTV, MacCatalyst (15, 0), NoMac] #endif diff --git a/src/corenfc.cs b/src/corenfc.cs index bcabf9246b31..49d22130a2d8 100644 --- a/src/corenfc.cs +++ b/src/corenfc.cs @@ -870,7 +870,7 @@ enum VasErrorCode [MacCatalyst (13, 1)] #if NET [Native] - enum NFCVasMode + enum NFCVasMode #else [Native ("NFCVASMode")] enum VasMode @@ -1071,7 +1071,8 @@ interface INFCTagReaderSessionDelegate { } [iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1119,7 +1120,8 @@ interface INFCVasReaderSessionDelegate { } [iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/coretext.cs b/src/coretext.cs index bb02cfff3cd8..40d28ebdfb86 100644 --- a/src/coretext.cs +++ b/src/coretext.cs @@ -126,7 +126,8 @@ interface CTFontManagerErrorKeys { #if NET [Internal] - [Static][Partial] + [Static] + [Partial] interface CTBaselineClassID { [Field ("kCTBaselineClassRoman")] NSString Roman { get; } @@ -148,7 +149,8 @@ interface CTBaselineClassID { } [Internal] - [Static][Partial] + [Static] + [Partial] interface CTBaselineFontID { [Field ("kCTBaselineReferenceFont")] NSString Reference { get; } @@ -274,7 +276,8 @@ interface CTFontTraitKey { } [Internal] - [Static][Partial] + [Static] + [Partial] interface CTFontNameKeyId { [Field ("kCTFontCopyrightNameKey")] NSString Copyright { get; } diff --git a/src/cryptotokenkit.cs b/src/cryptotokenkit.cs index 7da6fd74417a..cd5de12aa674 100644 --- a/src/cryptotokenkit.cs +++ b/src/cryptotokenkit.cs @@ -20,8 +20,7 @@ namespace CryptoTokenKit { [Native] [ErrorDomain ("TKErrorDomain")] [iOS (9, 0), Mac (10, 10), MacCatalyst (13, 1), TV (9, 0)] - public enum TKErrorCode : long - { + public enum TKErrorCode : long { NotImplemented = -1, CommunicationError = -2, CorruptedData = -3, @@ -38,8 +37,7 @@ public enum TKErrorCode : long #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] [Native] - public enum TKSmartCardSlotState : long - { + public enum TKSmartCardSlotState : long { Missing = 0, Empty = 1, Probing = 2, @@ -52,8 +50,7 @@ public enum TKSmartCardSlotState : long #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINCharset")] - public enum TKSmartCardPinCharset : long - { + public enum TKSmartCardPinCharset : long { Numeric = 0, Alphanumeric = 1, UpperAlphanumeric = 2, @@ -64,8 +61,7 @@ public enum TKSmartCardPinCharset : long #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINEncoding")] - public enum TKSmartCardPinEncoding : long - { + public enum TKSmartCardPinEncoding : long { Binary = 0, Ascii = 1, Bcd = 2, @@ -76,8 +72,7 @@ public enum TKSmartCardPinEncoding : long #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINJustification")] - public enum TKSmartCardPinJustification : long - { + public enum TKSmartCardPinJustification : long { Left = 0, Right = 1, } @@ -88,8 +83,7 @@ public enum TKSmartCardPinJustification : long [Flags] [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINCompletion")] - public enum TKSmartCardPinCompletion : ulong - { + public enum TKSmartCardPinCompletion : ulong { MaxLength = (1uL << 0), Key = (1uL << 1), Timeout = (1uL << 2), @@ -101,8 +95,7 @@ public enum TKSmartCardPinCompletion : ulong [Flags] [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINConfirmation")] - public enum TKSmartCardPinConfirmation : ulong - { + public enum TKSmartCardPinConfirmation : ulong { None = 0x0, New = (1uL << 0), Current = (1uL << 1), @@ -114,8 +107,7 @@ public enum TKSmartCardPinConfirmation : ulong [Flags] [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] [Native] - public enum TKSmartCardProtocol : ulong - { + public enum TKSmartCardProtocol : ulong { None = 0x0, T0 = (1uL << 0), T1 = (1uL << 1), @@ -128,8 +120,7 @@ public enum TKSmartCardProtocol : ulong #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Native] - public enum TKTokenOperation : long - { + public enum TKTokenOperation : long { None = 0, ReadData = 1, SignData = 2, @@ -142,8 +133,7 @@ public enum TKTokenOperation : long #endif [iOS (13, 0), Mac (10, 12), MacCatalyst (13, 1), TV (13, 0)] [Protocol] - interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate - { + interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate { [Abstract] [Export ("tokenDriver:createTokenForSmartCard:AID:error:")] [return: NullAllowed] @@ -153,15 +143,14 @@ interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKSmartCardTokenDriverDelegate {} + interface ITKSmartCardTokenDriverDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Protocol] - interface TKSmartCardUserInteractionDelegate - { + interface TKSmartCardUserInteractionDelegate { [Export ("characterEnteredInUserInteraction:")] void CharacterEntered (TKSmartCardUserInteraction interaction); @@ -187,16 +176,15 @@ interface TKSmartCardUserInteractionDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKSmartCardUserInteractionDelegate {} + interface ITKSmartCardUserInteractionDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface TKTokenDelegate - { + [BaseType (typeof (NSObject))] + interface TKTokenDelegate { [Abstract] [Export ("token:createSessionWithError:")] [return: NullAllowed] @@ -209,17 +197,16 @@ interface TKTokenDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenDelegate {} + interface ITKTokenDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface TKTokenDriverDelegate - { - [TV (14,0), Mac (10,15), iOS (14,0)] + [BaseType (typeof (NSObject))] + interface TKTokenDriverDelegate { + [TV (14, 0), Mac (10, 15), iOS (14, 0)] [Export ("tokenDriver:tokenForConfiguration:error:")] [return: NullAllowed] TKToken GetToken (TKTokenDriver driver, TKTokenConfiguration configuration, [NullAllowed] out NSError error); @@ -231,16 +218,15 @@ interface TKTokenDriverDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenDriverDelegate {} + interface ITKTokenDriverDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface TKTokenSessionDelegate - { + [BaseType (typeof (NSObject))] + interface TKTokenSessionDelegate { [Export ("tokenSession:beginAuthForOperation:constraint:error:")] [return: NullAllowed] TKTokenAuthOperation BeginAuthentication (TKTokenSession session, TKTokenOperation operation, NSObject constraint, [NullAllowed] out NSError error); @@ -264,15 +250,14 @@ interface TKTokenSessionDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenSessionDelegate {} + interface ITKTokenSessionDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTlvRecord), Name = "TKBERTLVRecord")] - interface TKBerTlvRecord - { + [BaseType (typeof (TKTlvRecord), Name = "TKBERTLVRecord")] + interface TKBerTlvRecord { [Static] [Export ("dataForTag:")] NSData GetData (ulong tag); @@ -281,16 +266,15 @@ interface TKBerTlvRecord NativeHandle Constructor (ulong tag, NSData value); [Export ("initWithTag:records:")] - NativeHandle Constructor (ulong tag, TKTlvRecord[] records); + NativeHandle Constructor (ulong tag, TKTlvRecord [] records); } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTlvRecord), Name = "TKCompactTLVRecord")] - interface TKCompactTlvRecord - { + [BaseType (typeof (TKTlvRecord), Name = "TKCompactTLVRecord")] + interface TKCompactTlvRecord { [Export ("initWithTag:value:")] NativeHandle Constructor (byte tag, NSData value); } @@ -299,9 +283,8 @@ interface TKCompactTlvRecord [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTlvRecord), Name = "TKSimpleTLVRecord")] - interface TKSimpleTlvRecord - { + [BaseType (typeof (TKTlvRecord), Name = "TKSimpleTLVRecord")] + interface TKSimpleTlvRecord { [Export ("initWithTag:value:")] NativeHandle Constructor (byte tag, NSData value); } @@ -320,9 +303,8 @@ interface TKSimpleTlvRecord [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] - interface TKSmartCard - { + [BaseType (typeof (NSObject))] + interface TKSmartCard { [Export ("slot")] TKSmartCardSlot Slot { get; } @@ -377,11 +359,11 @@ interface TKSmartCard [Export ("sendIns:p1:p2:data:le:reply:")] void Send (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, TKSmartCardSendCallback reply); - [Mac (10,12)] + [Mac (10, 12)] [Export ("inSessionWithError:executeBlock:")] bool ExecuteBlock ([NullAllowed] out NSError error, TKSmartCardExecuteCallback block); - [Mac (10,12)] + [Mac (10, 12)] [Export ("sendIns:p1:p2:data:le:sw:error:")] [return: NullAllowed] NSData Send (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, out ushort sw, [NullAllowed] out NSError error); @@ -391,10 +373,9 @@ interface TKSmartCard [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject), Name = "TKSmartCardATR")] + [BaseType (typeof (NSObject), Name = "TKSmartCardATR")] [DisableDefaultCtor] - interface TKSmartCardAtr - { + interface TKSmartCardAtr { [Export ("initWithBytes:")] NativeHandle Constructor (NSData bytes); @@ -405,8 +386,8 @@ interface TKSmartCardAtr NSData Bytes { get; } [Export ("protocols")] - [BindAs (typeof (TKSmartCardProtocol[]))] - NSNumber[] Protocols { get; } + [BindAs (typeof (TKSmartCardProtocol []))] + NSNumber [] Protocols { get; } // -(TKSmartCardATRInterfaceGroup * _Nullable)interfaceGroupAtIndex:(NSInteger)index; [Export ("interfaceGroupAtIndex:")] @@ -423,16 +404,15 @@ interface TKSmartCardAtr [Mac (10, 12)] [Export ("historicalRecords")] [NullAllowed] - TKCompactTlvRecord[] HistoricalRecords { get; } + TKCompactTlvRecord [] HistoricalRecords { get; } } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject), Name = "TKSmartCardATRInterfaceGroup")] - interface TKSmartCardAtrInterfaceGroup - { + [BaseType (typeof (NSObject), Name = "TKSmartCardATRInterfaceGroup")] + interface TKSmartCardAtrInterfaceGroup { [NullAllowed, Export ("TA")] NSNumber TA { get; } @@ -453,10 +433,9 @@ interface TKSmartCardAtrInterfaceGroup [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenSession - { + interface TKTokenSession { [Export ("initWithToken:")] [DesignatedInitializer] NativeHandle Constructor (TKToken token); @@ -476,9 +455,8 @@ interface TKTokenSession [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject), Name = "TKSmartCardPINFormat")] - interface TKSmartCardPinFormat - { + [BaseType (typeof (NSObject), Name = "TKSmartCardPINFormat")] + interface TKSmartCardPinFormat { [Export ("charset", ArgumentSemantic.Assign)] TKSmartCardPinCharset Charset { get; set; } @@ -511,9 +489,8 @@ interface TKSmartCardPinFormat [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] - interface TKSmartCardSlot - { + [BaseType (typeof (NSObject))] + interface TKSmartCardSlot { [Export ("state")] TKSmartCardSlotState State { get; } @@ -543,22 +520,21 @@ interface TKSmartCardSlot [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKSmartCardSlotManager - { + interface TKSmartCardSlotManager { [Static] [NullAllowed, Export ("defaultManager")] TKSmartCardSlotManager DefaultManager { get; } [Export ("slotNames")] - string[] SlotNames { get; } + string [] SlotNames { get; } [Export ("getSlotWithName:reply:")] [Async] void GetSlot (string name, TKGetSlotCallback reply); - [Mac (10,13)] + [Mac (10, 13)] [Export ("slotNamed:")] [return: NullAllowed] TKSmartCardSlot GetSlot (string name); @@ -568,9 +544,8 @@ interface TKSmartCardSlotManager [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKToken))] - interface TKSmartCardToken - { + [BaseType (typeof (TKToken))] + interface TKSmartCardToken { [Export ("initWithSmartCard:AID:instanceID:tokenDriver:")] [DesignatedInitializer] NativeHandle Constructor (TKSmartCard smartCard, [NullAllowed] NSData aid, string instanceId, TKSmartCardTokenDriver tokenDriver); @@ -584,17 +559,15 @@ interface TKSmartCardToken #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [BaseType (typeof (TKTokenDriver))] - interface TKSmartCardTokenDriver - { + interface TKSmartCardTokenDriver { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenSession))] - interface TKSmartCardTokenSession - { + [BaseType (typeof (TKTokenSession))] + interface TKSmartCardTokenSession { // Re-implemented from base class. [Export ("initWithToken:")] [DesignatedInitializer] @@ -608,9 +581,8 @@ interface TKSmartCardTokenSession [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] - interface TKSmartCardUserInteraction - { + [BaseType (typeof (NSObject))] + interface TKSmartCardUserInteraction { [Wrap ("WeakDelegate")] [NullAllowed] ITKSmartCardUserInteractionDelegate Delegate { get; set; } @@ -636,15 +608,14 @@ interface TKSmartCardUserInteraction [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(TKSmartCardUserInteraction), Name = "TKSmartCardUserInteractionForPINOperation")] - interface TKSmartCardUserInteractionForPinOperation - { + [BaseType (typeof (TKSmartCardUserInteraction), Name = "TKSmartCardUserInteractionForPINOperation")] + interface TKSmartCardUserInteractionForPinOperation { [Export ("PINCompletion", ArgumentSemantic.Assign)] TKSmartCardPinCompletion PinCompletion { get; set; } // not clear from the documentation if we can BindAs this to something or not [NullAllowed, Export ("PINMessageIndices", ArgumentSemantic.Assign)] - NSNumber[] PinMessageIndices { get; set; } + NSNumber [] PinMessageIndices { get; set; } [NullAllowed, Export ("locale", ArgumentSemantic.Assign)] NSLocale Locale { get; set; } @@ -660,9 +631,8 @@ interface TKSmartCardUserInteractionForPinOperation [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINChange")] - interface TKSmartCardUserInteractionForSecurePinChange - { + [BaseType (typeof (TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINChange")] + interface TKSmartCardUserInteractionForSecurePinChange { [Export ("PINConfirmation", ArgumentSemantic.Assign)] TKSmartCardPinConfirmation PinConfirmation { get; set; } } @@ -672,18 +642,16 @@ interface TKSmartCardUserInteractionForSecurePinChange #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [BaseType (typeof (TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINVerification")] - interface TKSmartCardUserInteractionForSecurePinVerification - { + interface TKSmartCardUserInteractionForSecurePinVerification { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject), Name = "TKTLVRecord")] + [BaseType (typeof (NSObject), Name = "TKTLVRecord")] [DisableDefaultCtor] - interface TKTlvRecord - { + interface TKTlvRecord { [Export ("tag")] ulong Tag { get; } @@ -701,17 +669,16 @@ interface TKTlvRecord [Static] [Export ("sequenceOfRecordsFromData:")] [return: NullAllowed] - TKTlvRecord[] CreateSequenceOfRecords (NSData data); + TKTlvRecord [] CreateSequenceOfRecords (NSData data); } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKToken - { + interface TKToken { [Export ("initWithTokenDriver:instanceID:")] [DesignatedInitializer] NativeHandle Constructor (TKTokenDriver tokenDriver, string instanceId); @@ -738,9 +705,8 @@ interface TKToken [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenAuthOperation : NSSecureCoding - { + [BaseType (typeof (NSObject))] + interface TKTokenAuthOperation : NSSecureCoding { [Export ("finishWithError:")] bool Finish ([NullAllowed] out NSError error); } @@ -749,10 +715,9 @@ interface TKTokenAuthOperation : NSSecureCoding [Experimental ("APL0001")] #endif [iOS (14, 0), Mac (10, 15), MacCatalyst (14, 0), TV (14, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenConfiguration - { + interface TKTokenConfiguration { [Export ("instanceID")] string InstanceId { get; } @@ -760,7 +725,7 @@ interface TKTokenConfiguration NSData ConfigurationData { get; set; } [Export ("keychainItems", ArgumentSemantic.Copy)] - TKTokenKeychainItem[] KeychainItems { get; set; } + TKTokenKeychainItem [] KeychainItems { get; set; } [Export ("keyForObjectID:error:")] [return: NullAllowed] @@ -775,9 +740,8 @@ interface TKTokenConfiguration [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenDriver - { + [BaseType (typeof (NSObject))] + interface TKTokenDriver { [Wrap ("WeakDelegate")] [NullAllowed] ITKTokenDriverDelegate Delegate { get; set; } @@ -790,10 +754,9 @@ interface TKTokenDriver [Experimental ("APL0001")] #endif [iOS (14, 0), Mac (10, 15), MacCatalyst (14, 0), TV (14, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenDriverConfiguration - { + interface TKTokenDriverConfiguration { [Static] [Export ("driverConfigurations")] NSDictionary DriverConfigurations { get; } @@ -815,10 +778,9 @@ interface TKTokenDriverConfiguration [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenKeyAlgorithm - { + interface TKTokenKeyAlgorithm { [Export ("isAlgorithm:")] bool IsAlgorithm ([BindAs (typeof (SecKeyAlgorithm))] NSString algorithm); @@ -830,9 +792,8 @@ interface TKTokenKeyAlgorithm [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenKeychainItem))] - interface TKTokenKeychainCertificate - { + [BaseType (typeof (TKTokenKeychainItem))] + interface TKTokenKeychainCertificate { [Export ("initWithCertificate:objectID:")] [DesignatedInitializer] NativeHandle Constructor ([BindAs (typeof (SecKeyAlgorithm))] NSString certificateRef, NSObject objectId); @@ -845,15 +806,14 @@ interface TKTokenKeychainCertificate [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenKeychainContents - { + interface TKTokenKeychainContents { [Export ("fillWithItems:")] - void Fill (TKTokenKeychainItem[] items); + void Fill (TKTokenKeychainItem [] items); [Export ("items", ArgumentSemantic.Copy)] - TKTokenKeychainItem[] Items { get; } + TKTokenKeychainItem [] Items { get; } [Export ("keyForObjectID:error:")] [return: NullAllowed] @@ -868,10 +828,9 @@ interface TKTokenKeychainContents [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenKeychainItem - { + interface TKTokenKeychainItem { [Export ("initWithObjectID:")] [DesignatedInitializer] NativeHandle Constructor (NSObject objectId); @@ -890,9 +849,8 @@ interface TKTokenKeychainItem [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenKeychainItem))] - interface TKTokenKeychainKey - { + [BaseType (typeof (TKTokenKeychainItem))] + interface TKTokenKeychainKey { [Export ("initWithCertificate:objectID:")] [DesignatedInitializer] NativeHandle Constructor (IntPtr certificate, NSObject objectId); @@ -932,9 +890,8 @@ interface TKTokenKeychainKey [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenKeyExchangeParameters - { + [BaseType (typeof (NSObject))] + interface TKTokenKeyExchangeParameters { [Export ("requestedSize")] nint RequestedSize { get; } @@ -946,9 +903,8 @@ interface TKTokenKeyExchangeParameters [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenAuthOperation))] - interface TKTokenPasswordAuthOperation - { + [BaseType (typeof (TKTokenAuthOperation))] + interface TKTokenPasswordAuthOperation { [NullAllowed, Export ("password")] string Password { get; set; } } @@ -957,9 +913,8 @@ interface TKTokenPasswordAuthOperation [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenAuthOperation), Name = "TKTokenSmartCardPINAuthOperation")] - interface TKTokenSmartCardPinAuthOperation - { + [BaseType (typeof (TKTokenAuthOperation), Name = "TKTokenSmartCardPINAuthOperation")] + interface TKTokenSmartCardPinAuthOperation { [Export ("PINFormat", ArgumentSemantic.Assign)] TKSmartCardPinFormat PinFormat { get; set; } @@ -980,11 +935,10 @@ interface TKTokenSmartCardPinAuthOperation [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenWatcher - { + [BaseType (typeof (NSObject))] + interface TKTokenWatcher { [Export ("tokenIDs")] - string[] TokenIds { get; } + string [] TokenIds { get; } // -(instancetype _Nonnull)initWithInsertionHandler:(void (^ _Nonnull)(NSString * _Nonnull))insertionHandler __attribute__((availability(macos, introduced=10.12, deprecated=10.13))) __attribute__((availability(ios, introduced=10.0, deprecated=11.0))); [Deprecated (PlatformName.MacOSX, 10, 13, "Use the default constructor followed by a call to the 'SetInsertionHandler' method.")] @@ -1011,10 +965,9 @@ interface TKTokenWatcher [Experimental ("APL0001")] #endif [iOS (15, 0), Mac (12, 0), MacCatalyst (15, 0), TV (15, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenWatcherTokenInfo - { + interface TKTokenWatcherTokenInfo { [Export ("tokenID")] string TokenId { get; } diff --git a/src/eventkit.cs b/src/eventkit.cs index 00c950adde57..1727818fcdbd 100644 --- a/src/eventkit.cs +++ b/src/eventkit.cs @@ -455,7 +455,7 @@ interface EKRecurrenceEnd : NSCopying, NSSecureCoding { interface EKRecurrenceDayOfWeek : NSCopying, NSSecureCoding { [Export ("dayOfTheWeek")] #if NET - EKWeekday DayOfTheWeek { get; } + EKWeekday DayOfTheWeek { get; } #else nint DayOfTheWeek { get; } #endif diff --git a/src/foundation.cs b/src/foundation.cs index 258609434527..b6077cd924b1 100644 --- a/src/foundation.cs +++ b/src/foundation.cs @@ -6015,7 +6015,9 @@ string SuggestedInvocationPhrase { #if HAS_APPCLIP // Inlined from NSUserActivity (AppClip) - [iOS (14,0)][NoTV][NoMac] + [iOS (14, 0)] + [NoTV] + [NoMac] [MacCatalyst (14, 0)] [Export ("appClipActivationPayload", ArgumentSemantic.Strong)] [NullAllowed] @@ -9466,7 +9468,7 @@ interface NSLinguisticAnalysis { [Wrap ("GetLinguisticTags (This, range, scheme.GetConstant ()!, options, orthography, out tokenRanges)")] #if NET - NSLinguisticTag[] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue[] tokenRanges); + NSLinguisticTag [] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue [] tokenRanges); #else NSLinguisticTagUnit [] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue [] tokenRanges); #endif @@ -9666,9 +9668,11 @@ interface NSObject2 : NSObjectProtocol { [Export ("exposedBindings")] NSString [] ExposedBindings (); #else - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] [Export ("exposedBindings")] - NSString[] ExposedBindings { get; } + NSString [] ExposedBindings { get; } #endif #if !NET @@ -14921,20 +14925,24 @@ interface NSFileProviderService { #if MONOMAC partial interface NSFilePresenter { - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] [NullAllowed] [Export ("primaryPresentedItemURL")] NSUrl PrimaryPresentedItemUrl { get; } } - [NoiOS][NoMacCatalyst][NoTV] - [Deprecated (PlatformName.MacOSX, 12, 0, message : "Use the Network.framework instead.")] + [NoiOS] + [NoMacCatalyst] + [NoTV] + [Deprecated (PlatformName.MacOSX, 12, 0, message: "Use the Network.framework instead.")] [BaseType (typeof (NSObject))] [DisableDefaultCtor] partial interface NSHost { [Static, Internal, Export ("currentHost")] - NSHost _Current { get;} + NSHost _Current { get; } [Static, Internal, Export ("hostWithName:")] NSHost _FromName ([NullAllowed] string name); @@ -14961,7 +14969,7 @@ partial interface NSHost { string _Address { get; } [Internal, Export ("addresses")] - string [] _Addresses { get; } + string [] _Addresses { get; } [Export ("hash"), Internal] nuint _Hash { get; } @@ -17659,7 +17667,8 @@ interface NSUrlSessionWebSocketTask { [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/gamekit.cs b/src/gamekit.cs index 8481c3ce6f1b..407a381b191f 100644 --- a/src/gamekit.cs +++ b/src/gamekit.cs @@ -58,10 +58,10 @@ namespace GameKit { delegate void GKEntriesForPlayersHandler (GKLeaderboardEntry localPlayerEntry, GKLeaderboardEntry [] entries, NSError error); #if MONOMAC - delegate void GKImageLoadedHandler (NSImage image, NSError error); + delegate void GKImageLoadedHandler (NSImage image, NSError error); delegate void GKPlayerPhotoLoaded (NSImage photo, NSError error); delegate void GKChallengeComposeHandler (NSViewController composeController, bool issuedChallenge, string [] sentPlayerIDs); - delegate void GKChallengeComposeHandler2 (NSViewController composeController, bool issuedChallenge, GKPlayer[] sentPlayers); + delegate void GKChallengeComposeHandler2 (NSViewController composeController, bool issuedChallenge, GKPlayer [] sentPlayers); #else delegate void GKImageLoadedHandler (UIImage image, NSError error); delegate void GKPlayerPhotoLoaded (UIImage photo, NSError error); @@ -765,8 +765,8 @@ interface GKLeaderboardViewControllerDelegate { [Deprecated (PlatformName.MacOSX, 10, 10, message: "Use 'GKGameCenterViewController' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'GKGameCenterViewController' instead.")] #if MONOMAC - [BaseType (typeof (GKGameCenterViewController), Events=new Type [] { typeof (GKLeaderboardViewControllerDelegate)}, Delegates=new string [] {"WeakDelegate"})] - interface GKLeaderboardViewController + [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKLeaderboardViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] + interface GKLeaderboardViewController #else [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKLeaderboardViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] interface GKLeaderboardViewController : UIAppearance @@ -1466,7 +1466,7 @@ interface GKMatchmaker { [MacCatalyst (13, 1)] #if MONOMAC - [BaseType (typeof (NSViewController), Delegates=new string [] { "WeakMatchmakerDelegate" }, Events=new Type [] {typeof(GKMatchmakerViewControllerDelegate)})] + [BaseType (typeof (NSViewController), Delegates = new string [] { "WeakMatchmakerDelegate" }, Events = new Type [] { typeof (GKMatchmakerViewControllerDelegate) })] #else [BaseType (typeof (UINavigationController), Delegates = new string [] { "WeakMatchmakerDelegate" }, Events = new Type [] { typeof (GKMatchmakerViewControllerDelegate) })] #endif @@ -1839,8 +1839,8 @@ interface GKAchievementViewControllerDelegate { [Deprecated (PlatformName.MacOSX, 10, 10, message: "Use 'GKGameCenterViewController' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'GKGameCenterViewController' instead.")] #if MONOMAC - [BaseType (typeof (GKGameCenterViewController), Events=new Type [] { typeof (GKAchievementViewControllerDelegate)}, Delegates=new string [] {"WeakDelegate"})] - interface GKAchievementViewController + [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKAchievementViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] + interface GKAchievementViewController #else [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKAchievementViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] interface GKAchievementViewController : UIAppearance @@ -1885,7 +1885,7 @@ interface GKDialogController { [NoTV] [Deprecated (PlatformName.MacCatalyst, 13, 1)] #if MONOMAC - [BaseType (typeof (NSViewController), Events=new Type [] { typeof (GKFriendRequestComposeViewControllerDelegate)}, Delegates=new string[] {"WeakComposeViewDelegate"})] + [BaseType (typeof (NSViewController), Events = new Type [] { typeof (GKFriendRequestComposeViewControllerDelegate) }, Delegates = new string [] { "WeakComposeViewDelegate" })] interface GKFriendRequestComposeViewController : GKViewController { [Export ("initWithNibName:bundle:")] [NoiOS] diff --git a/src/healthkit.cs b/src/healthkit.cs index a6acc3a0510a..52cc1a2262ec 100644 --- a/src/healthkit.cs +++ b/src/healthkit.cs @@ -220,7 +220,7 @@ public enum HKAudiogramSensitivityTestSide : long { #if NET /// The completion handler for . /// Completion handler for anchored object queries. - delegate void HKAnchoredObjectResultHandler (HKAnchoredObjectQuery query, HKSample[] results, nuint newAnchor, NSError error); + delegate void HKAnchoredObjectResultHandler (HKAnchoredObjectQuery query, HKSample [] results, nuint newAnchor, NSError error); #else delegate void HKAnchoredObjectResultHandler2 (HKAnchoredObjectQuery query, HKSample [] results, nuint newAnchor, NSError error); diff --git a/src/mapkit.cs b/src/mapkit.cs index 2a5bfe34006e..3a4245405bf5 100644 --- a/src/mapkit.cs +++ b/src/mapkit.cs @@ -28,11 +28,11 @@ using System; #if MONOMAC -using UIImage=AppKit.NSImage; -using UIView=AppKit.NSView; -using UIEdgeInsets=AppKit.NSEdgeInsets; -using UIColor=AppKit.NSColor; -using UIScene=AppKit.NSColor; +using UIImage = AppKit.NSImage; +using UIView = AppKit.NSView; +using UIEdgeInsets = AppKit.NSEdgeInsets; +using UIColor = AppKit.NSColor; +using UIScene = AppKit.NSColor; using UIControl = AppKit.NSControl; using UIBarButtonItem = Foundation.NSObject; using UIViewController = AppKit.NSViewController; diff --git a/src/mediaextension.cs b/src/mediaextension.cs index b7a7883c2c46..8706da954203 100644 --- a/src/mediaextension.cs +++ b/src/mediaextension.cs @@ -11,11 +11,10 @@ using UniformTypeIdentifiers; namespace MediaExtension { - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] [ErrorDomain ("MediaExtensionErrorDomain")] - public enum MEError : long - { + public enum MEError : long { UnsupportedFeature = -19320, AllocationFailure = -19321, InvalidParameter = -19322, @@ -30,37 +29,33 @@ public enum MEError : long ReferenceMissing = -19331, } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] - public enum MEFileInfoFragmentsStatus : long - { + public enum MEFileInfoFragmentsStatus : long { CouldNotContainFragments = 0, ContainsFragments = 1, CouldContainButDoesNotContainFragments = 2, } - [Flags, NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [Flags, NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] - public enum MEFormatReaderParseAdditionalFragmentsStatus : ulong - { + public enum MEFormatReaderParseAdditionalFragmentsStatus : ulong { SizeIncreased = 1uL << 0, FragmentAdded = 1uL << 1, FragmentsComplete = 1uL << 2, } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MEFormatReaderInstantiationOptions : NSCopying - { + interface MEFormatReaderInstantiationOptions : NSCopying { [Export ("allowIncrementalFragmentParsing")] bool AllowIncrementalFragmentParsing { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEFormatReaderExtension - { + interface MEFormatReaderExtension { [Abstract] [Export ("formatReaderWithByteSource:options:error:")] [return: NullAllowed] @@ -68,14 +63,13 @@ interface MEFormatReaderExtension } delegate void MEFormatReaderLoadFileInfoCallback ([NullAllowed] MEFileInfo fileInfo, [NullAllowed] NSError error); - delegate void MEFormatReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem[] metadata, [NullAllowed] NSError error); - delegate void MEFormatReaderLoadTrackReadersCallback ([NullAllowed] IMETrackReader[] trackReaders, [NullAllowed] NSError error); + delegate void MEFormatReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem [] metadata, [NullAllowed] NSError error); + delegate void MEFormatReaderLoadTrackReadersCallback ([NullAllowed] IMETrackReader [] trackReaders, [NullAllowed] NSError error); delegate void MEFormatReaderParseAdditionalFragmentsCallback ([NullAllowed] MEFormatReaderParseAdditionalFragmentsStatus fragmentStatus, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEFormatReader - { + interface MEFormatReader { [Abstract] [Export ("loadFileInfoWithCompletionHandler:")] void LoadFileInfo (MEFormatReaderLoadFileInfoCallback completionHandler); @@ -94,10 +88,9 @@ interface MEFormatReader interface IMEFormatReader { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] - interface MEFileInfo : NSCopying - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] + interface MEFileInfo : NSCopying { [Export ("duration", ArgumentSemantic.Assign)] CMTime Duration { get; set; } @@ -110,12 +103,11 @@ interface MEFileInfo : NSCopying delegate void METrackReaderLoadUneditedDurationCallback ([NullAllowed] CMTime uneditedDuration, [NullAllowed] NSError error); delegate void METrackReaderLoadTotalSampleDataLengthCallback (long totalSampleDataLength, [NullAllowed] NSError error); delegate void METrackReaderLoadEstimatedDataRateCallback (float estimatedDataRate, [NullAllowed] NSError error); - delegate void METrackReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem[] metadata, [NullAllowed] NSError error); + delegate void METrackReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem [] metadata, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface METrackReader - { + interface METrackReader { [Abstract] [Export ("loadTrackInfoWithCompletionHandler:")] void LoadTrackInfo (METrackReaderLoadTrackInfoCallback completionHandler); @@ -147,15 +139,14 @@ interface METrackReader interface IMETrackReader { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface METrackInfo : NSCopying - { + interface METrackInfo : NSCopying { [Export ("initWithMediaType:trackID:formatDescriptions:")] [DesignatedInitializer] // It's not clear from the documentation which type the format descriptors are, so keep as an array of NSObject for now. - NativeHandle Constructor (CMMediaType mediaType, int trackId, [Params] NSObject[] formatDescriptions); + NativeHandle Constructor (CMMediaType mediaType, int trackId, [Params] NSObject [] formatDescriptions); [Export ("mediaType")] CMMediaType MediaType { get; } @@ -169,7 +160,7 @@ interface METrackInfo : NSCopying // It's not clear from the documentation which type the format descriptors are, so keep as an array of NSObject for now. // However, name as 'Weak' to leave the good name open for when we know. [Export ("formatDescriptions", ArgumentSemantic.Copy)] - NSObject[] WeakFormatDescriptions { get; } + NSObject [] WeakFormatDescriptions { get; } // Inlined from the OptionalProperties (METrackInfo) category [Export ("naturalTimescale")] @@ -178,7 +169,7 @@ interface METrackInfo : NSCopying // Inlined from the OptionalProperties (METrackInfo) category [Export ("trackEdits", ArgumentSemantic.Copy), NullAllowed] [BindAs (typeof (CMTimeMapping []))] - NSValue[] TrackEdits { get; set; } + NSValue [] TrackEdits { get; set; } // Inlined from the LanguageTagOptionalProperties (METrackInfo) category [NullAllowed, Export ("extendedLanguageTag")] @@ -206,10 +197,9 @@ interface METrackInfo : NSCopying delegate void MESampleCursorLoadSampleBufferCallback ([NullAllowed] CMSampleBuffer newSampleBuffer, [NullAllowed] NSError error); delegate void MESampleCursorLoadPostDecodeProcessingMetadataCallback ([NullAllowed] NSDictionary postDecodeProcessingMetadata, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MESampleCursor : INSCopying - { + interface MESampleCursor : INSCopying { [Abstract] [Export ("presentationTimeStamp")] CMTime PresentationTimeStamp { get; } @@ -299,11 +289,10 @@ interface MESampleCursor : INSCopying interface IMESampleCursor { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MESampleCursorChunk : NSCopying - { + interface MESampleCursorChunk : NSCopying { [Export ("initWithByteSource:chunkStorageRange:chunkInfo:sampleIndexWithinChunk:")] [DesignatedInitializer] #if XAMCORE_5_0 @@ -338,11 +327,10 @@ interface MESampleCursorChunk : NSCopying nint SampleIndexWithinChunk { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MESampleLocation : NSCopying - { + interface MESampleLocation : NSCopying { [Export ("initWithByteSource:sampleLocation:")] [DesignatedInitializer] NativeHandle Constructor (MEByteSource byteSource, AVSampleCursorStorageRange sampleLocation); @@ -354,11 +342,10 @@ interface MESampleLocation : NSCopying MEByteSource ByteSource { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MEEstimatedSampleLocation : INSCopying - { + interface MEEstimatedSampleLocation : INSCopying { [Export ("initWithByteSource:estimatedSampleLocation:refinementDataLocation:")] [DesignatedInitializer] NativeHandle Constructor (MEByteSource byteSource, AVSampleCursorStorageRange estimatedSampleLocation, AVSampleCursorStorageRange refinementDataLocation); @@ -373,10 +360,9 @@ interface MEEstimatedSampleLocation : INSCopying MEByteSource ByteSource { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject), Name = "MEHEVCDependencyInfo")] - interface MEHevcDependencyInfo : INSCopying - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject), Name = "MEHEVCDependencyInfo")] + interface MEHevcDependencyInfo : INSCopying { [Export ("temporalSubLayerAccess")] bool TemporalSubLayerAccess { [Bind ("hasTemporalSubLayerAccess")] get; set; } @@ -418,11 +404,10 @@ interface MEHevcDependencyInfo : INSCopying delegate void MEByteSourceReadBytesCallback (nuint bytesRead, [NullAllowed] NSError error); delegate void MEByteSourceReadDataCallback ([NullAllowed] NSData data, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MEByteSource - { + interface MEByteSource { [Export ("fileName")] string FileName { get; } @@ -433,7 +418,7 @@ interface MEByteSource long FileLength { get; } [Export ("relatedFileNamesInSameDirectory")] - string[] RelatedFileNamesInSameDirectory { get; } + string [] RelatedFileNamesInSameDirectory { get; } [Export ("readDataOfLength:fromOffset:toDestination:completionHandler:")] unsafe void ReadData (nuint length, long offset, byte* dest, MEByteSourceReadBytesCallback completionHandler); @@ -455,18 +440,16 @@ interface MEByteSource [Flags] [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] - public enum MEDecodeFrameStatus : ulong - { + public enum MEDecodeFrameStatus : ulong { NoStatus = 0, FrameDropped = 1uL << 0, } delegate void MEVideoDecoderDecodeFrameCallback ([NullAllowed] CVImageBuffer imageBuffer, MEDecodeFrameStatus decodeStatus, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEVideoDecoder - { + interface MEVideoDecoder { [Export ("producesRAWOutput")] bool ProducesRawOutput { get; } @@ -484,7 +467,7 @@ interface MEVideoDecoder // of (and not call themselves), in which case the manual code would be // useless. Thus there's no strongly typed binding for this property. [Export ("supportedPixelFormatsOrderedByQuality")] - NSNumber[] SupportedPixelFormatsOrderedByQuality { get; } + NSNumber [] SupportedPixelFormatsOrderedByQuality { get; } [Export ("reducedResolution", ArgumentSemantic.Assign)] CGSize ReducedResolution { get; set; } @@ -494,7 +477,7 @@ interface MEVideoDecoder // of (and not call themselves), in which case the manual code would be // useless. Thus there's no strongly typed binding for this property. [Export ("pixelFormatsWithReducedResolutionDecodeSupport")] - NSNumber[] PixelFormatsWithReducedResolutionDecodeSupport { get; } + NSNumber [] PixelFormatsWithReducedResolutionDecodeSupport { get; } [Abstract] [Export ("readyForMoreMediaData")] @@ -508,9 +491,9 @@ interface MEVideoDecoder bool CanAcceptFormatDescription (CMFormatDescription formatDescription); } - interface IMEVideoDecoder {} + interface IMEVideoDecoder { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Static] interface MEVideoDecoderFields { [Notification] @@ -518,10 +501,9 @@ interface MEVideoDecoderFields { NSString ReadyForMoreMediaDataDidChangeNotification { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false, Name = "MERAWProcessorExtension")] - interface MERawProcessorExtension - { + interface MERawProcessorExtension { [Abstract] [Export ("init")] NativeHandle Constructor (); @@ -532,10 +514,9 @@ interface MERawProcessorExtension IMERawProcessor CreateProcessor (CMVideoFormatDescription formatDescription, MERawProcessorPixelBufferManager extensionPixelBufferManager, [NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject), Name = "MERAWProcessorPixelBufferManager")] - interface MERawProcessorPixelBufferManager - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject), Name = "MERAWProcessorPixelBufferManager")] + interface MERawProcessorPixelBufferManager { [Export ("pixelBufferAttributes", ArgumentSemantic.Copy)] NSDictionary PixelBufferAttributes { get; set; } @@ -544,10 +525,9 @@ interface MERawProcessorPixelBufferManager CVPixelBuffer CreatePixelBuffer ([NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject), Name = "MERAWProcessingParameter")] - interface MERawProcessingParameter - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject), Name = "MERAWProcessingParameter")] + interface MERawProcessingParameter { [Export ("name")] string Name { get; } @@ -561,10 +541,9 @@ interface MERawProcessingParameter bool Enabled { get; set; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingListElementParameter")] - interface MERawProcessingListElementParameter - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingListElementParameter")] + interface MERawProcessingListElementParameter { [Export ("initWithName:description:elementID:")] NativeHandle Constructor (string name, string description, nint elementId); @@ -572,11 +551,10 @@ interface MERawProcessingListElementParameter nint ListElementId { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingBooleanParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingBooleanParameter")] [DisableDefaultCtor] - interface MERawProcessingBooleanParameter - { + interface MERawProcessingBooleanParameter { [Export ("initWithName:key:description:initialValue:")] NativeHandle Constructor (string name, string key, string description, bool initialValue); @@ -605,11 +583,10 @@ interface MERawProcessingBooleanParameter bool HasCameraValue ([NullAllowed] out bool cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingIntegerParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingIntegerParameter")] [DisableDefaultCtor] - interface MERawProcessingIntegerParameter - { + interface MERawProcessingIntegerParameter { [Export ("initWithName:key:description:initialValue:maximum:minimum:")] NativeHandle Constructor (string name, string key, string description, nint initialValue, nint maximum, nint minimum); @@ -644,11 +621,10 @@ interface MERawProcessingIntegerParameter bool HasCameraValue ([NullAllowed] out nint cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingFloatParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingFloatParameter")] [DisableDefaultCtor] - interface MERawProcessingFloatParameter - { + interface MERawProcessingFloatParameter { [Export ("initWithName:key:description:initialValue:maximum:minimum:")] NativeHandle Constructor (string name, string key, string description, float initialValue, float maximum, float minimum); @@ -683,28 +659,27 @@ interface MERawProcessingFloatParameter bool HasCameraValue ([NullAllowed] out float cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingListParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingListParameter")] [DisableDefaultCtor] - interface MERawProcessingListParameter - { + interface MERawProcessingListParameter { [Export ("initWithName:key:description:list:initialValue:")] - NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue); + NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue); [Internal] [Export ("initWithName:key:description:list:initialValue:neutralValue:")] - NativeHandle _InitWithNeutralValue (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralValue); + NativeHandle _InitWithNeutralValue (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralValue); [Internal] [Export ("initWithName:key:description:list:initialValue:cameraValue:")] - NativeHandle _InitWithCameraValue (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint cameraValue); + NativeHandle _InitWithCameraValue (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint cameraValue); [Export ("initWithName:key:description:list:initialValue:neutralValue:cameraValue:")] [DesignatedInitializer] - NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralValue, nint cameraValue); + NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralValue, nint cameraValue); [Export ("listElements")] - MERawProcessingListElementParameter[] ListElements { get; } + MERawProcessingListElementParameter [] ListElements { get; } [Export ("initialValue")] nint InitialValue { get; } @@ -719,24 +694,22 @@ interface MERawProcessingListParameter bool HasCameraValue ([NullAllowed] out nint cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingSubGroupParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingSubGroupParameter")] [DisableDefaultCtor] - interface MERawProcessingSubGroupParameter - { + interface MERawProcessingSubGroupParameter { [Export ("initWithName:description:parameters:")] - NativeHandle Constructor (string name, string description, MERawProcessingParameter[] parameters); + NativeHandle Constructor (string name, string description, MERawProcessingParameter [] parameters); [Export ("subGroupParameters")] - MERawProcessingParameter[] SubGroupParameters { get; } + MERawProcessingParameter [] SubGroupParameters { get; } } delegate void MERawProcessorProcessFrameCallback ([NullAllowed] CVPixelBuffer pixelBuffer, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), MacCatalyst (18, 0)] + [NoTV, NoiOS, Mac (15, 0), MacCatalyst (18, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false, Name = "MERAWProcessor")] - interface MERawProcessor - { + interface MERawProcessor { [Export ("metalDeviceRegistryID")] ulong MetalDeviceRegistryId { get; set; } @@ -745,7 +718,7 @@ interface MERawProcessor [Abstract] [Export ("processingParameters")] - MERawProcessingParameter[] ProcessingParameters { get; } + MERawProcessingParameter [] ProcessingParameters { get; } [Abstract] [Export ("readyForMoreMediaData")] @@ -756,10 +729,9 @@ interface MERawProcessor void ProcessFrame (CVPixelBuffer inputFrame, MERawProcessorProcessFrameCallback completionHandler); } - [NoTV, NoiOS, Mac (15,0), MacCatalyst (18, 0)] + [NoTV, NoiOS, Mac (15, 0), MacCatalyst (18, 0)] [Static] - interface MERawProcessorFields - { + interface MERawProcessorFields { [Notification] [Field ("MERAWProcessorValuesDidChangeNotification")] NSString ValuesDidChangeNotification { get; } @@ -769,12 +741,11 @@ interface MERawProcessorFields NSString ReadyForMoreMediaDataDidChangeNotification { get; } } - interface IMERawProcessor {} + interface IMERawProcessor { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEVideoDecoderExtension - { + interface MEVideoDecoderExtension { [Abstract] [Export ("init")] NativeHandle Constructor (); @@ -785,10 +756,9 @@ interface MEVideoDecoderExtension IMEVideoDecoder CreateVideoDecoder (CMVideoCodecType codecType, CMVideoFormatDescription videoFormatDescription, NSDictionary videoDecoderSpecifications, MEVideoDecoderPixelBufferManager extensionDecoderPixelBufferManager, [NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] - interface MEVideoDecoderPixelBufferManager - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] + interface MEVideoDecoderPixelBufferManager { [Export ("pixelBufferAttributes", ArgumentSemantic.Copy)] NSDictionary PixelBufferAttributes { get; set; } @@ -801,9 +771,8 @@ interface MEVideoDecoderPixelBufferManager } [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof(NSObject))] - interface MEDecodeFrameOptions - { + [BaseType (typeof (NSObject))] + interface MEDecodeFrameOptions { [Export ("doNotOutputFrame")] bool DoNotOutputFrame { get; set; } diff --git a/src/mediaplayer.cs b/src/mediaplayer.cs index 8826acbb7651..602bc96109ae 100644 --- a/src/mediaplayer.cs +++ b/src/mediaplayer.cs @@ -371,7 +371,7 @@ interface MPMediaLibrary : NSSecureCoding { [Export ("addItemWithProductID:completionHandler:")] [Async] #if IOS - void AddItem (string productID, [NullAllowed] Action completionHandler); + void AddItem (string productID, [NullAllowed] Action completionHandler); #else void AddItem (string productID, [NullAllowed] Action completionHandler); #endif @@ -824,7 +824,7 @@ interface MPMoviePlayerTimedMetadataEventArgs { [NoMac] #if NET - [TV (16,0)] + [TV (16, 0)] [MacCatalyst (13, 1)] #else [Obsoleted (PlatformName.TvOS, 14, 0, message: "Removed in Xcode 12.")] @@ -1250,7 +1250,7 @@ interface MPTimedMetadata { [Export ("value")] #if NET - NSObject Value { get; } + NSObject Value { get; } #else NSObject value { get; } #endif diff --git a/src/metal.cs b/src/metal.cs index 34e4abd28161..74be7fab19d8 100644 --- a/src/metal.cs +++ b/src/metal.cs @@ -1584,7 +1584,7 @@ partial interface MTLDevice { [MacCatalyst (14, 0)] [NullAllowed, Export ("counterSets")] #if NET - IMTLCounterSet[] CounterSets { get; } + IMTLCounterSet [] CounterSets { get; } #else [Obsolete ("Use 'GetIMTLCounterSets' instead.")] MTLCounterSet [] CounterSets { get; } diff --git a/src/metrickit.cs b/src/metrickit.cs index 2c75b672a4c2..f1ecfa2488c8 100644 --- a/src/metrickit.cs +++ b/src/metrickit.cs @@ -163,7 +163,7 @@ interface MXMetaData : NSSecureCoding { [MacCatalyst (14, 0)] [Export ("dictionaryRepresentation")] #if MONOMAC - NSDictionary DictionaryRepresentation { get; } + NSDictionary DictionaryRepresentation { get; } #else [Internal] NSDictionary _DictionaryRepresentation14 { get; } diff --git a/src/networkextension.cs b/src/networkextension.cs index 698c2462256d..4bf350d5a2e6 100644 --- a/src/networkextension.cs +++ b/src/networkextension.cs @@ -1322,9 +1322,9 @@ interface NETunnelProviderManager { // CopyAppRules was incorrectly bound to AppRules and it is only available on macOS #if NET || MONOMAC || __MACCATALYST__ - [NoTV, NoiOS, MacCatalyst (15,0)] + [NoTV, NoiOS, MacCatalyst (15, 0)] [Export ("appRules", ArgumentSemantic.Copy)] - NEAppRule[] AppRules { get; set; } + NEAppRule [] AppRules { get; set; } #else [NoTV] [Obsolete ("Use 'CopyAppRules' instead, this property will be removed in the future.")] diff --git a/src/quicklook.cs b/src/quicklook.cs index 7b841c61b331..4d5a08c3abde 100644 --- a/src/quicklook.cs +++ b/src/quicklook.cs @@ -33,7 +33,7 @@ using CoreGraphics; #if MONOMAC using AppKit; -using UIWindowSceneActivationConfiguration=Foundation.NSObject; +using UIWindowSceneActivationConfiguration = Foundation.NSObject; #else using UIKit; #endif @@ -315,7 +315,9 @@ interface QLPreviewingController { } #else [Static] - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] interface QLThumbnailImage { [Internal, Field ("kQLThumbnailOptionScaleFactorKey")] NSString OptionScaleFactorKey { get; } diff --git a/src/scenekit.cs b/src/scenekit.cs index dc58ba55938a..ed14e0b6e0a4 100644 --- a/src/scenekit.cs +++ b/src/scenekit.cs @@ -4063,7 +4063,7 @@ interface SCNAction : NSCopying, NSSecureCoding { [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] #if NET - Func TimingFunction { get; set; } + Func TimingFunction { get; set; } #else Func TimingFunction2 { get; set; } #endif diff --git a/src/sharedwithyou.cs b/src/sharedwithyou.cs index 47b631dc0ee3..0d92484412c3 100644 --- a/src/sharedwithyou.cs +++ b/src/sharedwithyou.cs @@ -19,12 +19,12 @@ #if MONOMAC using AppKit; -using UIViewController=AppKit.NSViewController; -using UIView=AppKit.NSView; -using UIMenu=AppKit.NSMenu; -using UIImage=AppKit.NSImage; -using ICloudSharingControllerDelegate=AppKit.INSCloudSharingServiceDelegate; -using UIWindow=AppKit.NSWindow; +using UIViewController = AppKit.NSViewController; +using UIView = AppKit.NSView; +using UIMenu = AppKit.NSMenu; +using UIImage = AppKit.NSImage; +using ICloudSharingControllerDelegate = AppKit.INSCloudSharingServiceDelegate; +using UIWindow = AppKit.NSWindow; #else using UIKit; using ICloudSharingControllerDelegate = UIKit.IUICloudSharingControllerDelegate; diff --git a/src/soundanalysis.cs b/src/soundanalysis.cs index 997463167641..2b723ba87212 100644 --- a/src/soundanalysis.cs +++ b/src/soundanalysis.cs @@ -210,7 +210,7 @@ interface SNTimeDurationConstraint /* privately conforms to NSCoding, NSCopying, SNTimeDurationConstraintType Type { get; } #if NET - [BindAs (typeof (CMTime[]))] + [BindAs (typeof (CMTime []))] #endif [Export ("enumeratedDurations", ArgumentSemantic.Strong)] NSValue [] EnumeratedDurations { get; } diff --git a/src/spritekit.cs b/src/spritekit.cs index f832ac4342d9..aa35388789f3 100644 --- a/src/spritekit.cs +++ b/src/spritekit.cs @@ -140,205 +140,205 @@ partial interface SKNode : NSSecureCoding, NSCopying, UIFocusItem, UIFocusItemCo #else #error Unknown platform #endif - [DesignatedInitializer] - [Export ("init")] - NativeHandle Constructor (); - - [Static, Export ("node")] - SKNode Create (); - - [MacCatalyst (13, 1)] - [Static] - [Export ("nodeWithFileNamed:")] - [return: NullAllowed] - SKNode Create (string filename); - - [MacCatalyst (13, 1)] - [Internal] - [Static] - [Export ("nodeWithFileNamed:securelyWithClasses:andError:")] - [return: NullAllowed] - SKNode Create (string filename, IntPtr classesPtr, out NSError error); - - [Export ("frame")] + [DesignatedInitializer] + [Export ("init")] + NativeHandle Constructor (); + + [Static, Export ("node")] + SKNode Create (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("nodeWithFileNamed:")] + [return: NullAllowed] + SKNode Create (string filename); + + [MacCatalyst (13, 1)] + [Internal] + [Static] + [Export ("nodeWithFileNamed:securelyWithClasses:andError:")] + [return: NullAllowed] + SKNode Create (string filename, IntPtr classesPtr, out NSError error); + + [Export ("frame")] #if !MONOMAC - // For iOS+tvOS we also get this property from the UIFocusItem protocol, but we redefine it here to get the right availability attributes. - new + // For iOS+tvOS we also get this property from the UIFocusItem protocol, but we redefine it here to get the right availability attributes. + new #endif - CGRect Frame { get; } - - [Export ("calculateAccumulatedFrame")] - CGRect CalculateAccumulatedFrame (); - - [Export ("position")] - CGPoint Position { get; set; } - - [Export ("zPosition")] - nfloat ZPosition { get; set; } - - [Export ("zRotation")] - nfloat ZRotation { get; set; } + CGRect Frame { get; } - [Export ("xScale")] - nfloat XScale { get; set; } + [Export ("calculateAccumulatedFrame")] + CGRect CalculateAccumulatedFrame (); - [Export ("yScale")] - nfloat YScale { get; set; } + [Export ("position")] + CGPoint Position { get; set; } - [Export ("speed")] - nfloat Speed { get; set; } + [Export ("zPosition")] + nfloat ZPosition { get; set; } - [Export ("alpha")] - nfloat Alpha { get; set; } + [Export ("zRotation")] + nfloat ZRotation { get; set; } - [Export ("paused")] - bool Paused { [Bind ("isPaused")] get; set; } + [Export ("xScale")] + nfloat XScale { get; set; } - [Export ("hidden")] - bool Hidden { [Bind ("isHidden")] get; set; } + [Export ("yScale")] + nfloat YScale { get; set; } - [Export ("userInteractionEnabled")] - bool UserInteractionEnabled { [Bind ("isUserInteractionEnabled")] get; set; } + [Export ("speed")] + nfloat Speed { get; set; } - [NoMac] - [MacCatalyst (13, 1)] - [Export ("focusBehavior", ArgumentSemantic.Assign)] - SKNodeFocusBehavior FocusBehavior { get; set; } + [Export ("alpha")] + nfloat Alpha { get; set; } - [Export ("parent")] - [NullAllowed] - SKNode Parent { get; } + [Export ("paused")] + bool Paused { [Bind ("isPaused")] get; set; } - [Export ("children")] - SKNode [] Children { get; } + [Export ("hidden")] + bool Hidden { [Bind ("isHidden")] get; set; } - [NullAllowed] // by default this property is null - [Export ("name", ArgumentSemantic.Copy)] - string Name { get; set; } + [Export ("userInteractionEnabled")] + bool UserInteractionEnabled { [Bind ("isUserInteractionEnabled")] get; set; } - [Export ("scene")] - [NullAllowed] - SKScene Scene { get; } + [NoMac] + [MacCatalyst (13, 1)] + [Export ("focusBehavior", ArgumentSemantic.Assign)] + SKNodeFocusBehavior FocusBehavior { get; set; } - [Export ("physicsBody", ArgumentSemantic.Retain), NullAllowed] - SKPhysicsBody PhysicsBody { get; set; } + [Export ("parent")] + [NullAllowed] + SKNode Parent { get; } - [NullAllowed] // by default this property is null - [Export ("userData", ArgumentSemantic.Retain)] - NSMutableDictionary UserData { get; set; } + [Export ("children")] + SKNode [] Children { get; } - [Export ("setScale:")] - void SetScale (nfloat scale); - - [Export ("addChild:")] - [PostGet ("Children")] - void AddChild (SKNode node); + [NullAllowed] // by default this property is null + [Export ("name", ArgumentSemantic.Copy)] + string Name { get; set; } - [Export ("insertChild:atIndex:")] - [PostGet ("Children")] - void InsertChild (SKNode node, nint index); + [Export ("scene")] + [NullAllowed] + SKScene Scene { get; } - [Export ("removeChildrenInArray:")] - [PostGet ("Children")] - void RemoveChildren (SKNode [] nodes); + [Export ("physicsBody", ArgumentSemantic.Retain), NullAllowed] + SKPhysicsBody PhysicsBody { get; set; } - [Export ("removeAllChildren")] - [PostGet ("Children")] - void RemoveAllChildren (); + [NullAllowed] // by default this property is null + [Export ("userData", ArgumentSemantic.Retain)] + NSMutableDictionary UserData { get; set; } - [Export ("removeFromParent")] - void RemoveFromParent (); + [Export ("setScale:")] + void SetScale (nfloat scale); - [Export ("childNodeWithName:")] - [return: NullAllowed] - SKNode GetChildNode (string name); + [Export ("addChild:")] + [PostGet ("Children")] + void AddChild (SKNode node); - [Export ("enumerateChildNodesWithName:usingBlock:")] - void EnumerateChildNodes (string name, SKNodeChildEnumeratorHandler enumerationHandler); + [Export ("insertChild:atIndex:")] + [PostGet ("Children")] + void InsertChild (SKNode node, nint index); - [Export ("runAction:")] - void RunAction (SKAction action); + [Export ("removeChildrenInArray:")] + [PostGet ("Children")] + void RemoveChildren (SKNode [] nodes); - [Async] - [Export ("runAction:completion:")] - void RunAction (SKAction action, Action completionHandler); + [Export ("removeAllChildren")] + [PostGet ("Children")] + void RemoveAllChildren (); - [Export ("runAction:withKey:")] - void RunAction (SKAction action, string key); + [Export ("removeFromParent")] + void RemoveFromParent (); - [Export ("hasActions")] - bool HasActions { get; } + [Export ("childNodeWithName:")] + [return: NullAllowed] + SKNode GetChildNode (string name); - [Export ("actionForKey:")] - [return: NullAllowed] - SKAction GetActionForKey (string key); + [Export ("enumerateChildNodesWithName:usingBlock:")] + void EnumerateChildNodes (string name, SKNodeChildEnumeratorHandler enumerationHandler); - [Export ("removeActionForKey:")] - void RemoveActionForKey (string key); + [Export ("runAction:")] + void RunAction (SKAction action); - [Export ("removeAllActions")] - void RemoveAllActions (); + [Async] + [Export ("runAction:completion:")] + void RunAction (SKAction action, Action completionHandler); - [Export ("containsPoint:")] - bool ContainsPoint (CGPoint point); + [Export ("runAction:withKey:")] + void RunAction (SKAction action, string key); - [Export ("nodeAtPoint:")] - SKNode GetNodeAtPoint (CGPoint point); + [Export ("hasActions")] + bool HasActions { get; } - [Export ("nodesAtPoint:")] - SKNode [] GetNodesAtPoint (CGPoint point); + [Export ("actionForKey:")] + [return: NullAllowed] + SKAction GetActionForKey (string key); - [Export ("convertPoint:fromNode:")] - CGPoint ConvertPointFromNode (CGPoint point, SKNode sourceNode); + [Export ("removeActionForKey:")] + void RemoveActionForKey (string key); - [Export ("convertPoint:toNode:")] - CGPoint ConvertPointToNode (CGPoint point, SKNode sourceNode); + [Export ("removeAllActions")] + void RemoveAllActions (); - [Export ("intersectsNode:")] - bool IntersectsNode (SKNode node); + [Export ("containsPoint:")] + bool ContainsPoint (CGPoint point); - [MacCatalyst (13, 1)] - [Export ("isEqualToNode:")] - bool IsEqual (SKNode node); + [Export ("nodeAtPoint:")] + SKNode GetNodeAtPoint (CGPoint point); - [Export ("inParentHierarchy:")] - bool InParentHierarchy (SKNode node); + [Export ("nodesAtPoint:")] + SKNode [] GetNodesAtPoint (CGPoint point); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("reachConstraints", ArgumentSemantic.Copy)] - SKReachConstraints ReachConstraints { get; set; } + [Export ("convertPoint:fromNode:")] + CGPoint ConvertPointFromNode (CGPoint point, SKNode sourceNode); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("constraints", ArgumentSemantic.Copy)] - SKConstraint [] Constraints { get; set; } + [Export ("convertPoint:toNode:")] + CGPoint ConvertPointToNode (CGPoint point, SKNode sourceNode); - [MacCatalyst (13, 1)] - [Export ("objectForKeyedSubscript:")] - SKNode GetObjectsMatching (string nameExpression); + [Export ("intersectsNode:")] + bool IntersectsNode (SKNode node); - [MacCatalyst (13, 1)] - [Export ("moveToParent:")] - void MoveToParent (SKNode parent); + [MacCatalyst (13, 1)] + [Export ("isEqualToNode:")] + bool IsEqual (SKNode node); - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodeBounds:")] - GKPolygonObstacle [] ObstaclesFromNodeBounds (SKNode [] nodes); + [Export ("inParentHierarchy:")] + bool InParentHierarchy (SKNode node); - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodePhysicsBodies:")] - GKPolygonObstacle [] ObstaclesFromNodePhysicsBodies (SKNode [] nodes); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("reachConstraints", ArgumentSemantic.Copy)] + SKReachConstraints ReachConstraints { get; set; } - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromSpriteTextures:accuracy:")] - GKPolygonObstacle [] ObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("constraints", ArgumentSemantic.Copy)] + SKConstraint [] Constraints { get; set; } + + [MacCatalyst (13, 1)] + [Export ("objectForKeyedSubscript:")] + SKNode GetObjectsMatching (string nameExpression); + + [MacCatalyst (13, 1)] + [Export ("moveToParent:")] + void MoveToParent (SKNode parent); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodeBounds:")] + GKPolygonObstacle [] ObstaclesFromNodeBounds (SKNode [] nodes); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodePhysicsBodies:")] + GKPolygonObstacle [] ObstaclesFromNodePhysicsBodies (SKNode [] nodes); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromSpriteTextures:accuracy:")] + GKPolygonObstacle [] ObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); #if !NET [Deprecated (PlatformName.iOS, 10, 0, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] @@ -358,1496 +358,1496 @@ partial interface SKNode : NSSecureCoding, NSCopying, UIFocusItem, UIFocusItemCo void SetValue (SKAttributeValue value, string key); #endif - // Extensions from GameplayKit, inlined to avoid ugly static extension syntax - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromSpriteTextures:accuracy:")] - GKPolygonObstacle [] GetObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); + // Extensions from GameplayKit, inlined to avoid ugly static extension syntax + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromSpriteTextures:accuracy:")] + GKPolygonObstacle [] GetObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); + + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodeBounds:")] + GKPolygonObstacle [] GetObstaclesFromNodeBounds (SKNode [] nodes); + + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodePhysicsBodies:")] + GKPolygonObstacle [] GetObstaclesFromNodePhysicsBodies (SKNode [] nodes); + } - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodeBounds:")] - GKPolygonObstacle [] GetObstaclesFromNodeBounds (SKNode [] nodes); + [NoiOS] + [NoTV] + [NoMacCatalyst] + [Category, BaseType (typeof (NSEvent))] + partial interface SKNodeEvent_NSEvent { + + [Export ("locationInNode:")] + CGPoint LocationInNode (SKNode node); + } + /// Extension methods for that aide with conversion to Sprite Kit coordinates. + [NoMac] [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodePhysicsBodies:")] - GKPolygonObstacle [] GetObstaclesFromNodePhysicsBodies (SKNode [] nodes); -} + [Category, BaseType (typeof (UITouch))] + partial interface SKNodeTouches_UITouch { -[NoiOS] -[NoTV] -[NoMacCatalyst] -[Category, BaseType (typeof (NSEvent))] -partial interface SKNodeEvent_NSEvent { + [Export ("locationInNode:")] + CGPoint LocationInNode (SKNode node); - [Export ("locationInNode:")] - CGPoint LocationInNode (SKNode node); -} + [Export ("previousLocationInNode:")] + CGPoint PreviousLocationInNode (SKNode node); + } -/// Extension methods for that aide with conversion to Sprite Kit coordinates. -[NoMac] -[MacCatalyst (13, 1)] -[Category, BaseType (typeof (UITouch))] -partial interface SKNodeTouches_UITouch { + /// An that applies a Core Graphics to its output. + /// + /// Application developers should ensure that is . + /// Note that is a subclass of . + /// + /// Apple documentation for SKEffectNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + partial interface SKEffectNode : SKWarpable { - [Export ("locationInNode:")] - CGPoint LocationInNode (SKNode node); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("filter", ArgumentSemantic.Retain)] + CIFilter Filter { get; set; } - [Export ("previousLocationInNode:")] - CGPoint PreviousLocationInNode (SKNode node); -} + [Export ("shouldCenterFilter")] + bool ShouldCenterFilter { get; set; } -/// An that applies a Core Graphics to its output. -/// -/// Application developers should ensure that is . -/// Note that is a subclass of . -/// -/// Apple documentation for SKEffectNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKEffectNode : SKWarpable { + [Export ("shouldEnableEffects")] + bool ShouldEnableEffects { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("filter", ArgumentSemantic.Retain)] - CIFilter Filter { get; set; } + [Export ("shouldRasterize")] + bool ShouldRasterize { get; set; } - [Export ("shouldCenterFilter")] - bool ShouldCenterFilter { get; set; } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [Export ("shouldEnableEffects")] - bool ShouldEnableEffects { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - [Export ("shouldRasterize")] - bool ShouldRasterize { get; set; } + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + /// A method that derives a force by applying the physics of a field to a body that is within the field. + delegate Vector3 SKFieldForceEvaluator (/* vector_float3 */ Vector4 position, /* vector_float3 */ Vector4 velocity, float /* float, not CGFloat */ mass, float /* float, not CGFloat */ charge, double time); + /// Applies physics effects within a portion of a scene. + /// + /// Apple documentation for SKFieldNode [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [BaseType (typeof (SKNode))] + interface SKFieldNode { + [Export ("region", ArgumentSemantic.Retain)] + [NullAllowed] + SKRegion Region { get; set; } - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} + [Export ("strength")] + float Strength { get; set; } /* float, not CGFloat */ -/// A method that derives a force by applying the physics of a field to a body that is within the field. -delegate Vector3 SKFieldForceEvaluator (/* vector_float3 */ Vector4 position, /* vector_float3 */ Vector4 velocity, float /* float, not CGFloat */ mass, float /* float, not CGFloat */ charge, double time); + [Export ("falloff")] + float Falloff { get; set; } /* float, not CGFloat */ -/// Applies physics effects within a portion of a scene. -/// -/// Apple documentation for SKFieldNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKFieldNode { - [Export ("region", ArgumentSemantic.Retain)] - [NullAllowed] - SKRegion Region { get; set; } + [Export ("minimumRadius")] - [Export ("strength")] - float Strength { get; set; } /* float, not CGFloat */ + float MinimumRadius { get; set; } /* float, not CGFloat */ - [Export ("falloff")] - float Falloff { get; set; } /* float, not CGFloat */ + [Export ("enabled")] + bool Enabled { [Bind ("isEnabled")] get; set; } - [Export ("minimumRadius")] + [Export ("exclusive")] + bool Exclusive { [Bind ("isExclusive")] get; set; } - float MinimumRadius { get; set; } /* float, not CGFloat */ + [Export ("categoryBitMask")] + uint CategoryBitMask { get; set; } /* uint32_t */ - [Export ("enabled")] - bool Enabled { [Bind ("isEnabled")] get; set; } + [Export ("direction")] + /* This was typed as Vector4 since sizeof the native type (vector_float3) = 16 */ + Vector4 Direction { + [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] + set; + } - [Export ("exclusive")] - bool Exclusive { [Bind ("isExclusive")] get; set; } + [Export ("smoothness")] + float Smoothness { get; set; } /* float, not CGFloat */ - [Export ("categoryBitMask")] - uint CategoryBitMask { get; set; } /* uint32_t */ + [Export ("animationSpeed")] + float AnimationSpeed { get; set; } /* float, not CGFloat */ - [Export ("direction")] - /* This was typed as Vector4 since sizeof the native type (vector_float3) = 16 */ - Vector4 Direction { - [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] - set; - } + [Export ("texture", ArgumentSemantic.Retain)] + [NullAllowed] + SKTexture Texture { get; set; } - [Export ("smoothness")] - float Smoothness { get; set; } /* float, not CGFloat */ + [Static, Export ("dragField")] + SKFieldNode CreateDragField (); - [Export ("animationSpeed")] - float AnimationSpeed { get; set; } /* float, not CGFloat */ + [Static, Export ("vortexField")] + SKFieldNode CreateVortexField (); - [Export ("texture", ArgumentSemantic.Retain)] - [NullAllowed] - SKTexture Texture { get; set; } + [Static, Export ("radialGravityField")] + SKFieldNode CreateRadialGravityField (); - [Static, Export ("dragField")] - SKFieldNode CreateDragField (); + [Static, Export ("linearGravityFieldWithVector:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKFieldNode CreateLinearGravityField (/* vector_float3 */ Vector4 direction); - [Static, Export ("vortexField")] - SKFieldNode CreateVortexField (); + [Static, Export ("velocityFieldWithVector:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKFieldNode CreateVelocityField (/* vector_float3 */ Vector4 direction); - [Static, Export ("radialGravityField")] - SKFieldNode CreateRadialGravityField (); + [Static, Export ("velocityFieldWithTexture:")] + SKFieldNode CreateVelocityField (SKTexture velocityTexture); - [Static, Export ("linearGravityFieldWithVector:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKFieldNode CreateLinearGravityField (/* vector_float3 */ Vector4 direction); + [Static, Export ("noiseFieldWithSmoothness:animationSpeed:")] + SKFieldNode CreateNoiseField (nfloat smoothness, nfloat speed); - [Static, Export ("velocityFieldWithVector:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKFieldNode CreateVelocityField (/* vector_float3 */ Vector4 direction); + [Static, Export ("turbulenceFieldWithSmoothness:animationSpeed:")] + SKFieldNode CreateTurbulenceField (nfloat smoothness, nfloat speed); - [Static, Export ("velocityFieldWithTexture:")] - SKFieldNode CreateVelocityField (SKTexture velocityTexture); + [Static, Export ("springField")] + SKFieldNode CreateSpringField (); - [Static, Export ("noiseFieldWithSmoothness:animationSpeed:")] - SKFieldNode CreateNoiseField (nfloat smoothness, nfloat speed); + [Static, Export ("electricField")] + SKFieldNode CreateElectricField (); - [Static, Export ("turbulenceFieldWithSmoothness:animationSpeed:")] - SKFieldNode CreateTurbulenceField (nfloat smoothness, nfloat speed); + [Static, Export ("magneticField")] + SKFieldNode CreateMagneticField (); - [Static, Export ("springField")] - SKFieldNode CreateSpringField (); + [Static, Export ("customFieldWithEvaluationBlock:")] + SKFieldNode CreateCustomField (SKFieldForceEvaluator evaluator); + } - [Static, Export ("electricField")] - SKFieldNode CreateElectricField (); + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (SKEffectNode))] + interface SKScene + : GKSceneRootNodeType { + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [Static, Export ("magneticField")] - SKFieldNode CreateMagneticField (); + [Static, Export ("sceneWithSize:")] + SKScene FromSize (CGSize size); - [Static, Export ("customFieldWithEvaluationBlock:")] - SKFieldNode CreateCustomField (SKFieldForceEvaluator evaluator); -} + [MacCatalyst (13, 1)] + [Export ("sceneDidLoad")] + void SceneDidLoad (); -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (SKEffectNode))] -interface SKScene - : GKSceneRootNodeType { - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [Export ("size")] + CGSize Size { get; set; } - [Static, Export ("sceneWithSize:")] - SKScene FromSize (CGSize size); + [Export ("scaleMode")] + SKSceneScaleMode ScaleMode { get; set; } - [MacCatalyst (13, 1)] - [Export ("sceneDidLoad")] - void SceneDidLoad (); + [Export ("backgroundColor", ArgumentSemantic.Retain)] + UIColor BackgroundColor { get; set; } - [Export ("size")] - CGSize Size { get; set; } + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } - [Export ("scaleMode")] - SKSceneScaleMode ScaleMode { get; set; } + [Export ("physicsWorld")] + SKPhysicsWorld PhysicsWorld { get; } - [Export ("backgroundColor", ArgumentSemantic.Retain)] - UIColor BackgroundColor { get; set; } + [MacCatalyst (13, 1)] + [Export ("convertPointFromView:")] + CGPoint ConvertPointFromView (CGPoint point); - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } + [MacCatalyst (13, 1)] + [Export ("convertPointToView:")] + CGPoint ConvertPointToView (CGPoint point); - [Export ("physicsWorld")] - SKPhysicsWorld PhysicsWorld { get; } + [MacCatalyst (13, 1)] + [Export ("view", ArgumentSemantic.Weak)] + [NullAllowed] + SKView View { get; } - [MacCatalyst (13, 1)] - [Export ("convertPointFromView:")] - CGPoint ConvertPointFromView (CGPoint point); + [Export ("update:")] + void Update (double currentTime); - [MacCatalyst (13, 1)] - [Export ("convertPointToView:")] - CGPoint ConvertPointToView (CGPoint point); + [Export ("didEvaluateActions")] + void DidEvaluateActions (); - [MacCatalyst (13, 1)] - [Export ("view", ArgumentSemantic.Weak)] - [NullAllowed] - SKView View { get; } + [Export ("didSimulatePhysics")] + void DidSimulatePhysics (); - [Export ("update:")] - void Update (double currentTime); + [MacCatalyst (13, 1)] + [Export ("didMoveToView:")] + void DidMoveToView (SKView view); - [Export ("didEvaluateActions")] - void DidEvaluateActions (); + [MacCatalyst (13, 1)] + [Export ("willMoveFromView:")] + void WillMoveFromView (SKView view); - [Export ("didSimulatePhysics")] - void DidSimulatePhysics (); + [Export ("didChangeSize:")] + void DidChangeSize (CGSize oldSize); - [MacCatalyst (13, 1)] - [Export ("didMoveToView:")] - void DidMoveToView (SKView view); + [MacCatalyst (13, 1)] + [Export ("didApplyConstraints")] + void DidApplyConstraints (); - [MacCatalyst (13, 1)] - [Export ("willMoveFromView:")] - void WillMoveFromView (SKView view); + [MacCatalyst (13, 1)] + [Export ("didFinishUpdate")] + void DidFinishUpdate (); - [Export ("didChangeSize:")] - void DidChangeSize (CGSize oldSize); + [MacCatalyst (13, 1)] + [Export ("delegate", ArgumentSemantic.Weak), NullAllowed] + NSObject WeakDelegate { get; set; } - [MacCatalyst (13, 1)] - [Export ("didApplyConstraints")] - void DidApplyConstraints (); + [MacCatalyst (13, 1)] + [Wrap ("WeakDelegate")] + ISKSceneDelegate Delegate { get; set; } - [MacCatalyst (13, 1)] - [Export ("didFinishUpdate")] - void DidFinishUpdate (); + [MacCatalyst (13, 1)] + [Export ("audioEngine", ArgumentSemantic.Retain)] + AVAudioEngine AudioEngine { get; } - [MacCatalyst (13, 1)] - [Export ("delegate", ArgumentSemantic.Weak), NullAllowed] - NSObject WeakDelegate { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed, Export ("camera", ArgumentSemantic.Weak)] + SKCameraNode Camera { get; set; } - [MacCatalyst (13, 1)] - [Wrap ("WeakDelegate")] - ISKSceneDelegate Delegate { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed, Export ("listener", ArgumentSemantic.Weak)] + SKNode Listener { get; set; } + } - [MacCatalyst (13, 1)] - [Export ("audioEngine", ArgumentSemantic.Retain)] - AVAudioEngine AudioEngine { get; } + /// Interface representing the required methods (if any) of the protocol . + /// + /// This interface contains the required methods (if any) from the protocol defined by . + /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. + /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. + /// + interface ISKSceneDelegate { } + /// Delegate object for SKScene objects. Provides methods relating to animation events. + /// + /// Apple documentation for SKSceneDelegate [MacCatalyst (13, 1)] - [NullAllowed, Export ("camera", ArgumentSemantic.Weak)] - SKCameraNode Camera { get; set; } + [Protocol, Model] + [BaseType (typeof (NSObject))] + interface SKSceneDelegate { + [Export ("update:forScene:")] + void Update (double currentTime, SKScene scene); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("listener", ArgumentSemantic.Weak)] - SKNode Listener { get; set; } -} + [Export ("didEvaluateActionsForScene:")] + void DidEvaluateActions (SKScene scene); -/// Interface representing the required methods (if any) of the protocol . -/// -/// This interface contains the required methods (if any) from the protocol defined by . -/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. -/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. -/// -interface ISKSceneDelegate { } - -/// Delegate object for SKScene objects. Provides methods relating to animation events. -/// -/// Apple documentation for SKSceneDelegate -[MacCatalyst (13, 1)] -[Protocol, Model] -[BaseType (typeof (NSObject))] -interface SKSceneDelegate { - [Export ("update:forScene:")] - void Update (double currentTime, SKScene scene); - - [Export ("didEvaluateActionsForScene:")] - void DidEvaluateActions (SKScene scene); - - [Export ("didSimulatePhysicsForScene:")] - void DidSimulatePhysics (SKScene scene); - - [Export ("didApplyConstraintsForScene:")] - void DidApplyConstraints (SKScene scene); - - [Export ("didFinishUpdateForScene:")] - void DidFinishUpdate (SKScene scene); -} + [Export ("didSimulatePhysicsForScene:")] + void DidSimulatePhysics (SKScene scene); + + [Export ("didApplyConstraintsForScene:")] + void DidApplyConstraints (SKScene scene); + + [Export ("didFinishUpdateForScene:")] + void DidFinishUpdate (SKScene scene); + } + + /// An OpenGL ES fragment shader. + /// + /// Apple documentation for SKShader + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKShader : NSCopying, NSSecureCoding { + [Export ("initWithSource:")] + NativeHandle Constructor (string shaderSourceCode); -/// An OpenGL ES fragment shader. -/// -/// Apple documentation for SKShader -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKShader : NSCopying, NSSecureCoding { - [Export ("initWithSource:")] - NativeHandle Constructor (string shaderSourceCode); + [Export ("initWithSource:uniforms:")] + NativeHandle Constructor (string sharedSourceCode, SKUniform [] uniforms); - [Export ("initWithSource:uniforms:")] - NativeHandle Constructor (string sharedSourceCode, SKUniform [] uniforms); + [NullAllowed] // by default this property is null + [Export ("source")] + string Source { get; set; } - [NullAllowed] // by default this property is null - [Export ("source")] - string Source { get; set; } + // @property (copy) NSArray * uniforms; + [Export ("uniforms", ArgumentSemantic.Copy)] + SKUniform [] Uniforms { get; set; } - // @property (copy) NSArray * uniforms; - [Export ("uniforms", ArgumentSemantic.Copy)] - SKUniform [] Uniforms { get; set; } + // @required + (instancetype)shader; + [Static, Export ("shader")] + SKShader Create (); - // @required + (instancetype)shader; - [Static, Export ("shader")] - SKShader Create (); + [Static, Export ("shaderWithSource:")] + SKShader FromShaderSourceCode (string source); - [Static, Export ("shaderWithSource:")] - SKShader FromShaderSourceCode (string source); + [Static, Export ("shaderWithSource:uniforms:")] + SKShader FromShaderSourceCode (string source, SKUniform [] uniforms); - [Static, Export ("shaderWithSource:uniforms:")] - SKShader FromShaderSourceCode (string source, SKUniform [] uniforms); + [Static, Export ("shaderWithFileNamed:")] + SKShader FromFile (string name); - [Static, Export ("shaderWithFileNamed:")] - SKShader FromFile (string name); + [Export ("addUniform:")] + void AddUniform (SKUniform uniform); - [Export ("addUniform:")] - void AddUniform (SKUniform uniform); + [Export ("uniformNamed:")] + [return: NullAllowed] + SKUniform GetUniform (string uniformName); - [Export ("uniformNamed:")] - [return: NullAllowed] - SKUniform GetUniform (string uniformName); + [Export ("removeUniformNamed:")] + void RemoveUniform (string uniforName); - [Export ("removeUniformNamed:")] - void RemoveUniform (string uniforName); + [MacCatalyst (13, 1)] + [Export ("attributes", ArgumentSemantic.Copy)] + SKAttribute [] Attributes { get; set; } + } + /// A that displays a textured, colored sprite. + /// + /// Apple documentation for SKSpriteNode [MacCatalyst (13, 1)] - [Export ("attributes", ArgumentSemantic.Copy)] - SKAttribute [] Attributes { get; set; } -} + [BaseType (typeof (SKNode))] + partial interface SKSpriteNode : SKWarpable { -/// A that displays a textured, colored sprite. -/// -/// Apple documentation for SKSpriteNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKSpriteNode : SKWarpable { + [Static, Export ("spriteNodeWithTexture:size:")] + SKSpriteNode FromTexture ([NullAllowed] SKTexture texture, CGSize size); - [Static, Export ("spriteNodeWithTexture:size:")] - SKSpriteNode FromTexture ([NullAllowed] SKTexture texture, CGSize size); + [Static, Export ("spriteNodeWithTexture:")] + SKSpriteNode FromTexture ([NullAllowed] SKTexture texture); - [Static, Export ("spriteNodeWithTexture:")] - SKSpriteNode FromTexture ([NullAllowed] SKTexture texture); + [Static, Export ("spriteNodeWithImageNamed:")] + SKSpriteNode FromImageNamed (string name); - [Static, Export ("spriteNodeWithImageNamed:")] - SKSpriteNode FromImageNamed (string name); + [Static, Export ("spriteNodeWithColor:size:")] + SKSpriteNode FromColor (UIColor color, CGSize size); - [Static, Export ("spriteNodeWithColor:size:")] - SKSpriteNode FromColor (UIColor color, CGSize size); + [DesignatedInitializer] + [Export ("initWithTexture:color:size:")] + NativeHandle Constructor ([NullAllowed] SKTexture texture, UIColor color, CGSize size); - [DesignatedInitializer] - [Export ("initWithTexture:color:size:")] - NativeHandle Constructor ([NullAllowed] SKTexture texture, UIColor color, CGSize size); + [Export ("initWithTexture:")] + NativeHandle Constructor ([NullAllowed] SKTexture texture); - [Export ("initWithTexture:")] - NativeHandle Constructor ([NullAllowed] SKTexture texture); + // can't be null -> crash + [Export ("initWithImageNamed:")] + NativeHandle Constructor (string name); - // can't be null -> crash - [Export ("initWithImageNamed:")] - NativeHandle Constructor (string name); + [Export ("initWithColor:size:")] + NativeHandle Constructor (UIColor color, CGSize size); - [Export ("initWithColor:size:")] - NativeHandle Constructor (UIColor color, CGSize size); + [Export ("texture", ArgumentSemantic.Retain)] + [NullAllowed] + SKTexture Texture { get; set; } - [Export ("texture", ArgumentSemantic.Retain)] - [NullAllowed] - SKTexture Texture { get; set; } + [Export ("centerRect")] + CGRect CenterRect { get; set; } - [Export ("centerRect")] - CGRect CenterRect { get; set; } + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + [Export ("color", ArgumentSemantic.Retain)] + [NullAllowed] // it's actually null-resetable (see unit tests) + UIColor Color { get; set; } - [Export ("color", ArgumentSemantic.Retain)] - [NullAllowed] // it's actually null-resetable (see unit tests) - UIColor Color { get; set; } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } + [Export ("size")] + CGSize Size { get; set; } - [Export ("size")] - CGSize Size { get; set; } + // + // iOS 8 + // - // - // iOS 8 - // + [MacCatalyst (13, 1)] + [Static, Export ("spriteNodeWithTexture:normalMap:")] + SKSpriteNode Create ([NullAllowed] SKTexture texture, [NullAllowed] SKTexture normalMap); - [MacCatalyst (13, 1)] - [Static, Export ("spriteNodeWithTexture:normalMap:")] - SKSpriteNode Create ([NullAllowed] SKTexture texture, [NullAllowed] SKTexture normalMap); + [MacCatalyst (13, 1)] + [Static, Export ("spriteNodeWithImageNamed:normalMapped:")] + SKSpriteNode Create (string imageName, bool generateNormalMap); - [MacCatalyst (13, 1)] - [Static, Export ("spriteNodeWithImageNamed:normalMapped:")] - SKSpriteNode Create (string imageName, bool generateNormalMap); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("normalTexture", ArgumentSemantic.Retain)] + SKTexture NormalTexture { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("normalTexture", ArgumentSemantic.Retain)] - SKTexture NormalTexture { get; set; } + [MacCatalyst (13, 1)] + [Export ("lightingBitMask")] + uint LightingBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("lightingBitMask")] - uint LightingBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("shadowCastBitMask")] + uint ShadowCastBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("shadowCastBitMask")] - uint ShadowCastBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("shadowedBitMask")] + uint ShadowedBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("shadowedBitMask")] - uint ShadowedBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("shader", ArgumentSemantic.Retain), NullAllowed] + SKShader Shader { get; set; } - [MacCatalyst (13, 1)] - [Export ("shader", ArgumentSemantic.Retain), NullAllowed] - SKShader Shader { get; set; } + [MacCatalyst (13, 1)] + [Export ("scaleToSize:")] + void ScaleTo (CGSize size); - [MacCatalyst (13, 1)] - [Export ("scaleToSize:")] - void ScaleTo (CGSize size); + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } + /// An object that can control the properties of particles emitted by a . + /// + /// The total time of the sequence is normalized from 0.0 to 1.0. + /// + /// + /// + /// + /// + /// Apple documentation for SKKeyframeSequence [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} + [BaseType (typeof (NSObject))] + partial interface SKKeyframeSequence : NSSecureCoding, NSCopying { -/// An object that can control the properties of particles emitted by a . -/// -/// The total time of the sequence is normalized from 0.0 to 1.0. -/// -/// -/// -/// -/// -/// Apple documentation for SKKeyframeSequence -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -partial interface SKKeyframeSequence : NSSecureCoding, NSCopying { - - [DesignatedInitializer] - [Export ("initWithKeyframeValues:times:")] - [Internal] - NativeHandle Constructor ([NullAllowed] NSObject [] values, [NullAllowed] NSArray times); + [DesignatedInitializer] + [Export ("initWithKeyframeValues:times:")] + [Internal] + NativeHandle Constructor ([NullAllowed] NSObject [] values, [NullAllowed] NSArray times); - [Export ("initWithCapacity:")] - NativeHandle Constructor (nuint numItems); + [Export ("initWithCapacity:")] + NativeHandle Constructor (nuint numItems); - [Export ("count")] - nuint Count { get; } + [Export ("count")] + nuint Count { get; } - [Export ("addKeyframeValue:time:")] - void AddKeyframeValue (NSObject value, nfloat time); + [Export ("addKeyframeValue:time:")] + void AddKeyframeValue (NSObject value, nfloat time); - [Export ("removeLastKeyframe")] - void RemoveLastKeyframe (); + [Export ("removeLastKeyframe")] + void RemoveLastKeyframe (); - [Export ("removeKeyframeAtIndex:")] - void RemoveKeyframe (nuint index); + [Export ("removeKeyframeAtIndex:")] + void RemoveKeyframe (nuint index); - [Export ("setKeyframeValue:forIndex:")] - void SetKeyframeValue (NSObject value, nuint index); + [Export ("setKeyframeValue:forIndex:")] + void SetKeyframeValue (NSObject value, nuint index); - [Export ("setKeyframeTime:forIndex:")] - void SetKeyframeTime (nfloat time, nuint index); + [Export ("setKeyframeTime:forIndex:")] + void SetKeyframeTime (nfloat time, nuint index); - [Export ("setKeyframeValue:time:forIndex:")] - void SetKeyframeValue (NSObject value, nfloat time, nuint index); + [Export ("setKeyframeValue:time:forIndex:")] + void SetKeyframeValue (NSObject value, nfloat time, nuint index); - [Export ("getKeyframeValueForIndex:")] - NSObject GetKeyframeValue (nuint index); + [Export ("getKeyframeValueForIndex:")] + NSObject GetKeyframeValue (nuint index); - [Export ("getKeyframeTimeForIndex:")] - nfloat GetKeyframeTime (nuint index); + [Export ("getKeyframeTimeForIndex:")] + nfloat GetKeyframeTime (nuint index); - [Export ("sampleAtTime:")] - [return: NullAllowed] - NSObject SampleAtTime (nfloat time); + [Export ("sampleAtTime:")] + [return: NullAllowed] + NSObject SampleAtTime (nfloat time); - [Export ("interpolationMode")] - SKInterpolationMode InterpolationMode { get; set; } + [Export ("interpolationMode")] + SKInterpolationMode InterpolationMode { get; set; } - [Export ("repeatMode")] - SKRepeatMode RepeatMode { get; set; } -} + [Export ("repeatMode")] + SKRepeatMode RepeatMode { get; set; } + } -/// A that produces colored and textured particles. -/// -/// Emitted particles are not directly accessible to the application developer; their behavior can be controlled either via the creation parameters configurable in or by a . -/// -/// Apple documentation for SKEmitterNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKEmitterNode { + /// A that produces colored and textured particles. + /// + /// Emitted particles are not directly accessible to the application developer; their behavior can be controlled either via the creation parameters configurable in or by a . + /// + /// Apple documentation for SKEmitterNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + partial interface SKEmitterNode { - [Export ("advanceSimulationTime:")] - void AdvanceSimulationTime (double sec); + [Export ("advanceSimulationTime:")] + void AdvanceSimulationTime (double sec); - [Export ("resetSimulation")] - void ResetSimulation (); + [Export ("resetSimulation")] + void ResetSimulation (); - [NullAllowed] // by default this property is null - [Export ("particleTexture", ArgumentSemantic.Retain)] - SKTexture ParticleTexture { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleTexture", ArgumentSemantic.Retain)] + SKTexture ParticleTexture { get; set; } - [Export ("particleZPosition")] - nfloat ParticleZPosition { get; set; } + [Export ("particleZPosition")] + nfloat ParticleZPosition { get; set; } - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 8, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("particleZPositionRange")] - nfloat ParticleZPositionRange { get; set; } + [Deprecated (PlatformName.iOS, 8, 0)] + [Deprecated (PlatformName.TvOS, 8, 0)] + [Deprecated (PlatformName.MacOSX, 10, 10)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("particleZPositionRange")] + nfloat ParticleZPositionRange { get; set; } - [Export ("particleBlendMode")] - SKBlendMode ParticleBlendMode { get; set; } + [Export ("particleBlendMode")] + SKBlendMode ParticleBlendMode { get; set; } - [Export ("particleColor", ArgumentSemantic.Retain)] - UIColor ParticleColor { get; set; } + [Export ("particleColor", ArgumentSemantic.Retain)] + UIColor ParticleColor { get; set; } - [Export ("particleColorRedRange")] - nfloat ParticleColorRedRange { get; set; } + [Export ("particleColorRedRange")] + nfloat ParticleColorRedRange { get; set; } - [Export ("particleColorGreenRange")] - nfloat ParticleColorGreenRange { get; set; } + [Export ("particleColorGreenRange")] + nfloat ParticleColorGreenRange { get; set; } - [Export ("particleColorBlueRange")] - nfloat ParticleColorBlueRange { get; set; } + [Export ("particleColorBlueRange")] + nfloat ParticleColorBlueRange { get; set; } - [Export ("particleColorAlphaRange")] - nfloat ParticleColorAlphaRange { get; set; } + [Export ("particleColorAlphaRange")] + nfloat ParticleColorAlphaRange { get; set; } - [Export ("particleColorRedSpeed")] - nfloat ParticleColorRedSpeed { get; set; } + [Export ("particleColorRedSpeed")] + nfloat ParticleColorRedSpeed { get; set; } - [Export ("particleColorGreenSpeed")] - nfloat ParticleColorGreenSpeed { get; set; } + [Export ("particleColorGreenSpeed")] + nfloat ParticleColorGreenSpeed { get; set; } - [Export ("particleColorBlueSpeed")] - nfloat ParticleColorBlueSpeed { get; set; } + [Export ("particleColorBlueSpeed")] + nfloat ParticleColorBlueSpeed { get; set; } - [Export ("particleColorAlphaSpeed")] - nfloat ParticleColorAlphaSpeed { get; set; } + [Export ("particleColorAlphaSpeed")] + nfloat ParticleColorAlphaSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleColorSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleColorSequence { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleColorSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleColorSequence { get; set; } - [Export ("particleColorBlendFactor")] - nfloat ParticleColorBlendFactor { get; set; } + [Export ("particleColorBlendFactor")] + nfloat ParticleColorBlendFactor { get; set; } - [Export ("particleColorBlendFactorRange")] - nfloat ParticleColorBlendFactorRange { get; set; } + [Export ("particleColorBlendFactorRange")] + nfloat ParticleColorBlendFactorRange { get; set; } - [Export ("particleColorBlendFactorSpeed")] - nfloat ParticleColorBlendFactorSpeed { get; set; } + [Export ("particleColorBlendFactorSpeed")] + nfloat ParticleColorBlendFactorSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleColorBlendFactorSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleColorBlendFactorSequence { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleColorBlendFactorSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleColorBlendFactorSequence { get; set; } - [Export ("particlePosition")] - CGPoint ParticlePosition { get; set; } + [Export ("particlePosition")] + CGPoint ParticlePosition { get; set; } - [Export ("particlePositionRange")] - CGVector ParticlePositionRange { get; set; } + [Export ("particlePositionRange")] + CGVector ParticlePositionRange { get; set; } - [Export ("particleSpeed")] - nfloat ParticleSpeed { get; set; } + [Export ("particleSpeed")] + nfloat ParticleSpeed { get; set; } - [Export ("particleSpeedRange")] - nfloat ParticleSpeedRange { get; set; } + [Export ("particleSpeedRange")] + nfloat ParticleSpeedRange { get; set; } - [Export ("emissionAngle")] - nfloat EmissionAngle { get; set; } + [Export ("emissionAngle")] + nfloat EmissionAngle { get; set; } - [Export ("emissionAngleRange")] - nfloat EmissionAngleRange { get; set; } + [Export ("emissionAngleRange")] + nfloat EmissionAngleRange { get; set; } - [Export ("xAcceleration")] - nfloat XAcceleration { get; set; } + [Export ("xAcceleration")] + nfloat XAcceleration { get; set; } - [Export ("yAcceleration")] - nfloat YAcceleration { get; set; } + [Export ("yAcceleration")] + nfloat YAcceleration { get; set; } - [Export ("particleBirthRate")] - nfloat ParticleBirthRate { get; set; } + [Export ("particleBirthRate")] + nfloat ParticleBirthRate { get; set; } - [Export ("numParticlesToEmit")] - nuint NumParticlesToEmit { get; set; } + [Export ("numParticlesToEmit")] + nuint NumParticlesToEmit { get; set; } - [Export ("particleLifetime")] - nfloat ParticleLifetime { get; set; } + [Export ("particleLifetime")] + nfloat ParticleLifetime { get; set; } - [Export ("particleLifetimeRange")] - nfloat ParticleLifetimeRange { get; set; } + [Export ("particleLifetimeRange")] + nfloat ParticleLifetimeRange { get; set; } - [Export ("particleRotation")] - nfloat ParticleRotation { get; set; } + [Export ("particleRotation")] + nfloat ParticleRotation { get; set; } - [Export ("particleRotationRange")] - nfloat ParticleRotationRange { get; set; } + [Export ("particleRotationRange")] + nfloat ParticleRotationRange { get; set; } - [Export ("particleRotationSpeed")] - nfloat ParticleRotationSpeed { get; set; } + [Export ("particleRotationSpeed")] + nfloat ParticleRotationSpeed { get; set; } - [Export ("particleSize")] - CGSize ParticleSize { get; set; } + [Export ("particleSize")] + CGSize ParticleSize { get; set; } - [Export ("particleScale")] - nfloat ParticleScale { get; set; } + [Export ("particleScale")] + nfloat ParticleScale { get; set; } - [Export ("particleScaleRange")] - nfloat ParticleScaleRange { get; set; } + [Export ("particleScaleRange")] + nfloat ParticleScaleRange { get; set; } - [Export ("particleScaleSpeed")] - nfloat ParticleScaleSpeed { get; set; } + [Export ("particleScaleSpeed")] + nfloat ParticleScaleSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleScaleSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleScaleSequence { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleScaleSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleScaleSequence { get; set; } - [Export ("particleAlpha")] - nfloat ParticleAlpha { get; set; } + [Export ("particleAlpha")] + nfloat ParticleAlpha { get; set; } - [Export ("particleAlphaRange")] - nfloat ParticleAlphaRange { get; set; } + [Export ("particleAlphaRange")] + nfloat ParticleAlphaRange { get; set; } - [Export ("particleAlphaSpeed")] - nfloat ParticleAlphaSpeed { get; set; } + [Export ("particleAlphaSpeed")] + nfloat ParticleAlphaSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleAlphaSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleAlphaSequence { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleAlphaSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleAlphaSequence { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleAction", ArgumentSemantic.Copy)] - SKAction ParticleAction { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleAction", ArgumentSemantic.Copy)] + SKAction ParticleAction { get; set; } - [NullAllowed] // by default this property is null - [Export ("targetNode", ArgumentSemantic.Weak)] - SKNode TargetNode { get; set; } + [NullAllowed] // by default this property is null + [Export ("targetNode", ArgumentSemantic.Weak)] + SKNode TargetNode { get; set; } + + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("fieldBitMask")] + uint FieldBitMask { get; set; } /* uint32_t */ + + [Deprecated (PlatformName.iOS, 8, 0)] + [Deprecated (PlatformName.TvOS, 8, 0)] + [Deprecated (PlatformName.MacOSX, 10, 10)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("particleZPositionSpeed")] + nfloat ParticleZPositionSpeed { get; set; } + + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Export ("fieldBitMask")] - uint FieldBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("particleRenderOrder", ArgumentSemantic.Assign)] + SKParticleRenderOrder ParticleRenderOrder { get; set; } - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 8, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("particleZPositionSpeed")] - nfloat ParticleZPositionSpeed { get; set; } + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [MacCatalyst (13, 1)] - [Export ("particleRenderOrder", ArgumentSemantic.Assign)] - SKParticleRenderOrder ParticleRenderOrder { get; set; } + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } + /// A defined by a Core Graphics . + /// + /// Apple documentation for SKShapeNode [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [BaseType (typeof (SKNode))] + partial interface SKShapeNode { - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [NullAllowed] + [Export ("path")] + CGPath Path { get; set; } - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} + [Export ("strokeColor", ArgumentSemantic.Retain)] + UIColor StrokeColor { get; set; } -/// A defined by a Core Graphics . -/// -/// Apple documentation for SKShapeNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKShapeNode { + [Export ("fillColor", ArgumentSemantic.Retain)] + UIColor FillColor { get; set; } - [NullAllowed] - [Export ("path")] - CGPath Path { get; set; } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [Export ("strokeColor", ArgumentSemantic.Retain)] - UIColor StrokeColor { get; set; } + [Export ("antialiased")] + bool Antialiased { [Bind ("isAntialiased")] get; set; } - [Export ("fillColor", ArgumentSemantic.Retain)] - UIColor FillColor { get; set; } + [Export ("lineWidth")] + nfloat LineWidth { get; set; } - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [Export ("glowWidth")] + nfloat GlowWidth { get; set; } - [Export ("antialiased")] - bool Antialiased { [Bind ("isAntialiased")] get; set; } + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("fillTexture", ArgumentSemantic.Retain)] + SKTexture FillTexture { get; set; } - [Export ("lineWidth")] - nfloat LineWidth { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("fillShader", ArgumentSemantic.Retain)] + SKShader FillShader { get; set; } - [Export ("glowWidth")] - nfloat GlowWidth { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("strokeTexture", ArgumentSemantic.Retain)] + SKTexture StrokeTexture { get; set; } - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("fillTexture", ArgumentSemantic.Retain)] - SKTexture FillTexture { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("strokeShader", ArgumentSemantic.Retain)] + SKShader StrokeShader { get; set; } + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPath:")] + SKShapeNode FromPath (CGPath path); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPath:centered:")] + SKShapeNode FromPath (CGPath path, bool centered); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRect:")] + SKShapeNode FromRect (CGRect rect); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRectOfSize:")] + SKShapeNode FromRect (CGSize size); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRect:cornerRadius:")] + SKShapeNode FromRect (CGRect rect, nfloat cornerRadius); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRectOfSize:cornerRadius:")] + SKShapeNode FromRect (CGSize size, nfloat cornerRadius); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithCircleOfRadius:")] + SKShapeNode FromCircle (nfloat radius); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithEllipseInRect:")] + SKShapeNode FromEllipse (CGRect rect); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithEllipseOfSize:")] + SKShapeNode FromEllipse (CGSize size); + + // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 + [Internal] + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPoints:count:")] + SKShapeNode FromPoints (ref CGPoint points, nuint numPoints); + + // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 + [Internal] + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithSplinePoints:count:")] + SKShapeNode FromSplinePoints (ref CGPoint points, nuint numPoints); + + [MacCatalyst (13, 1)] + [Export ("lineCap")] + CGLineCap LineCap { get; set; } + + [MacCatalyst (13, 1)] + [Export ("lineJoin")] + CGLineJoin LineJoin { get; set; } + + [MacCatalyst (13, 1)] + [Export ("miterLimit")] + nfloat MiterLimit { get; set; } + + [MacCatalyst (13, 1)] + [Export ("lineLength")] + nfloat LineLength { get; } + + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } + + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); + + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } + /// A range of motion used with inverse kinematics. + /// + /// Apple documentation for SKReachConstraints [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("fillShader", ArgumentSemantic.Retain)] - SKShader FillShader { get; set; } + [BaseType (typeof (NSObject))] + interface SKReachConstraints : NSSecureCoding { + [DesignatedInitializer] + [Export ("initWithLowerAngleLimit:upperAngleLimit:")] + NativeHandle Constructor (nfloat lowerAngleLimit, nfloat upperAngleLimit); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("strokeTexture", ArgumentSemantic.Retain)] - SKTexture StrokeTexture { get; set; } + [Export ("lowerAngleLimit", ArgumentSemantic.UnsafeUnretained)] + nfloat LowerAngleLimit { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("strokeShader", ArgumentSemantic.Retain)] - SKShader StrokeShader { get; set; } + [Export ("upperAngleLimit", ArgumentSemantic.UnsafeUnretained)] + nfloat UpperAngleLimit { get; set; } + } + /// A path-defined area. Typically used for hit-testing and physics-field extents. + /// + /// Apple documentation for SKRegion [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPath:")] - SKShapeNode FromPath (CGPath path); + [BaseType (typeof (NSObject))] + interface SKRegion : NSCopying, NSSecureCoding { + [Export ("initWithRadius:")] + NativeHandle Constructor (float /* float, not CGFloat */ radius); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPath:centered:")] - SKShapeNode FromPath (CGPath path, bool centered); + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRect:")] - SKShapeNode FromRect (CGRect rect); + [Export ("initWithPath:")] + NativeHandle Constructor (CGPath path); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRectOfSize:")] - SKShapeNode FromRect (CGSize size); + [Export ("path")] + [NullAllowed] + CGPath Path { get; } - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRect:cornerRadius:")] - SKShapeNode FromRect (CGRect rect, nfloat cornerRadius); + [Static, Export ("infiniteRegion")] + SKRegion InfiniteRegion { get; } - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRectOfSize:cornerRadius:")] - SKShapeNode FromRect (CGSize size, nfloat cornerRadius); + [Export ("inverseRegion")] + SKRegion InverseRegion (); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithCircleOfRadius:")] - SKShapeNode FromCircle (nfloat radius); + [Export ("regionByUnionWithRegion:")] + SKRegion CreateUnion (SKRegion region); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithEllipseInRect:")] - SKShapeNode FromEllipse (CGRect rect); + [Export ("regionByDifferenceFromRegion:")] + SKRegion CreateDifference (SKRegion region); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithEllipseOfSize:")] - SKShapeNode FromEllipse (CGSize size); + [Export ("regionByIntersectionWithRegion:")] + SKRegion CreateIntersection (SKRegion region); - // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 - [Internal] - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPoints:count:")] - SKShapeNode FromPoints (ref CGPoint points, nuint numPoints); + [Export ("containsPoint:")] + bool ContainsPoint (CGPoint point); + } - // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 - [Internal] + /// A that displays a string. + /// + /// Apple documentation for SKLabelNode [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithSplinePoints:count:")] - SKShapeNode FromSplinePoints (ref CGPoint points, nuint numPoints); + [BaseType (typeof (SKNode))] + partial interface SKLabelNode { - [MacCatalyst (13, 1)] - [Export ("lineCap")] - CGLineCap LineCap { get; set; } + [Static, Export ("labelNodeWithFontNamed:")] + SKLabelNode FromFont ([NullAllowed] string fontName); - [MacCatalyst (13, 1)] - [Export ("lineJoin")] - CGLineJoin LineJoin { get; set; } + [Export ("initWithFontNamed:")] + NativeHandle Constructor ([NullAllowed] string fontName); - [MacCatalyst (13, 1)] - [Export ("miterLimit")] - nfloat MiterLimit { get; set; } + [MacCatalyst (13, 1)] + [Static, Export ("labelNodeWithText:")] + SKLabelNode FromText ([NullAllowed] string text); - [MacCatalyst (13, 1)] - [Export ("lineLength")] - nfloat LineLength { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("labelNodeWithAttributedText:")] + SKLabelNode FromText ([NullAllowed] NSAttributedString attributedText); - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [Export ("verticalAlignmentMode")] + SKLabelVerticalAlignmentMode VerticalAlignmentMode { get; set; } - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [Export ("horizontalAlignmentMode")] + SKLabelHorizontalAlignmentMode HorizontalAlignmentMode { get; set; } - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} + [MacCatalyst (13, 1)] + [Export ("numberOfLines")] + nint NumberOfLines { get; set; } -/// A range of motion used with inverse kinematics. -/// -/// Apple documentation for SKReachConstraints -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKReachConstraints : NSSecureCoding { - [DesignatedInitializer] - [Export ("initWithLowerAngleLimit:upperAngleLimit:")] - NativeHandle Constructor (nfloat lowerAngleLimit, nfloat upperAngleLimit); - - [Export ("lowerAngleLimit", ArgumentSemantic.UnsafeUnretained)] - nfloat LowerAngleLimit { get; set; } - - [Export ("upperAngleLimit", ArgumentSemantic.UnsafeUnretained)] - nfloat UpperAngleLimit { get; set; } -} + [MacCatalyst (13, 1)] + [Export ("lineBreakMode", ArgumentSemantic.Assign)] + NSLineBreakMode LineBreakMode { get; set; } -/// A path-defined area. Typically used for hit-testing and physics-field extents. -/// -/// Apple documentation for SKRegion -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKRegion : NSCopying, NSSecureCoding { - [Export ("initWithRadius:")] - NativeHandle Constructor (float /* float, not CGFloat */ radius); + [MacCatalyst (13, 1)] + [Export ("preferredMaxLayoutWidth")] + nfloat PreferredMaxLayoutWidth { get; set; } - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [Export ("fontName", ArgumentSemantic.Copy)] + [NullAllowed] + string FontName { get; set; } - [Export ("initWithPath:")] - NativeHandle Constructor (CGPath path); + [Export ("text", ArgumentSemantic.Copy)] + [NullAllowed] // nullable in Xcode7 headers and caught by introspection tests + string Text { get; set; } - [Export ("path")] - [NullAllowed] - CGPath Path { get; } + [MacCatalyst (13, 1)] + [NullAllowed, Export ("attributedText", ArgumentSemantic.Copy)] + NSAttributedString AttributedText { get; set; } - [Static, Export ("infiniteRegion")] - SKRegion InfiniteRegion { get; } + [Export ("fontSize")] + nfloat FontSize { get; set; } - [Export ("inverseRegion")] - SKRegion InverseRegion (); + [Export ("fontColor", ArgumentSemantic.Retain)] + [NullAllowed] + UIColor FontColor { get; set; } - [Export ("regionByUnionWithRegion:")] - SKRegion CreateUnion (SKRegion region); + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("regionByDifferenceFromRegion:")] - SKRegion CreateDifference (SKRegion region); + [NullAllowed] // by default this property is null + [Export ("color", ArgumentSemantic.Retain)] + UIColor Color { get; set; } - [Export ("regionByIntersectionWithRegion:")] - SKRegion CreateIntersection (SKRegion region); + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } + } - [Export ("containsPoint:")] - bool ContainsPoint (CGPoint point); -} + /// A node that creates a lighting effect within a scene. + /// + /// Apple documentation for SKLightNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + interface SKLightNode { + [Export ("enabled")] + bool Enabled { [Bind ("isEnabled")] get; set; } -/// A that displays a string. -/// -/// Apple documentation for SKLabelNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKLabelNode { + [Export ("lightColor")] + UIColor LightColor { get; set; } - [Static, Export ("labelNodeWithFontNamed:")] - SKLabelNode FromFont ([NullAllowed] string fontName); + [Export ("ambientColor")] + UIColor AmbientColor { get; set; } - [Export ("initWithFontNamed:")] - NativeHandle Constructor ([NullAllowed] string fontName); + [Export ("shadowColor")] + UIColor ShadowColor { get; set; } - [MacCatalyst (13, 1)] - [Static, Export ("labelNodeWithText:")] - SKLabelNode FromText ([NullAllowed] string text); + [Export ("falloff")] + nfloat Falloff { get; set; } + + [Export ("categoryBitMask")] + uint CategoryBitMask { get; set; } /* uint32_t */ + } + /// A that displays video. + /// + /// Apple documentation for SKVideoNode [MacCatalyst (13, 1)] - [Static] - [Export ("labelNodeWithAttributedText:")] - SKLabelNode FromText ([NullAllowed] NSAttributedString attributedText); + [BaseType (typeof (SKNode))] + partial interface SKVideoNode { + [Static, Export ("videoNodeWithAVPlayer:")] + SKVideoNode FromPlayer (AVPlayer player); - [Export ("verticalAlignmentMode")] - SKLabelVerticalAlignmentMode VerticalAlignmentMode { get; set; } + [Static, Export ("videoNodeWithVideoFileNamed:"), Internal] + SKVideoNode VideoNodeWithVideoFileNamed (string videoFile); - [Export ("horizontalAlignmentMode")] - SKLabelHorizontalAlignmentMode HorizontalAlignmentMode { get; set; } + [Static, Export ("videoNodeWithFileNamed:"), Internal] + SKVideoNode VideoNodeWithFileNamed (string videoFile); - [MacCatalyst (13, 1)] - [Export ("numberOfLines")] - nint NumberOfLines { get; set; } + [Static, Export ("videoNodeWithVideoURL:"), Internal] + SKVideoNode VideoNodeWithVideoURL (NSUrl videoURL); - [MacCatalyst (13, 1)] - [Export ("lineBreakMode", ArgumentSemantic.Assign)] - NSLineBreakMode LineBreakMode { get; set; } + [Static, Export ("videoNodeWithURL:"), Internal] + SKVideoNode VideoNodeWithURL (NSUrl videoURL); - [MacCatalyst (13, 1)] - [Export ("preferredMaxLayoutWidth")] - nfloat PreferredMaxLayoutWidth { get; set; } + [DesignatedInitializer] + [Export ("initWithAVPlayer:")] + NativeHandle Constructor (AVPlayer player); - [Export ("fontName", ArgumentSemantic.Copy)] - [NullAllowed] - string FontName { get; set; } + [Export ("initWithVideoFileNamed:"), Internal] + IntPtr InitWithVideoFileNamed (string videoFile); - [Export ("text", ArgumentSemantic.Copy)] - [NullAllowed] // nullable in Xcode7 headers and caught by introspection tests - string Text { get; set; } + [Export ("initWithFileNamed:"), Internal] + IntPtr InitWithFileNamed (string videoFile); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("attributedText", ArgumentSemantic.Copy)] - NSAttributedString AttributedText { get; set; } + [Export ("initWithVideoURL:"), Internal] + IntPtr InitWithVideoURL (NSUrl url); - [Export ("fontSize")] - nfloat FontSize { get; set; } + [Export ("initWithURL:"), Internal] + IntPtr InitWithURL (NSUrl url); - [Export ("fontColor", ArgumentSemantic.Retain)] - [NullAllowed] - UIColor FontColor { get; set; } + [Export ("play")] + void Play (); - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + [Export ("pause")] + void Pause (); - [NullAllowed] // by default this property is null - [Export ("color", ArgumentSemantic.Retain)] - UIColor Color { get; set; } + [Export ("size")] + CGSize Size { get; set; } - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } -} + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } + } -/// A node that creates a lighting effect within a scene. -/// -/// Apple documentation for SKLightNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKLightNode { - [Export ("enabled")] - bool Enabled { [Bind ("isEnabled")] get; set; } + /// Mathematical constraint on a node's position or orientation. + /// + /// Apple documentation for SKConstraint + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKConstraint : NSSecureCoding, NSCopying { + [Export ("enabled")] + bool Enabled { get; set; } - [Export ("lightColor")] - UIColor LightColor { get; set; } + [NullAllowed] // by default this property is null + [Export ("referenceNode", ArgumentSemantic.Retain)] + SKNode ReferenceNode { get; set; } - [Export ("ambientColor")] - UIColor AmbientColor { get; set; } + [Static, Export ("positionX:")] + SKConstraint CreateXRestriction (SKRange range); - [Export ("shadowColor")] - UIColor ShadowColor { get; set; } + [Static, Export ("positionY:")] + SKConstraint CreateYRestriction (SKRange range); - [Export ("falloff")] - nfloat Falloff { get; set; } + [Static, Export ("positionX:Y:")] + SKConstraint CreateRestriction (SKRange xRange, SKRange yRange); - [Export ("categoryBitMask")] - uint CategoryBitMask { get; set; } /* uint32_t */ -} + [Static, Export ("distance:toNode:")] + SKConstraint CreateDistance (SKRange range, SKNode node); -/// A that displays video. -/// -/// Apple documentation for SKVideoNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKVideoNode { - [Static, Export ("videoNodeWithAVPlayer:")] - SKVideoNode FromPlayer (AVPlayer player); + [Static, Export ("distance:toPoint:")] + SKConstraint CreateDistance (SKRange range, CGPoint point); - [Static, Export ("videoNodeWithVideoFileNamed:"), Internal] - SKVideoNode VideoNodeWithVideoFileNamed (string videoFile); + [Static, Export ("distance:toPoint:inNode:")] + SKConstraint CreateDistance (SKRange range, CGPoint point, SKNode node); - [Static, Export ("videoNodeWithFileNamed:"), Internal] - SKVideoNode VideoNodeWithFileNamed (string videoFile); + [Static, Export ("zRotation:")] + SKConstraint CreateZRotation (SKRange zRange); - [Static, Export ("videoNodeWithVideoURL:"), Internal] - SKVideoNode VideoNodeWithVideoURL (NSUrl videoURL); + [Static, Export ("orientToNode:offset:")] + SKConstraint CreateOrientToNode (SKNode node, SKRange radians); - [Static, Export ("videoNodeWithURL:"), Internal] - SKVideoNode VideoNodeWithURL (NSUrl videoURL); + [Static, Export ("orientToPoint:offset:")] + SKConstraint CreateOrientToPoint (CGPoint point, SKRange radians); - [DesignatedInitializer] - [Export ("initWithAVPlayer:")] - NativeHandle Constructor (AVPlayer player); + [Static, Export ("orientToPoint:inNode:offset:")] + SKConstraint CreateOrientToPoint (CGPoint point, SKNode node, SKRange radians); + } - [Export ("initWithVideoFileNamed:"), Internal] - IntPtr InitWithVideoFileNamed (string videoFile); + /// A node that masks its children's pixels. + /// + /// An masks pixels outside of the area defined by its node. Pixels that fall outside of that area are not passed up towards the root of the . + /// + /// + /// Apple documentation for SKCropNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + partial interface SKCropNode { - [Export ("initWithFileNamed:"), Internal] - IntPtr InitWithFileNamed (string videoFile); + [NullAllowed] // by default this property is null + [Export ("maskNode", ArgumentSemantic.Retain)] + SKNode MaskNode { get; set; } + } - [Export ("initWithVideoURL:"), Internal] - IntPtr InitWithVideoURL (NSUrl url); + /// A that displays a . + /// + /// Application developers should note the availability of debugging properties, such as . + /// + /// Apple documentation for SKView + [MacCatalyst (13, 1)] + [BaseType (typeof (UIView))] + [DisableDefaultCtor] +#if MONOMAC + partial interface SKView : NSSecureCoding { +#else + partial interface SKView { +#endif + [Export ("initWithFrame:")] + NativeHandle Constructor (CGRect frame); - [Export ("initWithURL:"), Internal] - IntPtr InitWithURL (NSUrl url); + [Export ("paused")] + bool Paused { [Bind ("isPaused")] get; set; } - [Export ("play")] - void Play (); + [Export ("showsFPS")] + bool ShowsFPS { get; set; } - [Export ("pause")] - void Pause (); + [Export ("showsDrawCount")] + bool ShowsDrawCount { get; set; } - [Export ("size")] - CGSize Size { get; set; } + [Export ("showsNodeCount")] + bool ShowsNodeCount { get; set; } - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } -} + [MacCatalyst (13, 1)] + [Export ("showsPhysics")] + bool ShowsPhysics { get; set; } -/// Mathematical constraint on a node's position or orientation. -/// -/// Apple documentation for SKConstraint -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKConstraint : NSSecureCoding, NSCopying { - [Export ("enabled")] - bool Enabled { get; set; } + [Export ("asynchronous")] + bool Asynchronous { [Bind ("isAsynchronous")] get; set; } - [NullAllowed] // by default this property is null - [Export ("referenceNode", ArgumentSemantic.Retain)] - SKNode ReferenceNode { get; set; } + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("frameInterval")] + nint FrameInterval { get; set; } - [Static, Export ("positionX:")] - SKConstraint CreateXRestriction (SKRange range); + [Export ("presentScene:")] + void PresentScene ([NullAllowed] SKScene scene); - [Static, Export ("positionY:")] - SKConstraint CreateYRestriction (SKRange range); + [Export ("presentScene:transition:")] + void PresentScene (SKScene scene, SKTransition transition); - [Static, Export ("positionX:Y:")] - SKConstraint CreateRestriction (SKRange xRange, SKRange yRange); + [Export ("scene")] + [NullAllowed] + SKScene Scene { get; } - [Static, Export ("distance:toNode:")] - SKConstraint CreateDistance (SKRange range, SKNode node); + [Export ("textureFromNode:")] + [return: NullAllowed] + SKTexture TextureFromNode (SKNode node); - [Static, Export ("distance:toPoint:")] - SKConstraint CreateDistance (SKRange range, CGPoint point); + [Export ("convertPoint:toScene:")] + CGPoint ConvertPointToScene (CGPoint point, SKScene scene); - [Static, Export ("distance:toPoint:inNode:")] - SKConstraint CreateDistance (SKRange range, CGPoint point, SKNode node); + [Export ("convertPoint:fromScene:")] + CGPoint ConvertPointFromScene (CGPoint point, SKScene scene); - [Static, Export ("zRotation:")] - SKConstraint CreateZRotation (SKRange zRange); + [Export ("ignoresSiblingOrder")] + bool IgnoresSiblingOrder { get; set; } - [Static, Export ("orientToNode:offset:")] - SKConstraint CreateOrientToNode (SKNode node, SKRange radians); + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("allowsTransparency")] + bool AllowsTransparency { get; set; } - [Static, Export ("orientToPoint:offset:")] - SKConstraint CreateOrientToPoint (CGPoint point, SKRange radians); + [MacCatalyst (13, 1)] + [Export ("shouldCullNonVisibleNodes")] + bool ShouldCullNonVisibleNodes { get; set; } - [Static, Export ("orientToPoint:inNode:offset:")] - SKConstraint CreateOrientToPoint (CGPoint point, SKNode node, SKRange radians); -} + [MacCatalyst (13, 1)] + [Export ("showsFields")] + bool ShowsFields { get; set; } -/// A node that masks its children's pixels. -/// -/// An masks pixels outside of the area defined by its node. Pixels that fall outside of that area are not passed up towards the root of the . -/// -/// -/// Apple documentation for SKCropNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKCropNode { - - [NullAllowed] // by default this property is null - [Export ("maskNode", ArgumentSemantic.Retain)] - SKNode MaskNode { get; set; } -} + [MacCatalyst (13, 1)] + [Export ("showsQuadCount")] + bool ShowsQuadCount { get; set; } -/// A that displays a . -/// -/// Application developers should note the availability of debugging properties, such as . -/// -/// Apple documentation for SKView -[MacCatalyst (13, 1)] -[BaseType (typeof (UIView))] -[DisableDefaultCtor] -#if MONOMAC - partial interface SKView : NSSecureCoding { -#else -partial interface SKView { -#endif - [Export ("initWithFrame:")] - NativeHandle Constructor (CGRect frame); + [MacCatalyst (13, 1)] + [Export ("textureFromNode:crop:")] + [return: NullAllowed] + SKTexture TextureFromNode (SKNode node, CGRect crop); - [Export ("paused")] - bool Paused { [Bind ("isPaused")] get; set; } + [MacCatalyst (13, 1)] + [Export ("preferredFramesPerSecond")] + nint PreferredFramesPerSecond { get; set; } - [Export ("showsFPS")] - bool ShowsFPS { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] + ISKViewDelegate Delegate { get; set; } - [Export ("showsDrawCount")] - bool ShowsDrawCount { get; set; } + [iOS (14, 0)] + [TV (14, 0)] + [MacCatalyst (14, 0)] + [Export ("disableDepthStencilBuffer")] + bool DisableDepthStencilBuffer { get; set; } + } - [Export ("showsNodeCount")] - bool ShowsNodeCount { get; set; } + /// Interface representing the required methods (if any) of the protocol . + /// + /// This interface contains the required methods (if any) from the protocol defined by . + /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. + /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. + /// + interface ISKViewDelegate { } + /// Delegate object for objects, allowing the developer to control the frame rate. + /// + /// Apple documentation for SKViewDelegate [MacCatalyst (13, 1)] - [Export ("showsPhysics")] - bool ShowsPhysics { get; set; } + [Protocol, Model] + [BaseType (typeof (NSObject))] + interface SKViewDelegate { + [Export ("view:shouldRenderAtTime:")] + bool ShouldRender (SKView view, double time); + } - [Export ("asynchronous")] - bool Asynchronous { [Bind ("isAsynchronous")] get; set; } + /// Transitions that can be used between s. Used with the method. + /// + /// Apple documentation for SKTransition + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + partial interface SKTransition : NSCopying { - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("frameInterval")] - nint FrameInterval { get; set; } + [Static, Export ("crossFadeWithDuration:")] + SKTransition CrossFadeWithDuration (double sec); - [Export ("presentScene:")] - void PresentScene ([NullAllowed] SKScene scene); + [Static, Export ("fadeWithDuration:")] + SKTransition FadeWithDuration (double sec); - [Export ("presentScene:transition:")] - void PresentScene (SKScene scene, SKTransition transition); + [Static, Export ("fadeWithColor:duration:")] + SKTransition FadeWithColor (UIColor color, double sec); - [Export ("scene")] - [NullAllowed] - SKScene Scene { get; } + [Static, Export ("flipHorizontalWithDuration:")] + SKTransition FlipHorizontalWithDuration (double sec); - [Export ("textureFromNode:")] - [return: NullAllowed] - SKTexture TextureFromNode (SKNode node); + [Static, Export ("flipVerticalWithDuration:")] + SKTransition FlipVerticalWithDuration (double sec); - [Export ("convertPoint:toScene:")] - CGPoint ConvertPointToScene (CGPoint point, SKScene scene); + [Static, Export ("revealWithDirection:duration:")] + SKTransition RevealWithDirection (SKTransitionDirection direction, double sec); - [Export ("convertPoint:fromScene:")] - CGPoint ConvertPointFromScene (CGPoint point, SKScene scene); + [Static, Export ("moveInWithDirection:duration:")] + SKTransition MoveInWithDirection (SKTransitionDirection direction, double sec); - [Export ("ignoresSiblingOrder")] - bool IgnoresSiblingOrder { get; set; } + [Static, Export ("pushWithDirection:duration:")] + SKTransition PushWithDirection (SKTransitionDirection direction, double sec); - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Export ("allowsTransparency")] - bool AllowsTransparency { get; set; } + [Static, Export ("doorsOpenHorizontalWithDuration:")] + SKTransition DoorsOpenHorizontalWithDuration (double sec); - [MacCatalyst (13, 1)] - [Export ("shouldCullNonVisibleNodes")] - bool ShouldCullNonVisibleNodes { get; set; } + [Static, Export ("doorsOpenVerticalWithDuration:")] + SKTransition DoorsOpenVerticalWithDuration (double sec); - [MacCatalyst (13, 1)] - [Export ("showsFields")] - bool ShowsFields { get; set; } + [Static, Export ("doorsCloseHorizontalWithDuration:")] + SKTransition DoorsCloseHorizontalWithDuration (double sec); - [MacCatalyst (13, 1)] - [Export ("showsQuadCount")] - bool ShowsQuadCount { get; set; } + [Static, Export ("doorsCloseVerticalWithDuration:")] + SKTransition DoorsCloseVerticalWithDuration (double sec); - [MacCatalyst (13, 1)] - [Export ("textureFromNode:crop:")] - [return: NullAllowed] - SKTexture TextureFromNode (SKNode node, CGRect crop); - - [MacCatalyst (13, 1)] - [Export ("preferredFramesPerSecond")] - nint PreferredFramesPerSecond { get; set; } - - [MacCatalyst (13, 1)] - [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] - ISKViewDelegate Delegate { get; set; } - - [iOS (14, 0)] - [TV (14, 0)] - [MacCatalyst (14, 0)] - [Export ("disableDepthStencilBuffer")] - bool DisableDepthStencilBuffer { get; set; } -} - -/// Interface representing the required methods (if any) of the protocol . -/// -/// This interface contains the required methods (if any) from the protocol defined by . -/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. -/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. -/// -interface ISKViewDelegate { } - -/// Delegate object for objects, allowing the developer to control the frame rate. -/// -/// Apple documentation for SKViewDelegate -[MacCatalyst (13, 1)] -[Protocol, Model] -[BaseType (typeof (NSObject))] -interface SKViewDelegate { - [Export ("view:shouldRenderAtTime:")] - bool ShouldRender (SKView view, double time); -} - -/// Transitions that can be used between s. Used with the method. -/// -/// Apple documentation for SKTransition -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -partial interface SKTransition : NSCopying { - - [Static, Export ("crossFadeWithDuration:")] - SKTransition CrossFadeWithDuration (double sec); - - [Static, Export ("fadeWithDuration:")] - SKTransition FadeWithDuration (double sec); - - [Static, Export ("fadeWithColor:duration:")] - SKTransition FadeWithColor (UIColor color, double sec); - - [Static, Export ("flipHorizontalWithDuration:")] - SKTransition FlipHorizontalWithDuration (double sec); - - [Static, Export ("flipVerticalWithDuration:")] - SKTransition FlipVerticalWithDuration (double sec); - - [Static, Export ("revealWithDirection:duration:")] - SKTransition RevealWithDirection (SKTransitionDirection direction, double sec); + [Static, Export ("doorwayWithDuration:")] + SKTransition DoorwayWithDuration (double sec); - [Static, Export ("moveInWithDirection:duration:")] - SKTransition MoveInWithDirection (SKTransitionDirection direction, double sec); + [MacCatalyst (13, 1)] + [Static, Export ("transitionWithCIFilter:duration:")] + SKTransition TransitionWithCIFilter (CIFilter filter, double sec); - [Static, Export ("pushWithDirection:duration:")] - SKTransition PushWithDirection (SKTransitionDirection direction, double sec); + [Export ("pausesIncomingScene")] + bool PausesIncomingScene { get; set; } - [Static, Export ("doorsOpenHorizontalWithDuration:")] - SKTransition DoorsOpenHorizontalWithDuration (double sec); - - [Static, Export ("doorsOpenVerticalWithDuration:")] - SKTransition DoorsOpenVerticalWithDuration (double sec); - - [Static, Export ("doorsCloseHorizontalWithDuration:")] - SKTransition DoorsCloseHorizontalWithDuration (double sec); - - [Static, Export ("doorsCloseVerticalWithDuration:")] - SKTransition DoorsCloseVerticalWithDuration (double sec); - - [Static, Export ("doorwayWithDuration:")] - SKTransition DoorwayWithDuration (double sec); + [Export ("pausesOutgoingScene")] + bool PausesOutgoingScene { get; set; } + } + /// An image that can be used with one or more s and particles. + /// + /// Sprite Kit attempts to be efficient with the memory associated with textures. Textures are lazy-loaded from their source files and in preparation for loading onto the graphics hardware. This lazy-loading can be overridden with the Preload* methods. + /// + /// + /// Apple documentation for SKTexture [MacCatalyst (13, 1)] - [Static, Export ("transitionWithCIFilter:duration:")] - SKTransition TransitionWithCIFilter (CIFilter filter, double sec); + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + partial interface SKTexture : NSSecureCoding, NSCopying { - [Export ("pausesIncomingScene")] - bool PausesIncomingScene { get; set; } + [Static, Export ("textureWithImageNamed:")] + SKTexture FromImageNamed (string name); - [Export ("pausesOutgoingScene")] - bool PausesOutgoingScene { get; set; } -} + [Static, Export ("textureWithRect:inTexture:")] + SKTexture FromRectangle (CGRect rect, SKTexture texture); -/// An image that can be used with one or more s and particles. -/// -/// Sprite Kit attempts to be efficient with the memory associated with textures. Textures are lazy-loaded from their source files and in preparation for loading onto the graphics hardware. This lazy-loading can be overridden with the Preload* methods. -/// -/// -/// Apple documentation for SKTexture -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -partial interface SKTexture : NSSecureCoding, NSCopying { + [Static, Export ("textureWithCGImage:")] + SKTexture FromImage (CGImage image); - [Static, Export ("textureWithImageNamed:")] - SKTexture FromImageNamed (string name); + [Static, Export ("textureWithImage:")] + SKTexture FromImage (UIImage image); - [Static, Export ("textureWithRect:inTexture:")] - SKTexture FromRectangle (CGRect rect, SKTexture texture); + [Static, Export ("textureWithData:size:")] + SKTexture FromData (NSData pixelData, CGSize size); - [Static, Export ("textureWithCGImage:")] - SKTexture FromImage (CGImage image); + [Static, Export ("textureWithData:size:rowLength:alignment:")] + SKTexture FromData (NSData pixelData, CGSize size, uint /* unsigned int*/ rowLength, uint /* unsigned int */ alignment); - [Static, Export ("textureWithImage:")] - SKTexture FromImage (UIImage image); + [MacCatalyst (13, 1)] + [Export ("textureByApplyingCIFilter:")] + SKTexture TextureByApplyingCIFilter (CIFilter filter); - [Static, Export ("textureWithData:size:")] - SKTexture FromData (NSData pixelData, CGSize size); + [Export ("textureRect")] + CGRect TextureRect { get; } - [Static, Export ("textureWithData:size:rowLength:alignment:")] - SKTexture FromData (NSData pixelData, CGSize size, uint /* unsigned int*/ rowLength, uint /* unsigned int */ alignment); + [Export ("size")] + CGSize Size { get; } - [MacCatalyst (13, 1)] - [Export ("textureByApplyingCIFilter:")] - SKTexture TextureByApplyingCIFilter (CIFilter filter); + [Export ("filteringMode")] + SKTextureFilteringMode FilteringMode { get; set; } - [Export ("textureRect")] - CGRect TextureRect { get; } + [Export ("usesMipmaps")] + bool UsesMipmaps { get; set; } - [Export ("size")] - CGSize Size { get; } + [Static] + [Export ("preloadTextures:withCompletionHandler:")] + [Async] + // note: unlike SKTextureAtlas completion can't be null (or it crash) + void PreloadTextures (SKTexture [] textures, Action completion); - [Export ("filteringMode")] - SKTextureFilteringMode FilteringMode { get; set; } + [Export ("preloadWithCompletionHandler:")] + [Async] + // note: unlike SKTextureAtlas completion can't be null (or it crash) + void Preload (Action completion); - [Export ("usesMipmaps")] - bool UsesMipmaps { get; set; } + [MacCatalyst (13, 1)] + [Export ("textureByGeneratingNormalMap")] + SKTexture CreateTextureByGeneratingNormalMap (); - [Static] - [Export ("preloadTextures:withCompletionHandler:")] - [Async] - // note: unlike SKTextureAtlas completion can't be null (or it crash) - void PreloadTextures (SKTexture [] textures, Action completion); + [MacCatalyst (13, 1)] + [Export ("textureByGeneratingNormalMapWithSmoothness:contrast:")] + SKTexture CreateTextureByGeneratingNormalMap (nfloat smoothness, nfloat contrast); - [Export ("preloadWithCompletionHandler:")] - [Async] - // note: unlike SKTextureAtlas completion can't be null (or it crash) - void Preload (Action completion); + [MacCatalyst (13, 1)] + [Static, Export ("textureVectorNoiseWithSmoothness:size:")] + SKTexture FromTextureVectorNoise (nfloat smoothness, CGSize size); - [MacCatalyst (13, 1)] - [Export ("textureByGeneratingNormalMap")] - SKTexture CreateTextureByGeneratingNormalMap (); + [MacCatalyst (13, 1)] + [Static, Export ("textureNoiseWithSmoothness:size:grayscale:")] + SKTexture FromTextureNoise (nfloat smoothness, CGSize size, bool grayscale); - [MacCatalyst (13, 1)] - [Export ("textureByGeneratingNormalMapWithSmoothness:contrast:")] - SKTexture CreateTextureByGeneratingNormalMap (nfloat smoothness, nfloat contrast); + [MacCatalyst (13, 1)] + [Static, Export ("textureWithData:size:flipped:")] + SKTexture FromData (NSData pixelData, CGSize size, bool flipped); - [MacCatalyst (13, 1)] - [Static, Export ("textureVectorNoiseWithSmoothness:size:")] - SKTexture FromTextureVectorNoise (nfloat smoothness, CGSize size); + [MacCatalyst (13, 1)] + [Export ("CGImage")] + CGImage CGImage { get; } - [MacCatalyst (13, 1)] - [Static, Export ("textureNoiseWithSmoothness:size:grayscale:")] - SKTexture FromTextureNoise (nfloat smoothness, CGSize size, bool grayscale); - - [MacCatalyst (13, 1)] - [Static, Export ("textureWithData:size:flipped:")] - SKTexture FromData (NSData pixelData, CGSize size, bool flipped); + // Static Category from GameplayKit + [MacCatalyst (13, 1)] + [Static] + [Export ("textureWithNoiseMap:")] + SKTexture FromNoiseMap (GKNoiseMap noiseMap); + } - [MacCatalyst (13, 1)] - [Export ("CGImage")] - CGImage CGImage { get; } + /// A method that modifies a texture in place. + delegate void SKTextureModify (IntPtr pixelData, nuint lengthInBytes); - // Static Category from GameplayKit + /// A texture that can be modified after assignment. + /// + /// Apple documentation for SKMutableTexture [MacCatalyst (13, 1)] - [Static] - [Export ("textureWithNoiseMap:")] - SKTexture FromNoiseMap (GKNoiseMap noiseMap); -} - -/// A method that modifies a texture in place. -delegate void SKTextureModify (IntPtr pixelData, nuint lengthInBytes); - -/// A texture that can be modified after assignment. -/// -/// Apple documentation for SKMutableTexture -[MacCatalyst (13, 1)] -[BaseType (typeof (SKTexture))] -[DisableDefaultCtor] // cannot be created (like SKTexture) by calling `init` -interface SKMutableTexture { - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); - - [Export ("initWithSize:pixelFormat:")] - NativeHandle Constructor (CGSize size, CVPixelFormatType pixelFormat); + [BaseType (typeof (SKTexture))] + [DisableDefaultCtor] // cannot be created (like SKTexture) by calling `init` + interface SKMutableTexture { + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [Static, Export ("mutableTextureWithSize:")] - SKMutableTexture Create (CGSize size); + [Export ("initWithSize:pixelFormat:")] + NativeHandle Constructor (CGSize size, CVPixelFormatType pixelFormat); - [Export ("modifyPixelDataWithBlock:")] - void ModifyPixelData (SKTextureModify modifyMethod); -} - -delegate void SKTextureAtlasLoadCallback (NSError error, SKTextureAtlas foundAtlases); - -/// A collection of s that are loaded from a single source. -/// -/// -/// Apple documentation for SKTextureAtlas -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -partial interface SKTextureAtlas : NSSecureCoding { - - [Static, Export ("atlasNamed:")] - SKTextureAtlas FromName (string name); + [Static, Export ("mutableTextureWithSize:")] + SKMutableTexture Create (CGSize size); - [Export ("textureNamed:")] - SKTexture TextureNamed (string name); - - [Export ("textureNames")] - string [] TextureNames { get; } + [Export ("modifyPixelDataWithBlock:")] + void ModifyPixelData (SKTextureModify modifyMethod); + } - [Static] - [Export ("preloadTextureAtlases:withCompletionHandler:")] - [Async] - // Unfortunate name, should have been PreloadTextureAtlases - void PreloadTextures (SKTextureAtlas [] textures, Action completion); + delegate void SKTextureAtlasLoadCallback (NSError error, SKTextureAtlas foundAtlases); + /// A collection of s that are loaded from a single source. + /// + /// + /// Apple documentation for SKTextureAtlas [MacCatalyst (13, 1)] - [Static] - [Export ("preloadTextureAtlasesNamed:withCompletionHandler:")] - [Async (ResultTypeName = "SKTextureAtlasLoadResult")] - void PreloadTextureAtlases (string [] atlasNames, SKTextureAtlasLoadCallback completionHandler); + [BaseType (typeof (NSObject))] + partial interface SKTextureAtlas : NSSecureCoding { - [Export ("preloadWithCompletionHandler:")] - [Async] - void Preload (Action completion); + [Static, Export ("atlasNamed:")] + SKTextureAtlas FromName (string name); - [MacCatalyst (13, 1)] - [Static, Export ("atlasWithDictionary:")] - SKTextureAtlas FromDictionary (NSDictionary properties); + [Export ("textureNamed:")] + SKTexture TextureNamed (string name); -} + [Export ("textureNames")] + string [] TextureNames { get; } -/// Holds shareable uniform data for SKShader objects. -/// -/// Apple documentation for SKUniform -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKUniform : NSCopying, NSSecureCoding { - [Export ("initWithName:")] - NativeHandle Constructor (string name); + [Static] + [Export ("preloadTextureAtlases:withCompletionHandler:")] + [Async] + // Unfortunate name, should have been PreloadTextureAtlases + void PreloadTextures (SKTextureAtlas [] textures, Action completion); - [Export ("initWithName:texture:")] - NativeHandle Constructor (string name, [NullAllowed] SKTexture texture); + [MacCatalyst (13, 1)] + [Static] + [Export ("preloadTextureAtlasesNamed:withCompletionHandler:")] + [Async (ResultTypeName = "SKTextureAtlasLoadResult")] + void PreloadTextureAtlases (string [] atlasNames, SKTextureAtlasLoadCallback completionHandler); - [Export ("initWithName:float:")] - NativeHandle Constructor (string name, float /* float, not CGFloat */ value); + [Export ("preloadWithCompletionHandler:")] + [Async] + void Preload (Action completion); - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector2:")] - IntPtr InitWithNameFloatVector2 (string name, Vector2 value); + [MacCatalyst (13, 1)] + [Static, Export ("atlasWithDictionary:")] + SKTextureAtlas FromDictionary (NSDictionary properties); - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [MarshalNativeExceptions] - [Internal] - IntPtr InitWithNameVectorFloat2 (string name, Vector2 value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector3:")] - IntPtr InitWithNameFloatVector3 (string name, Vector3 value); - - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameVectorFloat3 (string name, Vector3 value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector4:")] - IntPtr InitWithNameFloatVector4 (string name, Vector4 value); + } - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameVectorFloat4 (string name, Vector4 value); + /// Holds shareable uniform data for SKShader objects. + /// + /// Apple documentation for SKUniform + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKUniform : NSCopying, NSSecureCoding { + [Export ("initWithName:")] + NativeHandle Constructor (string name); + + [Export ("initWithName:texture:")] + NativeHandle Constructor (string name, [NullAllowed] SKTexture texture); + + [Export ("initWithName:float:")] + NativeHandle Constructor (string name, float /* float, not CGFloat */ value); + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector2:")] + IntPtr InitWithNameFloatVector2 (string name, Vector2 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [MarshalNativeExceptions] + [Internal] + IntPtr InitWithNameVectorFloat2 (string name, Vector2 value); + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector3:")] + IntPtr InitWithNameFloatVector3 (string name, Vector3 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [Internal] + IntPtr InitWithNameVectorFloat3 (string name, Vector3 value); + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector4:")] + IntPtr InitWithNameFloatVector4 (string name, Vector4 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [Internal] + IntPtr InitWithNameVectorFloat4 (string name, Vector4 value); #if !NET [Internal] @@ -1867,10 +1867,10 @@ interface SKUniform : NSCopying, NSSecureCoding { IntPtr InitWithNameMatrixFloat2x2 (string name, Matrix2 value); #endif // !NET - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat2x2 value); + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat2x2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + NativeHandle Constructor (string name, MatrixFloat2x2 value); #if !NET [Internal] @@ -1888,10 +1888,10 @@ interface SKUniform : NSCopying, NSSecureCoding { IntPtr InitWithNameMatrixFloat3x3 (string name, Matrix3 value); #endif // !NET - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat3x3 value); + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat3x3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + NativeHandle Constructor (string name, MatrixFloat3x3 value); #if !NET [Internal] @@ -1911,80 +1911,80 @@ interface SKUniform : NSCopying, NSSecureCoding { IntPtr InitWithNameMatrixFloat4x4 (string name, Matrix4 value); #endif // !NET - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat4x4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat4x4 value); - - [Export ("name")] - string Name { get; } - - [Export ("uniformType")] - SKUniformType UniformType { get; } - - [Export ("textureValue")] - [NullAllowed] - SKTexture TextureValue { get; set; } - - [Export ("floatValue")] - float FloatValue { get; set; } /* float, not CGFloat */ - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector2Value")] - Vector2 _FloatVector2Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] - [Internal] - Vector2 _VectorFloat2Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector3Value")] - Vector3 _FloatVector3Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] - [Internal] - Vector3 _VectorFloat3Value { + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat4x4:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector4Value")] - Vector4 _FloatVector4Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] - [Internal] - Vector4 _VectorFloat4Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + NativeHandle Constructor (string name, MatrixFloat4x4 value); + + [Export ("name")] + string Name { get; } + + [Export ("uniformType")] + SKUniformType UniformType { get; } + + [Export ("textureValue")] + [NullAllowed] + SKTexture TextureValue { get; set; } + + [Export ("floatValue")] + float FloatValue { get; set; } /* float, not CGFloat */ + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector2Value")] + Vector2 _FloatVector2Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] + [Internal] + Vector2 _VectorFloat2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector3Value")] + Vector3 _FloatVector3Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] + [Internal] + Vector3 _VectorFloat3Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector4Value")] + Vector4 _FloatVector4Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] + [Internal] + Vector4 _VectorFloat4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } #if !NET [Internal] @@ -1995,14 +1995,14 @@ Vector4 _VectorFloat4Value { Matrix2 _FloatMatrix2Value { get; set; } #endif // !NET - [MacCatalyst (13, 1)] - [Export ("matrixFloat2x2Value", ArgumentSemantic.Assign)] - MatrixFloat2x2 MatrixFloat2x2Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [MacCatalyst (13, 1)] + [Export ("matrixFloat2x2Value", ArgumentSemantic.Assign)] + MatrixFloat2x2 MatrixFloat2x2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } #if !NET [Internal] @@ -2013,14 +2013,14 @@ MatrixFloat2x2 MatrixFloat2x2Value { Matrix3 _FloatMatrix3Value { get; set; } #endif // !NET - [MacCatalyst (13, 1)] - [Export ("matrixFloat3x3Value", ArgumentSemantic.Assign)] - MatrixFloat3x3 MatrixFloat3x3Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [MacCatalyst (13, 1)] + [Export ("matrixFloat3x3Value", ArgumentSemantic.Assign)] + MatrixFloat3x3 MatrixFloat3x3Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } #if !NET [Internal] @@ -2031,42 +2031,42 @@ MatrixFloat3x3 MatrixFloat3x3Value { Matrix4 _FloatMatrix4Value { get; set; } #endif // !NET - [MacCatalyst (13, 1)] - [Export ("matrixFloat4x4Value", ArgumentSemantic.Assign)] - MatrixFloat4x4 MatrixFloat4x4Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [MacCatalyst (13, 1)] + [Export ("matrixFloat4x4Value", ArgumentSemantic.Assign)] + MatrixFloat4x4 MatrixFloat4x4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } - [Static, Export ("uniformWithName:")] - SKUniform Create (string name); + [Static, Export ("uniformWithName:")] + SKUniform Create (string name); - [Static, Export ("uniformWithName:texture:")] - SKUniform Create (string name, [NullAllowed] SKTexture texture); + [Static, Export ("uniformWithName:texture:")] + SKUniform Create (string name, [NullAllowed] SKTexture texture); - [Static, Export ("uniformWithName:float:")] - SKUniform Create (string name, float /* float, not CGFloat */ value); + [Static, Export ("uniformWithName:float:")] + SKUniform Create (string name, float /* float, not CGFloat */ value); - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [MarshalNativeExceptions] - SKUniform Create (string name, Vector2 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [MarshalNativeExceptions] + SKUniform Create (string name, Vector2 value); - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Vector3 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, Vector3 value); - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Vector4 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, Vector4 value); #if !NET [Obsolete ("Use the '(string, MatrixFloat2x2)' overload instead.")] @@ -2076,11 +2076,11 @@ MatrixFloat4x4 MatrixFloat4x4Value { SKUniform Create (string name, Matrix2 value); #endif // !NET - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat2x2 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat2x2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, MatrixFloat2x2 value); #if !NET [Obsolete ("Use the '(string, MatrixFloat3x3)' overload instead.")] @@ -2090,11 +2090,11 @@ MatrixFloat4x4 MatrixFloat4x4Value { SKUniform Create (string name, Matrix3 value); #endif - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat3x3 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat3x3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, MatrixFloat3x3 value); #if !NET [Obsolete ("Use 'the '(string, MatrixFloat4x4)' overload instead.")] @@ -2104,1415 +2104,1415 @@ MatrixFloat4x4 MatrixFloat4x4Value { SKUniform Create (string name, Matrix4 value); #endif // !NET - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat4x4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat4x4 value); -} + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat4x4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, MatrixFloat4x4 value); + } -/// The delegate for a custom action, used with . -delegate void SKActionDurationHandler (SKNode node, nfloat elapsedTime); + /// The delegate for a custom action, used with . + delegate void SKActionDurationHandler (SKNode node, nfloat elapsedTime); -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] // To create an action, call the class method for the action you are interested in. -partial interface SKAction : NSSecureCoding, NSCopying { + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] // To create an action, call the class method for the action you are interested in. + partial interface SKAction : NSSecureCoding, NSCopying { - [Export ("duration")] - double Duration { get; set; } + [Export ("duration")] + double Duration { get; set; } - [Export ("timingMode")] - SKActionTimingMode TimingMode { get; set; } + [Export ("timingMode")] + SKActionTimingMode TimingMode { get; set; } - [Export ("speed")] - nfloat Speed { get; set; } + [Export ("speed")] + nfloat Speed { get; set; } - [Export ("reversedAction")] - SKAction ReversedAction { get; } + [Export ("reversedAction")] + SKAction ReversedAction { get; } - // These are in a category - [Static, Export ("moveByX:y:duration:")] - SKAction MoveBy (nfloat deltaX, nfloat deltaY, double sec); + // These are in a category + [Static, Export ("moveByX:y:duration:")] + SKAction MoveBy (nfloat deltaX, nfloat deltaY, double sec); - [Static, Export ("moveBy:duration:")] - SKAction MoveBy (CGVector delta, double duration); + [Static, Export ("moveBy:duration:")] + SKAction MoveBy (CGVector delta, double duration); - [Static, Export ("moveTo:duration:")] - SKAction MoveTo (CGPoint location, double sec); + [Static, Export ("moveTo:duration:")] + SKAction MoveTo (CGPoint location, double sec); - [Static, Export ("moveToX:duration:")] - SKAction MoveToX (nfloat x, double sec); + [Static, Export ("moveToX:duration:")] + SKAction MoveToX (nfloat x, double sec); - [Static, Export ("moveToY:duration:")] - SKAction MoveToY (nfloat y, double sec); + [Static, Export ("moveToY:duration:")] + SKAction MoveToY (nfloat y, double sec); - [Static, Export ("rotateByAngle:duration:")] - SKAction RotateByAngle (nfloat radians, double sec); + [Static, Export ("rotateByAngle:duration:")] + SKAction RotateByAngle (nfloat radians, double sec); - [Static, Export ("rotateToAngle:duration:")] - SKAction RotateToAngle (nfloat radians, double sec); + [Static, Export ("rotateToAngle:duration:")] + SKAction RotateToAngle (nfloat radians, double sec); - [Static, Export ("rotateToAngle:duration:shortestUnitArc:")] - SKAction RotateToAngle (nfloat radians, double sec, bool shortedUnitArc); + [Static, Export ("rotateToAngle:duration:shortestUnitArc:")] + SKAction RotateToAngle (nfloat radians, double sec, bool shortedUnitArc); - [Static, Export ("resizeByWidth:height:duration:")] - SKAction ResizeByWidth (nfloat width, nfloat height, double duration); + [Static, Export ("resizeByWidth:height:duration:")] + SKAction ResizeByWidth (nfloat width, nfloat height, double duration); - [Static, Export ("resizeToWidth:height:duration:")] - SKAction ResizeTo (nfloat width, nfloat height, double duration); + [Static, Export ("resizeToWidth:height:duration:")] + SKAction ResizeTo (nfloat width, nfloat height, double duration); - [Static, Export ("resizeToWidth:duration:")] - SKAction ResizeToWidth (nfloat width, double duration); + [Static, Export ("resizeToWidth:duration:")] + SKAction ResizeToWidth (nfloat width, double duration); - [Static, Export ("resizeToHeight:duration:")] - SKAction ResizeToHeight (nfloat height, double duration); + [Static, Export ("resizeToHeight:duration:")] + SKAction ResizeToHeight (nfloat height, double duration); - [Static, Export ("scaleBy:duration:")] - SKAction ScaleBy (nfloat scale, double sec); + [Static, Export ("scaleBy:duration:")] + SKAction ScaleBy (nfloat scale, double sec); - [Static, Export ("scaleXBy:y:duration:")] - SKAction ScaleBy (nfloat xScale, nfloat yScale, double sec); + [Static, Export ("scaleXBy:y:duration:")] + SKAction ScaleBy (nfloat xScale, nfloat yScale, double sec); - [Static, Export ("scaleTo:duration:")] - SKAction ScaleTo (nfloat scale, double sec); + [Static, Export ("scaleTo:duration:")] + SKAction ScaleTo (nfloat scale, double sec); - [Static, Export ("scaleXTo:y:duration:")] - SKAction ScaleTo (nfloat xScale, nfloat yScale, double sec); + [Static, Export ("scaleXTo:y:duration:")] + SKAction ScaleTo (nfloat xScale, nfloat yScale, double sec); - [Static, Export ("scaleXTo:duration:")] - SKAction ScaleXTo (nfloat scale, double sec); + [Static, Export ("scaleXTo:duration:")] + SKAction ScaleXTo (nfloat scale, double sec); - [Static, Export ("scaleYTo:duration:")] - SKAction ScaleYTo (nfloat scale, double sec); + [Static, Export ("scaleYTo:duration:")] + SKAction ScaleYTo (nfloat scale, double sec); - [MacCatalyst (13, 1)] - [Static] - [Export ("scaleToSize:duration:")] - SKAction ScaleTo (CGSize size, double sec); + [MacCatalyst (13, 1)] + [Static] + [Export ("scaleToSize:duration:")] + SKAction ScaleTo (CGSize size, double sec); - [Static, Export ("sequence:")] - SKAction Sequence ([Params] SKAction [] actions); + [Static, Export ("sequence:")] + SKAction Sequence ([Params] SKAction [] actions); - [Static, Export ("group:")] - SKAction Group ([Params] SKAction [] actions); + [Static, Export ("group:")] + SKAction Group ([Params] SKAction [] actions); - [Static, Export ("repeatAction:count:")] - SKAction RepeatAction (SKAction action, nuint count); + [Static, Export ("repeatAction:count:")] + SKAction RepeatAction (SKAction action, nuint count); - [Static, Export ("repeatActionForever:")] - SKAction RepeatActionForever (SKAction action); + [Static, Export ("repeatActionForever:")] + SKAction RepeatActionForever (SKAction action); - [Static, Export ("fadeInWithDuration:")] - SKAction FadeInWithDuration (double sec); + [Static, Export ("fadeInWithDuration:")] + SKAction FadeInWithDuration (double sec); - [Static, Export ("fadeOutWithDuration:")] - SKAction FadeOutWithDuration (double sec); + [Static, Export ("fadeOutWithDuration:")] + SKAction FadeOutWithDuration (double sec); - [Static, Export ("fadeAlphaBy:duration:")] - SKAction FadeAlphaBy (nfloat factor, double sec); + [Static, Export ("fadeAlphaBy:duration:")] + SKAction FadeAlphaBy (nfloat factor, double sec); - [Static, Export ("fadeAlphaTo:duration:")] - SKAction FadeAlphaTo (nfloat alpha, double sec); + [Static, Export ("fadeAlphaTo:duration:")] + SKAction FadeAlphaTo (nfloat alpha, double sec); - [MacCatalyst (13, 1)] - [Static, Export ("setTexture:")] - SKAction SetTexture (SKTexture texture); + [MacCatalyst (13, 1)] + [Static, Export ("setTexture:")] + SKAction SetTexture (SKTexture texture); - [MacCatalyst (13, 1)] - [Static, Export ("setTexture:resize:")] - SKAction SetTexture (SKTexture texture, bool resize); + [MacCatalyst (13, 1)] + [Static, Export ("setTexture:resize:")] + SKAction SetTexture (SKTexture texture, bool resize); - [Static, Export ("animateWithTextures:timePerFrame:")] - SKAction AnimateWithTextures (SKTexture [] textures, double sec); + [Static, Export ("animateWithTextures:timePerFrame:")] + SKAction AnimateWithTextures (SKTexture [] textures, double sec); - [Static, Export ("animateWithTextures:timePerFrame:resize:restore:")] - SKAction AnimateWithTextures (SKTexture [] textures, double sec, bool resize, bool restore); + [Static, Export ("animateWithTextures:timePerFrame:resize:restore:")] + SKAction AnimateWithTextures (SKTexture [] textures, double sec, bool resize, bool restore); - [Static, Export ("playSoundFileNamed:waitForCompletion:")] - SKAction PlaySoundFileNamed (string soundFile, bool wait); + [Static, Export ("playSoundFileNamed:waitForCompletion:")] + SKAction PlaySoundFileNamed (string soundFile, bool wait); - [Static, Export ("colorizeWithColor:colorBlendFactor:duration:")] - SKAction ColorizeWithColor (UIColor color, nfloat colorBlendFactor, double sec); + [Static, Export ("colorizeWithColor:colorBlendFactor:duration:")] + SKAction ColorizeWithColor (UIColor color, nfloat colorBlendFactor, double sec); - [Static, Export ("colorizeWithColorBlendFactor:duration:")] - SKAction ColorizeWithColorBlendFactor (nfloat colorBlendFactor, double sec); + [Static, Export ("colorizeWithColorBlendFactor:duration:")] + SKAction ColorizeWithColorBlendFactor (nfloat colorBlendFactor, double sec); - [Static, Export ("followPath:duration:")] - SKAction FollowPath (CGPath path, double sec); + [Static, Export ("followPath:duration:")] + SKAction FollowPath (CGPath path, double sec); - [Static, Export ("followPath:asOffset:orientToPath:duration:")] + [Static, Export ("followPath:asOffset:orientToPath:duration:")] #if XAMCORE_5_0 SKAction FollowPath (CGPath path, bool offset, bool orientToPath, double sec); #else - SKAction FollowPath (CGPath path, bool offset, bool orient, double sec); + SKAction FollowPath (CGPath path, bool offset, bool orient, double sec); #endif - [MacCatalyst (13, 1)] - [Static, Export ("followPath:speed:")] - SKAction FollowPath (CGPath path, nfloat speed); + [MacCatalyst (13, 1)] + [Static, Export ("followPath:speed:")] + SKAction FollowPath (CGPath path, nfloat speed); - [MacCatalyst (13, 1)] - [Static, Export ("followPath:asOffset:orientToPath:speed:")] + [MacCatalyst (13, 1)] + [Static, Export ("followPath:asOffset:orientToPath:speed:")] #if XAMCORE_5_0 SKAction FollowPath (CGPath path, bool offset, bool orientToPath, nfloat speed); #else - SKAction FollowPath (CGPath path, bool offset, bool orient, nfloat speed); + SKAction FollowPath (CGPath path, bool offset, bool orient, nfloat speed); #endif - [Static, Export ("speedBy:duration:")] - SKAction SpeedBy (nfloat speed, double sec); - - [Static, Export ("speedTo:duration:")] - SKAction SpeedTo (nfloat speed, double sec); - - [Static, Export ("waitForDuration:")] - SKAction WaitForDuration (double sec); - - [Static, Export ("waitForDuration:withRange:")] - SKAction WaitForDuration (double sec, double durationRange); - - [Static, Export ("removeFromParent")] - SKAction RemoveFromParent (); + [Static, Export ("speedBy:duration:")] + SKAction SpeedBy (nfloat speed, double sec); - [Static, Export ("performSelector:onTarget:")] - SKAction PerformSelector (Selector selector, NSObject target); + [Static, Export ("speedTo:duration:")] + SKAction SpeedTo (nfloat speed, double sec); - [Static, Export ("runBlock:")] - SKAction Run (Action block); + [Static, Export ("waitForDuration:")] + SKAction WaitForDuration (double sec); - [Static, Export ("runBlock:queue:")] - SKAction Run (Action block, DispatchQueue queue); + [Static, Export ("waitForDuration:withRange:")] + SKAction WaitForDuration (double sec, double durationRange); + + [Static, Export ("removeFromParent")] + SKAction RemoveFromParent (); + + [Static, Export ("performSelector:onTarget:")] + SKAction PerformSelector (Selector selector, NSObject target); - [Static, Export ("runAction:onChildWithName:")] - SKAction RunAction (SKAction action, string name); - - [Static, Export ("customActionWithDuration:actionBlock:")] - SKAction CustomActionWithDuration (double seconds, SKActionDurationHandler actionHandler); + [Static, Export ("runBlock:")] + SKAction Run (Action block); + + [Static, Export ("runBlock:queue:")] + SKAction Run (Action block, DispatchQueue queue); + + [Static, Export ("runAction:onChildWithName:")] + SKAction RunAction (SKAction action, string name); + + [Static, Export ("customActionWithDuration:actionBlock:")] + SKAction CustomActionWithDuration (double seconds, SKActionDurationHandler actionHandler); + + // + // iOS 8 cluster (a few more are above, as part of their family + // + [MacCatalyst (13, 1)] + [Static, Export ("hide")] + SKAction Hide (); + + [MacCatalyst (13, 1)] + [Static, Export ("unhide")] + SKAction Unhide (); + + [MacCatalyst (13, 1)] + [Static, Export ("reachTo:rootNode:duration:")] + SKAction ReachTo (CGPoint position, SKNode rootNode, double secs); + + [MacCatalyst (13, 1)] + [Static, Export ("reachTo:rootNode:velocity:")] + SKAction ReachTo (CGPoint position, SKNode rootNode, nfloat velocity); + + [MacCatalyst (13, 1)] + [Static, Export ("reachToNode:rootNode:duration:")] + SKAction ReachToNode (SKNode node, SKNode rootNode, double sec); + + [MacCatalyst (13, 1)] + [Static, Export ("reachToNode:rootNode:velocity:")] + SKAction ReachToNode (SKNode node, SKNode rootNode, nfloat velocity); + + [MacCatalyst (13, 1)] + [Static, Export ("strengthTo:duration:")] + SKAction StrengthTo (float /* float, not CGFloat */ strength, double sec); + + [MacCatalyst (13, 1)] + [Static, Export ("strengthBy:duration:")] + SKAction StrengthBy (float /* float, not CGFloat */ strength, double sec); + + [MacCatalyst (13, 1)] + [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] + SKActionTimingFunction2 TimingFunction2 { get; set; } + + [MacCatalyst (13, 1)] + [Static, Export ("falloffBy:duration:")] + SKAction FalloffBy (float /* float, not CGFloat */ to, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("falloffTo:duration:")] + SKAction FalloffTo (float falloff, double sec); + + // iOS 9 cluster + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:")] + [return: NullAllowed] + SKAction Create (string name); + + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:duration:")] + [return: NullAllowed] + SKAction Create (string name, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:fromURL:")] + [return: NullAllowed] + SKAction Create (string name, NSUrl url); + + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:fromURL:duration:")] + [return: NullAllowed] + SKAction Create (string name, NSUrl url, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("setNormalTexture:")] + SKAction SetNormalTexture (SKTexture texture); + + [MacCatalyst (13, 1)] + [Static] + [Export ("setNormalTexture:resize:")] + SKAction SetNormalTexture (SKTexture texture, bool resize); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithNormalTextures:timePerFrame:")] + SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithNormalTextures:timePerFrame:resize:restore:")] + SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame, bool resize, bool restore); + + [MacCatalyst (13, 1)] + [Static] + [Export ("play")] + SKAction CreatePlay (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("pause")] + SKAction CreatePause (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("stop")] + SKAction CreateStop (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changePlaybackRateTo:duration:")] + SKAction CreateChangePlaybackRate (float playbackRate, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changePlaybackRateBy:duration:")] + SKAction CreateChangePlaybackRateBy (float playbackRate, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeVolumeTo:duration:")] + SKAction CreateChangeVolume (float newVolume, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeVolumeBy:duration:")] + SKAction CreateChangeVolumeBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeChargeTo:duration:")] + SKAction CreateChangeChargeTo (float newCharge, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeChargeBy:duration:")] + SKAction CreateChangeChargeBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeMassTo:duration:")] + SKAction CreateChangeMassTo (float newMass, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeMassBy:duration:")] + SKAction CreateChangeMassBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyForce:duration:")] + SKAction CreateApplyForce (CGVector force, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyForce:atPoint:duration:")] + SKAction CreateApplyForce (CGVector force, CGPoint point, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyTorque:duration:")] + SKAction CreateApplyTorque (nfloat torque, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyImpulse:duration:")] + SKAction CreateApplyImpulse (CGVector impulse, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyImpulse:atPoint:duration:")] + SKAction CreateApplyImpulse (CGVector impulse, CGPoint point, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyAngularImpulse:duration:")] + SKAction CreateApplyAngularImpulse (nfloat impulse, double duration); + + // SKAction_SKAudioNode inlined + + [MacCatalyst (13, 1)] + [Static] + [Export ("stereoPanTo:duration:")] + SKAction CreateStereoPanTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("stereoPanBy:duration:")] + SKAction CreateStereoPanBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeReverbTo:duration:")] + SKAction CreateChangeReverbTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeReverbBy:duration:")] + SKAction CreateChangeReverbBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeObstructionTo:duration:")] + SKAction CreateChangeObstructionTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeObstructionBy:duration:")] + SKAction CreateChangeObstructionBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeOcclusionTo:duration:")] + SKAction CreateChangeOcclusionTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeOcclusionBy:duration:")] + SKAction CreateChangeOcclusionBy (float by, double duration); + + // SKAction_SKWarpable + + [MacCatalyst (13, 1)] + [Static] + [Export ("warpTo:duration:")] + [return: NullAllowed] + SKAction WarpTo (SKWarpGeometry warp, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithWarps:times:")] + [return: NullAllowed] + SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithWarps:times:restore:")] + [return: NullAllowed] + SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times, bool restore); + } - // - // iOS 8 cluster (a few more are above, as part of their family - // + /// [MacCatalyst (13, 1)] - [Static, Export ("hide")] - SKAction Hide (); + [DisableDefaultCtor] // see https://bugzilla.xamarin.com/show_bug.cgi?id=14502 + [BaseType (typeof (NSObject))] + partial interface SKPhysicsBody : NSSecureCoding, NSCopying { - [MacCatalyst (13, 1)] - [Static, Export ("unhide")] - SKAction Unhide (); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithBodies:")] + SKPhysicsBody FromBodies (SKPhysicsBody [] bodies); - [MacCatalyst (13, 1)] - [Static, Export ("reachTo:rootNode:duration:")] - SKAction ReachTo (CGPoint position, SKNode rootNode, double secs); + [Static, Export ("bodyWithCircleOfRadius:")] + SKPhysicsBody CreateCircularBody (nfloat radius); - [MacCatalyst (13, 1)] - [Static, Export ("reachTo:rootNode:velocity:")] - SKAction ReachTo (CGPoint position, SKNode rootNode, nfloat velocity); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithCircleOfRadius:center:")] + SKPhysicsBody CreateCircularBody (nfloat radius, CGPoint center); - [MacCatalyst (13, 1)] - [Static, Export ("reachToNode:rootNode:duration:")] - SKAction ReachToNode (SKNode node, SKNode rootNode, double sec); + [Static, Export ("bodyWithRectangleOfSize:")] + SKPhysicsBody CreateRectangularBody (CGSize size); - [MacCatalyst (13, 1)] - [Static, Export ("reachToNode:rootNode:velocity:")] - SKAction ReachToNode (SKNode node, SKNode rootNode, nfloat velocity); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithRectangleOfSize:center:")] + SKPhysicsBody CreateRectangularBody (CGSize size, CGPoint center); - [MacCatalyst (13, 1)] - [Static, Export ("strengthTo:duration:")] - SKAction StrengthTo (float /* float, not CGFloat */ strength, double sec); + [Static, Export ("bodyWithPolygonFromPath:")] + SKPhysicsBody CreateBodyFromPath (CGPath path); - [MacCatalyst (13, 1)] - [Static, Export ("strengthBy:duration:")] - SKAction StrengthBy (float /* float, not CGFloat */ strength, double sec); + [Static, Export ("bodyWithEdgeFromPoint:toPoint:")] + SKPhysicsBody CreateEdge (CGPoint fromPoint, CGPoint toPoint); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] - SKActionTimingFunction2 TimingFunction2 { get; set; } + [Static, Export ("bodyWithEdgeChainFromPath:")] + SKPhysicsBody CreateEdgeChain (CGPath path); - [MacCatalyst (13, 1)] - [Static, Export ("falloffBy:duration:")] - SKAction FalloffBy (float /* float, not CGFloat */ to, double duration); + [Static, Export ("bodyWithEdgeLoopFromPath:")] + SKPhysicsBody CreateEdgeLoop (CGPath path); - [MacCatalyst (13, 1)] - [Static] - [Export ("falloffTo:duration:")] - SKAction FalloffTo (float falloff, double sec); + [Static, Export ("bodyWithEdgeLoopFromRect:")] + SKPhysicsBody CreateEdgeLoop (CGRect rect); - // iOS 9 cluster - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:")] - [return: NullAllowed] - SKAction Create (string name); + [Export ("dynamic")] + bool Dynamic { [Bind ("isDynamic")] get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:duration:")] - [return: NullAllowed] - SKAction Create (string name, double duration); + [Export ("usesPreciseCollisionDetection")] + bool UsesPreciseCollisionDetection { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:fromURL:")] - [return: NullAllowed] - SKAction Create (string name, NSUrl url); + [Export ("allowsRotation")] + bool AllowsRotation { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:fromURL:duration:")] - [return: NullAllowed] - SKAction Create (string name, NSUrl url, double duration); + [Export ("resting")] + bool Resting { [Bind ("isResting")] get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("setNormalTexture:")] - SKAction SetNormalTexture (SKTexture texture); + [Export ("friction")] + nfloat Friction { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("setNormalTexture:resize:")] - SKAction SetNormalTexture (SKTexture texture, bool resize); + [Export ("restitution")] + nfloat Restitution { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithNormalTextures:timePerFrame:")] - SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame); + [Export ("linearDamping", ArgumentSemantic.Assign)] + nfloat LinearDamping { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithNormalTextures:timePerFrame:resize:restore:")] - SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame, bool resize, bool restore); + [Export ("angularDamping", ArgumentSemantic.Assign)] + nfloat AngularDamping { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("play")] - SKAction CreatePlay (); + [Export ("density")] + nfloat Density { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("pause")] - SKAction CreatePause (); + [Export ("mass")] + nfloat Mass { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("stop")] - SKAction CreateStop (); + [Export ("area")] + nfloat Area { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changePlaybackRateTo:duration:")] - SKAction CreateChangePlaybackRate (float playbackRate, double duration); + [Export ("affectedByGravity", ArgumentSemantic.Assign)] + bool AffectedByGravity { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changePlaybackRateBy:duration:")] - SKAction CreateChangePlaybackRateBy (float playbackRate, double duration); + [Export ("categoryBitMask", ArgumentSemantic.Assign)] + uint CategoryBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeVolumeTo:duration:")] - SKAction CreateChangeVolume (float newVolume, double duration); + [Export ("collisionBitMask", ArgumentSemantic.Assign)] + uint CollisionBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeVolumeBy:duration:")] - SKAction CreateChangeVolumeBy (float by, double duration); + [Export ("contactTestBitMask", ArgumentSemantic.Assign)] + uint ContactTestBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeChargeTo:duration:")] - SKAction CreateChangeChargeTo (float newCharge, double duration); + [Export ("joints")] + SKPhysicsJoint [] Joints { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeChargeBy:duration:")] - SKAction CreateChangeChargeBy (float by, double duration); + [Export ("node", ArgumentSemantic.Weak)] + [NullAllowed] + SKNode Node { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeMassTo:duration:")] - SKAction CreateChangeMassTo (float newMass, double duration); + [Export ("velocity")] + CGVector Velocity { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeMassBy:duration:")] - SKAction CreateChangeMassBy (float by, double duration); + [Export ("angularVelocity")] + nfloat AngularVelocity { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("applyForce:duration:")] - SKAction CreateApplyForce (CGVector force, double duration); + [Export ("applyForce:")] + void ApplyForce (CGVector force); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyForce:atPoint:duration:")] - SKAction CreateApplyForce (CGVector force, CGPoint point, double duration); + [Export ("applyForce:atPoint:")] + void ApplyForce (CGVector force, CGPoint point); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyTorque:duration:")] - SKAction CreateApplyTorque (nfloat torque, double duration); + [Export ("applyTorque:")] + void ApplyTorque (nfloat torque); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyImpulse:duration:")] - SKAction CreateApplyImpulse (CGVector impulse, double duration); + [Export ("applyImpulse:")] + void ApplyImpulse (CGVector impulse); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyImpulse:atPoint:duration:")] - SKAction CreateApplyImpulse (CGVector impulse, CGPoint point, double duration); + [Export ("applyImpulse:atPoint:")] + void ApplyImpulse (CGVector impulse, CGPoint point); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyAngularImpulse:duration:")] - SKAction CreateApplyAngularImpulse (nfloat impulse, double duration); + [Export ("applyAngularImpulse:")] + void ApplyAngularImpulse (nfloat impulse); - // SKAction_SKAudioNode inlined + [Export ("allContactedBodies")] + SKPhysicsBody [] AllContactedBodies { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("stereoPanTo:duration:")] - SKAction CreateStereoPanTo (float target, double duration); + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithTexture:size:")] + SKPhysicsBody Create (SKTexture texture, CGSize size); - [MacCatalyst (13, 1)] - [Static] - [Export ("stereoPanBy:duration:")] - SKAction CreateStereoPanBy (float by, double duration); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithTexture:alphaThreshold:size:")] + SKPhysicsBody Create (SKTexture texture, float /* float, not CGFloat */ alphaThreshold, CGSize size); - [MacCatalyst (13, 1)] - [Static] - [Export ("changeReverbTo:duration:")] - SKAction CreateChangeReverbTo (float target, double duration); + [MacCatalyst (13, 1)] + [Export ("charge")] + nfloat Charge { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeReverbBy:duration:")] - SKAction CreateChangeReverbBy (float by, double duration); + [MacCatalyst (13, 1)] + [Export ("fieldBitMask")] + uint FieldBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeObstructionTo:duration:")] - SKAction CreateChangeObstructionTo (float target, double duration); + [MacCatalyst (13, 1)] + [Export ("pinned")] + bool Pinned { get; set; } + } + /// Encapsulates the data of a collision between two s. + /// + /// + /// Apple documentation for SKPhysicsContact [MacCatalyst (13, 1)] - [Static] - [Export ("changeObstructionBy:duration:")] - SKAction CreateChangeObstructionBy (float by, double duration); + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] // An SKPhysicsContact object is created automatically by Scene Kit + partial interface SKPhysicsContact { - [MacCatalyst (13, 1)] - [Static] - [Export ("changeOcclusionTo:duration:")] - SKAction CreateChangeOcclusionTo (float target, double duration); + [Export ("bodyA")] + SKPhysicsBody BodyA { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeOcclusionBy:duration:")] - SKAction CreateChangeOcclusionBy (float by, double duration); + [Export ("bodyB")] + SKPhysicsBody BodyB { get; } - // SKAction_SKWarpable + [Export ("contactPoint")] + CGPoint ContactPoint { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("warpTo:duration:")] - [return: NullAllowed] - SKAction WarpTo (SKWarpGeometry warp, double duration); + [Export ("collisionImpulse")] + nfloat CollisionImpulse { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithWarps:times:")] - [return: NullAllowed] - SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times); + [MacCatalyst (13, 1)] + [Export ("contactNormal")] + CGVector ContactNormal { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithWarps:times:restore:")] - [return: NullAllowed] - SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times, bool restore); -} + } -/// -[MacCatalyst (13, 1)] -[DisableDefaultCtor] // see https://bugzilla.xamarin.com/show_bug.cgi?id=14502 -[BaseType (typeof (NSObject))] -partial interface SKPhysicsBody : NSSecureCoding, NSCopying { + /// Interface representing the required methods (if any) of the protocol . + /// + /// This interface contains the required methods (if any) from the protocol defined by . + /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. + /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. + /// + interface ISKPhysicsContactDelegate { } + /// [MacCatalyst (13, 1)] - [Static, Export ("bodyWithBodies:")] - SKPhysicsBody FromBodies (SKPhysicsBody [] bodies); + [BaseType (typeof (NSObject))] + [Model] + [Protocol] + partial interface SKPhysicsContactDelegate { - [Static, Export ("bodyWithCircleOfRadius:")] - SKPhysicsBody CreateCircularBody (nfloat radius); + [Export ("didBeginContact:")] + void DidBeginContact (SKPhysicsContact contact); - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithCircleOfRadius:center:")] - SKPhysicsBody CreateCircularBody (nfloat radius, CGPoint center); + [Export ("didEndContact:")] + void DidEndContact (SKPhysicsContact contact); + } - [Static, Export ("bodyWithRectangleOfSize:")] - SKPhysicsBody CreateRectangularBody (CGSize size); + /// + delegate void SKPhysicsWorldBodiesEnumeratorHandler (SKPhysicsBody body, out bool stop); + /// The delegate used for enumerating bodies that fall along a ray when used with M:SpriteKit.SKPhysicsWorld.EnumerateBodies(System.Drawing.PointF,System.Drawing.PointF,SpriteKit.SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler*. + delegate void SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler (SKPhysicsBody body, CGPoint point, CGVector normal, out bool stop); + /// [MacCatalyst (13, 1)] - [Static, Export ("bodyWithRectangleOfSize:center:")] - SKPhysicsBody CreateRectangularBody (CGSize size, CGPoint center); - - [Static, Export ("bodyWithPolygonFromPath:")] - SKPhysicsBody CreateBodyFromPath (CGPath path); - - [Static, Export ("bodyWithEdgeFromPoint:toPoint:")] - SKPhysicsBody CreateEdge (CGPoint fromPoint, CGPoint toPoint); + [BaseType (typeof (NSObject), + Delegates = new string [] { "WeakContactDelegate" }, + Events = new Type [] { typeof (SKPhysicsContactDelegate) })] + [DisableDefaultCtor] // You do not create SKPhysicsWorld objects directly; instead, read the physicsWorld property of an SKScene object. + partial interface SKPhysicsWorld : NSSecureCoding { - [Static, Export ("bodyWithEdgeChainFromPath:")] - SKPhysicsBody CreateEdgeChain (CGPath path); + [Export ("gravity")] + CGVector Gravity { get; set; } - [Static, Export ("bodyWithEdgeLoopFromPath:")] - SKPhysicsBody CreateEdgeLoop (CGPath path); + [Export ("speed")] + nfloat Speed { get; set; } - [Static, Export ("bodyWithEdgeLoopFromRect:")] - SKPhysicsBody CreateEdgeLoop (CGRect rect); + [Export ("contactDelegate", ArgumentSemantic.Assign), NullAllowed] + NSObject WeakContactDelegate { get; set; } - [Export ("dynamic")] - bool Dynamic { [Bind ("isDynamic")] get; set; } + [Wrap ("WeakContactDelegate")] + ISKPhysicsContactDelegate ContactDelegate { get; set; } - [Export ("usesPreciseCollisionDetection")] - bool UsesPreciseCollisionDetection { get; set; } + [Export ("addJoint:")] + void AddJoint (SKPhysicsJoint joint); - [Export ("allowsRotation")] - bool AllowsRotation { get; set; } + [Export ("removeJoint:")] + void RemoveJoint (SKPhysicsJoint joint); - [Export ("resting")] - bool Resting { [Bind ("isResting")] get; set; } + [Export ("removeAllJoints")] + void RemoveAllJoints (); - [Export ("friction")] - nfloat Friction { get; set; } + [Export ("bodyAtPoint:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGPoint point); - [Export ("restitution")] - nfloat Restitution { get; set; } + [Export ("bodyInRect:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGRect rect); - [Export ("linearDamping", ArgumentSemantic.Assign)] - nfloat LinearDamping { get; set; } + [Export ("bodyAlongRayStart:end:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGPoint rayStart, CGPoint rayEnd); - [Export ("angularDamping", ArgumentSemantic.Assign)] - nfloat AngularDamping { get; set; } + [Export ("enumerateBodiesAtPoint:usingBlock:")] + void EnumerateBodies (CGPoint point, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); - [Export ("density")] - nfloat Density { get; set; } + [Export ("enumerateBodiesInRect:usingBlock:")] + void EnumerateBodies (CGRect rect, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); - [Export ("mass")] - nfloat Mass { get; set; } + [Export ("enumerateBodiesAlongRayStart:end:usingBlock:")] + void EnumerateBodies (CGPoint start, CGPoint end, SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler enumeratorHandler); - [Export ("area")] - nfloat Area { get; } - - [Export ("affectedByGravity", ArgumentSemantic.Assign)] - bool AffectedByGravity { get; set; } + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("sampleFieldsAt:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector3 SampleFields (/* vector_float3 */ Vector3 position); + } - [Export ("categoryBitMask", ArgumentSemantic.Assign)] - uint CategoryBitMask { get; set; } /* uint32_t */ + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [Abstract] // You never instantiate objects of this class directly + partial interface SKPhysicsJoint : NSSecureCoding { - [Export ("collisionBitMask", ArgumentSemantic.Assign)] - uint CollisionBitMask { get; set; } /* uint32_t */ + [Export ("bodyA", ArgumentSemantic.Retain)] + SKPhysicsBody BodyA { get; set; } - [Export ("contactTestBitMask", ArgumentSemantic.Assign)] - uint ContactTestBitMask { get; set; } /* uint32_t */ + [Export ("bodyB", ArgumentSemantic.Retain)] + SKPhysicsBody BodyB { get; set; } - [Export ("joints")] - SKPhysicsJoint [] Joints { get; } + [MacCatalyst (13, 1)] + [Export ("reactionForce")] + CGVector ReactionForce { get; } - [Export ("node", ArgumentSemantic.Weak)] - [NullAllowed] - SKNode Node { get; } + [MacCatalyst (13, 1)] + [Export ("reactionTorque")] + nfloat ReactionTorque { get; } + } - [Export ("velocity")] - CGVector Velocity { get; set; } + /// A that pins two bodies to a common point. + /// + /// Apple documentation for SKPhysicsJointPin + [MacCatalyst (13, 1)] + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchor` using the default ctor (see #14511) + partial interface SKPhysicsJointPin { - [Export ("angularVelocity")] - nfloat AngularVelocity { get; set; } + [Static, Export ("jointWithBodyA:bodyB:anchor:")] + SKPhysicsJointPin Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); - [Export ("applyForce:")] - void ApplyForce (CGVector force); + [Export ("shouldEnableLimits")] + bool ShouldEnableLimits { get; set; } - [Export ("applyForce:atPoint:")] - void ApplyForce (CGVector force, CGPoint point); + [Export ("lowerAngleLimit")] + nfloat LowerAngleLimit { get; set; } - [Export ("applyTorque:")] - void ApplyTorque (nfloat torque); + [Export ("upperAngleLimit")] + nfloat UpperAngleLimit { get; set; } - [Export ("applyImpulse:")] - void ApplyImpulse (CGVector impulse); + [Export ("frictionTorque")] + nfloat FrictionTorque { get; set; } - [Export ("applyImpulse:atPoint:")] - void ApplyImpulse (CGVector impulse, CGPoint point); + [MacCatalyst (13, 1)] + [Export ("rotationSpeed")] + nfloat RotationSpeed { get; set; } + } - [Export ("applyAngularImpulse:")] - void ApplyAngularImpulse (nfloat impulse); + /// A that connects two bodies as if by a spring. + /// + /// Apple documentation for SKPhysicsJointSpring + [MacCatalyst (13, 1)] + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) + partial interface SKPhysicsJointSpring { - [Export ("allContactedBodies")] - SKPhysicsBody [] AllContactedBodies { get; } + [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] + SKPhysicsJointSpring Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithTexture:size:")] - SKPhysicsBody Create (SKTexture texture, CGSize size); + [Export ("damping")] + nfloat Damping { get; set; } - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithTexture:alphaThreshold:size:")] - SKPhysicsBody Create (SKTexture texture, float /* float, not CGFloat */ alphaThreshold, CGSize size); + [Export ("frequency")] + nfloat Frequency { get; set; } + } + /// A that rigidly connects two bodies. + /// + /// At least one of the s must have its property set to or this will not behave properly. + /// + /// Apple documentation for SKPhysicsJointFixed [MacCatalyst (13, 1)] - [Export ("charge")] - nfloat Charge { get; set; } + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // https://bugzilla.xamarin.com/show_bug.cgi?id=14511 + partial interface SKPhysicsJointFixed { - [MacCatalyst (13, 1)] - [Export ("fieldBitMask")] - uint FieldBitMask { get; set; } /* uint32_t */ + [Static, Export ("jointWithBodyA:bodyB:anchor:")] + SKPhysicsJointFixed Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); + } + /// A that connects two bodies as if by a sliding rod. + /// + /// Apple documentation for SKPhysicsJointSliding [MacCatalyst (13, 1)] - [Export ("pinned")] - bool Pinned { get; set; } -} - -/// Encapsulates the data of a collision between two s. -/// -/// -/// Apple documentation for SKPhysicsContact -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] // An SKPhysicsContact object is created automatically by Scene Kit -partial interface SKPhysicsContact { + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchor` and `axis` using the default ctor (see #14511) + partial interface SKPhysicsJointSliding { - [Export ("bodyA")] - SKPhysicsBody BodyA { get; } + [Static, Export ("jointWithBodyA:bodyB:anchor:axis:")] + SKPhysicsJointSliding Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor, CGVector axis); - [Export ("bodyB")] - SKPhysicsBody BodyB { get; } + [Export ("shouldEnableLimits")] + bool ShouldEnableLimits { get; set; } - [Export ("contactPoint")] - CGPoint ContactPoint { get; } + [Export ("lowerDistanceLimit")] + nfloat LowerDistanceLimit { get; set; } - [Export ("collisionImpulse")] - nfloat CollisionImpulse { get; } + [Export ("upperDistanceLimit")] + nfloat UpperDistanceLimit { get; set; } + } + /// A that connects two bodies as if by a rope. + /// + /// Apple documentation for SKPhysicsJointLimit [MacCatalyst (13, 1)] - [Export ("contactNormal")] - CGVector ContactNormal { get; } + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) + partial interface SKPhysicsJointLimit { -} + [Export ("maxLength")] + nfloat MaxLength { get; set; } -/// Interface representing the required methods (if any) of the protocol . -/// -/// This interface contains the required methods (if any) from the protocol defined by . -/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. -/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. -/// -interface ISKPhysicsContactDelegate { } - -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[Model] -[Protocol] -partial interface SKPhysicsContactDelegate { - - [Export ("didBeginContact:")] - void DidBeginContact (SKPhysicsContact contact); - - [Export ("didEndContact:")] - void DidEndContact (SKPhysicsContact contact); -} + [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] + SKPhysicsJointLimit Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); + } -/// -delegate void SKPhysicsWorldBodiesEnumeratorHandler (SKPhysicsBody body, out bool stop); -/// The delegate used for enumerating bodies that fall along a ray when used with M:SpriteKit.SKPhysicsWorld.EnumerateBodies(System.Drawing.PointF,System.Drawing.PointF,SpriteKit.SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler*. -delegate void SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler (SKPhysicsBody body, CGPoint point, CGVector normal, out bool stop); + /// Defines a range for acceptable float values. + /// + /// Apple documentation for SKRange + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKRange : NSSecureCoding, NSCopying { + [DesignatedInitializer] + [Export ("initWithLowerLimit:upperLimit:")] + NativeHandle Constructor (nfloat lowerLimit, nfloat upperLimier); -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject), - Delegates = new string [] { "WeakContactDelegate" }, - Events = new Type [] { typeof (SKPhysicsContactDelegate) })] -[DisableDefaultCtor] // You do not create SKPhysicsWorld objects directly; instead, read the physicsWorld property of an SKScene object. -partial interface SKPhysicsWorld : NSSecureCoding { + [Export ("lowerLimit")] + nfloat LowerLimit { get; set; } - [Export ("gravity")] - CGVector Gravity { get; set; } + [Export ("upperLimit")] + nfloat UpperLimit { get; set; } - [Export ("speed")] - nfloat Speed { get; set; } + [Static, Export ("rangeWithLowerLimit:upperLimit:")] + SKRange Create (nfloat lower, nfloat upper); - [Export ("contactDelegate", ArgumentSemantic.Assign), NullAllowed] - NSObject WeakContactDelegate { get; set; } + [Static, Export ("rangeWithLowerLimit:")] + SKRange CreateWithLowerLimit (nfloat lower); - [Wrap ("WeakContactDelegate")] - ISKPhysicsContactDelegate ContactDelegate { get; set; } + [Static, Export ("rangeWithUpperLimit:")] + SKRange CreateWithUpperLimit (nfloat upper); - [Export ("addJoint:")] - void AddJoint (SKPhysicsJoint joint); + [Static, Export ("rangeWithConstantValue:")] + SKRange CreateConstant (nfloat value); - [Export ("removeJoint:")] - void RemoveJoint (SKPhysicsJoint joint); + [Static, Export ("rangeWithValue:variance:")] + SKRange CreateWithVariance (nfloat value, nfloat variance); - [Export ("removeAllJoints")] - void RemoveAllJoints (); + [Static, Export ("rangeWithNoLimits")] + SKRange CreateUnlimited (); + } - [Export ("bodyAtPoint:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGPoint point); + /// A that holds audio information. + /// + /// Apple documentation for SKAudioNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + [DisableDefaultCtor] + interface SKAudioNode : NSSecureCoding { + [Export ("initWithAVAudioNode:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] AVAudioNode node); - [Export ("bodyInRect:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGRect rect); + [Export ("initWithFileNamed:")] + NativeHandle Constructor (string fileName); - [Export ("bodyAlongRayStart:end:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGPoint rayStart, CGPoint rayEnd); + [Export ("initWithURL:")] + NativeHandle Constructor (NSUrl url); - [Export ("enumerateBodiesAtPoint:usingBlock:")] - void EnumerateBodies (CGPoint point, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + [NullAllowed, Export ("avAudioNode", ArgumentSemantic.Retain)] + AVAudioNode AvAudioNode { get; set; } - [Export ("enumerateBodiesInRect:usingBlock:")] - void EnumerateBodies (CGRect rect, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + [Export ("autoplayLooped")] + bool AutoplayLooped { get; set; } - [Export ("enumerateBodiesAlongRayStart:end:usingBlock:")] - void EnumerateBodies (CGPoint start, CGPoint end, SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler enumeratorHandler); + [Export ("positional")] + bool Positional { [Bind ("isPositional")] get; set; } + } - // - // iOS 8 - // + /// A node that specifies the position inside a from which it can be rendered. + /// + /// Apple documentation for SKCameraNode [MacCatalyst (13, 1)] - [Export ("sampleFieldsAt:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector3 SampleFields (/* vector_float3 */ Vector3 position); -} - -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[Abstract] // You never instantiate objects of this class directly -partial interface SKPhysicsJoint : NSSecureCoding { - - [Export ("bodyA", ArgumentSemantic.Retain)] - SKPhysicsBody BodyA { get; set; } - - [Export ("bodyB", ArgumentSemantic.Retain)] - SKPhysicsBody BodyB { get; set; } + [BaseType (typeof (SKNode))] + interface SKCameraNode { + [Export ("containsNode:")] + bool Contains (SKNode node); - [MacCatalyst (13, 1)] - [Export ("reactionForce")] - CGVector ReactionForce { get; } + [Export ("containedNodeSet")] + NSSet ContainedNodeSet { get; } + } + /// A that holds an archived collection of child nodes that can be used in multiple places throughout the game. + /// + /// Apple documentation for SKReferenceNode [MacCatalyst (13, 1)] - [Export ("reactionTorque")] - nfloat ReactionTorque { get; } -} - -/// A that pins two bodies to a common point. -/// -/// Apple documentation for SKPhysicsJointPin -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchor` using the default ctor (see #14511) -partial interface SKPhysicsJointPin { + [BaseType (typeof (SKNode))] + [DisableDefaultCtor] + interface SKReferenceNode { + [Export ("initWithURL:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] NSUrl url); - [Static, Export ("jointWithBodyA:bodyB:anchor:")] - SKPhysicsJointPin Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); + [Export ("initWithFileNamed:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] string fileName); - [Export ("shouldEnableLimits")] - bool ShouldEnableLimits { get; set; } + [Static] + [Export ("referenceNodeWithFileNamed:")] + SKReferenceNode FromFile (string fileName); - [Export ("lowerAngleLimit")] - nfloat LowerAngleLimit { get; set; } + [Static] + [Export ("referenceNodeWithURL:")] + SKReferenceNode FromUrl (NSUrl referenceUrl); - [Export ("upperAngleLimit")] - nfloat UpperAngleLimit { get; set; } + [Export ("didLoadReferenceNode:")] + void DidLoadReferenceNode ([NullAllowed] SKNode node); - [Export ("frictionTorque")] - nfloat FrictionTorque { get; set; } + [Export ("resolveReferenceNode")] + void Resolve (); + } + /// Holds per-node data to be used with a custom shader. + /// + /// Apple documentation for SKAttribute [MacCatalyst (13, 1)] - [Export ("rotationSpeed")] - nfloat RotationSpeed { get; set; } -} - -/// A that connects two bodies as if by a spring. -/// -/// Apple documentation for SKPhysicsJointSpring -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) -partial interface SKPhysicsJointSpring { - - [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] - SKPhysicsJointSpring Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); - - [Export ("damping")] - nfloat Damping { get; set; } - - [Export ("frequency")] - nfloat Frequency { get; set; } -} - -/// A that rigidly connects two bodies. -/// -/// At least one of the s must have its property set to or this will not behave properly. -/// -/// Apple documentation for SKPhysicsJointFixed -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // https://bugzilla.xamarin.com/show_bug.cgi?id=14511 -partial interface SKPhysicsJointFixed { - - [Static, Export ("jointWithBodyA:bodyB:anchor:")] - SKPhysicsJointFixed Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); -} - -/// A that connects two bodies as if by a sliding rod. -/// -/// Apple documentation for SKPhysicsJointSliding -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchor` and `axis` using the default ctor (see #14511) -partial interface SKPhysicsJointSliding { - - [Static, Export ("jointWithBodyA:bodyB:anchor:axis:")] - SKPhysicsJointSliding Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor, CGVector axis); - - [Export ("shouldEnableLimits")] - bool ShouldEnableLimits { get; set; } - - [Export ("lowerDistanceLimit")] - nfloat LowerDistanceLimit { get; set; } - - [Export ("upperDistanceLimit")] - nfloat UpperDistanceLimit { get; set; } -} - -/// A that connects two bodies as if by a rope. -/// -/// Apple documentation for SKPhysicsJointLimit -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) -partial interface SKPhysicsJointLimit { - - [Export ("maxLength")] - nfloat MaxLength { get; set; } - - [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] - SKPhysicsJointLimit Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); -} - -/// Defines a range for acceptable float values. -/// -/// Apple documentation for SKRange -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKRange : NSSecureCoding, NSCopying { - [DesignatedInitializer] - [Export ("initWithLowerLimit:upperLimit:")] - NativeHandle Constructor (nfloat lowerLimit, nfloat upperLimier); - - [Export ("lowerLimit")] - nfloat LowerLimit { get; set; } - - [Export ("upperLimit")] - nfloat UpperLimit { get; set; } - - [Static, Export ("rangeWithLowerLimit:upperLimit:")] - SKRange Create (nfloat lower, nfloat upper); - - [Static, Export ("rangeWithLowerLimit:")] - SKRange CreateWithLowerLimit (nfloat lower); - - [Static, Export ("rangeWithUpperLimit:")] - SKRange CreateWithUpperLimit (nfloat upper); - - [Static, Export ("rangeWithConstantValue:")] - SKRange CreateConstant (nfloat value); - - [Static, Export ("rangeWithValue:variance:")] - SKRange CreateWithVariance (nfloat value, nfloat variance); - - [Static, Export ("rangeWithNoLimits")] - SKRange CreateUnlimited (); -} - -/// A that holds audio information. -/// -/// Apple documentation for SKAudioNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -[DisableDefaultCtor] -interface SKAudioNode : NSSecureCoding { - [Export ("initWithAVAudioNode:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] AVAudioNode node); - - [Export ("initWithFileNamed:")] - NativeHandle Constructor (string fileName); - - [Export ("initWithURL:")] - NativeHandle Constructor (NSUrl url); - - [NullAllowed, Export ("avAudioNode", ArgumentSemantic.Retain)] - AVAudioNode AvAudioNode { get; set; } + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + interface SKAttribute : NSSecureCoding { + [Static] + [Export ("attributeWithName:type:")] + SKAttribute Create (string name, SKAttributeType type); - [Export ("autoplayLooped")] - bool AutoplayLooped { get; set; } - - [Export ("positional")] - bool Positional { [Bind ("isPositional")] get; set; } -} - -/// A node that specifies the position inside a from which it can be rendered. -/// -/// Apple documentation for SKCameraNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKCameraNode { - [Export ("containsNode:")] - bool Contains (SKNode node); - - [Export ("containedNodeSet")] - NSSet ContainedNodeSet { get; } -} - -/// A that holds an archived collection of child nodes that can be used in multiple places throughout the game. -/// -/// Apple documentation for SKReferenceNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -[DisableDefaultCtor] -interface SKReferenceNode { - [Export ("initWithURL:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] NSUrl url); - - [Export ("initWithFileNamed:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] string fileName); - - [Static] - [Export ("referenceNodeWithFileNamed:")] - SKReferenceNode FromFile (string fileName); - - [Static] - [Export ("referenceNodeWithURL:")] - SKReferenceNode FromUrl (NSUrl referenceUrl); - - [Export ("didLoadReferenceNode:")] - void DidLoadReferenceNode ([NullAllowed] SKNode node); - - [Export ("resolveReferenceNode")] - void Resolve (); -} - -/// Holds per-node data to be used with a custom shader. -/// -/// Apple documentation for SKAttribute -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -interface SKAttribute : NSSecureCoding { - [Static] - [Export ("attributeWithName:type:")] - SKAttribute Create (string name, SKAttributeType type); - - [Export ("initWithName:type:")] - [DesignatedInitializer] - NativeHandle Constructor (string name, SKAttributeType type); - - [Export ("name")] - string Name { get; } - - [Export ("type")] - SKAttributeType Type { get; } -} - -/// Holds the value, of the appropriate , for an . -/// -/// Apple documentation for SKAttributeValue -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] // DesignatedInitializer below -interface SKAttributeValue : NSSecureCoding { - [DesignatedInitializer] - [Export ("init")] - NativeHandle Constructor (); - - [Static] - [Export ("valueWithFloat:")] - SKAttributeValue Create (float value); + [Export ("initWithName:type:")] + [DesignatedInitializer] + NativeHandle Constructor (string name, SKAttributeType type); - [Static] - [Export ("valueWithVectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector2 value); + [Export ("name")] + string Name { get; } - [Static] - [Export ("valueWithVectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector3 value); + [Export ("type")] + SKAttributeType Type { get; } + } - [Static] - [Export ("valueWithVectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector4 value); + /// Holds the value, of the appropriate , for an . + /// + /// Apple documentation for SKAttributeValue + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] // DesignatedInitializer below + interface SKAttributeValue : NSSecureCoding { + [DesignatedInitializer] + [Export ("init")] + NativeHandle Constructor (); - [Export ("floatValue")] - float FloatValue { get; set; } + [Static] + [Export ("valueWithFloat:")] + SKAttributeValue Create (float value); - [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] - Vector2 VectorFloat2Value { + [Static] + [Export ("valueWithVectorFloat2:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + SKAttributeValue Create (Vector2 value); - [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] - Vector3 VectorFloat3Value { + [Static] + [Export ("valueWithVectorFloat3:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + SKAttributeValue Create (Vector3 value); - [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] - Vector4 VectorFloat4Value { + [Static] + [Export ("valueWithVectorFloat4:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; + SKAttributeValue Create (Vector4 value); + + [Export ("floatValue")] + float FloatValue { get; set; } + + [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] + Vector2 VectorFloat2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] + Vector3 VectorFloat3Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] + Vector4 VectorFloat4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } } -} -/// A single kind of tile in a tile map. -/// -/// Apple documentation for SKTileDefinition -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -interface SKTileDefinition : NSCopying, NSSecureCoding { - [Static] - [Export ("tileDefinitionWithTexture:")] - SKTileDefinition Create (SKTexture texture); - - [Static] - [Export ("tileDefinitionWithTexture:size:")] - SKTileDefinition Create (SKTexture texture, CGSize size); - - [Static] - [Export ("tileDefinitionWithTexture:normalTexture:size:")] - SKTileDefinition Create (SKTexture texture, SKTexture normalTexture, CGSize size); + /// A single kind of tile in a tile map. + /// + /// Apple documentation for SKTileDefinition + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + interface SKTileDefinition : NSCopying, NSSecureCoding { + [Static] + [Export ("tileDefinitionWithTexture:")] + SKTileDefinition Create (SKTexture texture); - [Static] - [Export ("tileDefinitionWithTextures:size:timePerFrame:")] - SKTileDefinition Create (SKTexture [] textures, CGSize size, nfloat timePerFrame); + [Static] + [Export ("tileDefinitionWithTexture:size:")] + SKTileDefinition Create (SKTexture texture, CGSize size); - [Static] - [Export ("tileDefinitionWithTextures:normalTextures:size:timePerFrame:")] - SKTileDefinition Create (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); + [Static] + [Export ("tileDefinitionWithTexture:normalTexture:size:")] + SKTileDefinition Create (SKTexture texture, SKTexture normalTexture, CGSize size); - [Export ("initWithTexture:")] - NativeHandle Constructor (SKTexture texture); + [Static] + [Export ("tileDefinitionWithTextures:size:timePerFrame:")] + SKTileDefinition Create (SKTexture [] textures, CGSize size, nfloat timePerFrame); - [Export ("initWithTexture:size:")] - NativeHandle Constructor (SKTexture texture, CGSize size); + [Static] + [Export ("tileDefinitionWithTextures:normalTextures:size:timePerFrame:")] + SKTileDefinition Create (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); - [Export ("initWithTexture:normalTexture:size:")] - NativeHandle Constructor (SKTexture texture, SKTexture normalTexture, CGSize size); + [Export ("initWithTexture:")] + NativeHandle Constructor (SKTexture texture); - [Export ("initWithTextures:size:timePerFrame:")] - NativeHandle Constructor (SKTexture [] textures, CGSize size, nfloat timePerFrame); + [Export ("initWithTexture:size:")] + NativeHandle Constructor (SKTexture texture, CGSize size); - [Export ("initWithTextures:normalTextures:size:timePerFrame:")] - NativeHandle Constructor (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); + [Export ("initWithTexture:normalTexture:size:")] + NativeHandle Constructor (SKTexture texture, SKTexture normalTexture, CGSize size); - [Export ("textures", ArgumentSemantic.Copy)] - SKTexture [] Textures { get; set; } + [Export ("initWithTextures:size:timePerFrame:")] + NativeHandle Constructor (SKTexture [] textures, CGSize size, nfloat timePerFrame); - [Export ("normalTextures", ArgumentSemantic.Copy)] - SKTexture [] NormalTextures { get; set; } + [Export ("initWithTextures:normalTextures:size:timePerFrame:")] + NativeHandle Constructor (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); - [NullAllowed, Export ("userData", ArgumentSemantic.Retain)] - NSMutableDictionary UserData { get; set; } + [Export ("textures", ArgumentSemantic.Copy)] + SKTexture [] Textures { get; set; } - [NullAllowed, Export ("name")] - string Name { get; set; } + [Export ("normalTextures", ArgumentSemantic.Copy)] + SKTexture [] NormalTextures { get; set; } - [Export ("size", ArgumentSemantic.Assign)] - CGSize Size { get; set; } + [NullAllowed, Export ("userData", ArgumentSemantic.Retain)] + NSMutableDictionary UserData { get; set; } - [Export ("timePerFrame")] - nfloat TimePerFrame { get; set; } + [NullAllowed, Export ("name")] + string Name { get; set; } - [Export ("placementWeight")] - nuint PlacementWeight { get; set; } + [Export ("size", ArgumentSemantic.Assign)] + CGSize Size { get; set; } - [Export ("rotation", ArgumentSemantic.Assign)] - SKTileDefinitionRotation Rotation { get; set; } + [Export ("timePerFrame")] + nfloat TimePerFrame { get; set; } - [Export ("flipVertically")] - bool FlipVertically { get; set; } + [Export ("placementWeight")] + nuint PlacementWeight { get; set; } - [Export ("flipHorizontally")] - bool FlipHorizontally { get; set; } -} + [Export ("rotation", ArgumentSemantic.Assign)] + SKTileDefinitionRotation Rotation { get; set; } -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKTileMapNode : NSCopying, NSSecureCoding { - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); + [Export ("flipVertically")] + bool FlipVertically { get; set; } - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); + [Export ("flipHorizontally")] + bool FlipHorizontally { get; set; } + } - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:tileGroupLayout:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + interface SKTileMapNode : NSCopying, NSSecureCoding { + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); - [Export ("initWithTileSet:columns:rows:tileSize:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); - [Export ("initWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:tileGroupLayout:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); - [Export ("initWithTileSet:columns:rows:tileSize:tileGroupLayout:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); + [Export ("initWithTileSet:columns:rows:tileSize:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); - [Export ("numberOfColumns")] - nuint NumberOfColumns { get; set; } + [Export ("initWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); - [Export ("numberOfRows")] - nuint NumberOfRows { get; set; } + [Export ("initWithTileSet:columns:rows:tileSize:tileGroupLayout:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); - [Export ("tileSize", ArgumentSemantic.Assign)] - CGSize TileSize { get; set; } + [Export ("numberOfColumns")] + nuint NumberOfColumns { get; set; } - [Export ("mapSize")] - CGSize MapSize { get; } + [Export ("numberOfRows")] + nuint NumberOfRows { get; set; } - [Export ("tileSet", ArgumentSemantic.Assign)] - SKTileSet TileSet { get; set; } + [Export ("tileSize", ArgumentSemantic.Assign)] + CGSize TileSize { get; set; } - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + [Export ("mapSize")] + CGSize MapSize { get; } - [Export ("color", ArgumentSemantic.Retain)] - UIColor Color { get; set; } + [Export ("tileSet", ArgumentSemantic.Assign)] + SKTileSet TileSet { get; set; } - [Export ("blendMode", ArgumentSemantic.Assign)] - SKBlendMode BlendMode { get; set; } + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("anchorPoint", ArgumentSemantic.Assign)] - CGPoint AnchorPoint { get; set; } + [Export ("color", ArgumentSemantic.Retain)] + UIColor Color { get; set; } - [NullAllowed, Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [Export ("blendMode", ArgumentSemantic.Assign)] + SKBlendMode BlendMode { get; set; } - [Export ("lightingBitMask")] - uint LightingBitMask { get; set; } + [Export ("anchorPoint", ArgumentSemantic.Assign)] + CGPoint AnchorPoint { get; set; } - [Export ("enableAutomapping")] - bool EnableAutomapping { get; set; } + [NullAllowed, Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - [Export ("fillWithTileGroup:")] - void Fill ([NullAllowed] SKTileGroup tileGroup); + [Export ("lightingBitMask")] + uint LightingBitMask { get; set; } - [Export ("tileDefinitionAtColumn:row:")] - [return: NullAllowed] - SKTileDefinition GetTileDefinition (nuint column, nuint row); + [Export ("enableAutomapping")] + bool EnableAutomapping { get; set; } - [Export ("tileGroupAtColumn:row:")] - [return: NullAllowed] - SKTileGroup GetTileGroup (nuint column, nuint row); + [Export ("fillWithTileGroup:")] + void Fill ([NullAllowed] SKTileGroup tileGroup); - [Export ("setTileGroup:forColumn:row:")] - void SetTileGroup ([NullAllowed] SKTileGroup tileGroup, nuint column, nuint row); + [Export ("tileDefinitionAtColumn:row:")] + [return: NullAllowed] + SKTileDefinition GetTileDefinition (nuint column, nuint row); - [Export ("setTileGroup:andTileDefinition:forColumn:row:")] - void SetTileGroup (SKTileGroup tileGroup, SKTileDefinition tileDefinition, nuint column, nuint row); + [Export ("tileGroupAtColumn:row:")] + [return: NullAllowed] + SKTileGroup GetTileGroup (nuint column, nuint row); - [Export ("tileColumnIndexFromPosition:")] - nuint GetTileColumnIndex (CGPoint position); + [Export ("setTileGroup:forColumn:row:")] + void SetTileGroup ([NullAllowed] SKTileGroup tileGroup, nuint column, nuint row); - [Export ("tileRowIndexFromPosition:")] - nuint GetTileRowIndex (CGPoint position); + [Export ("setTileGroup:andTileDefinition:forColumn:row:")] + void SetTileGroup (SKTileGroup tileGroup, SKTileDefinition tileDefinition, nuint column, nuint row); - [Export ("centerOfTileAtColumn:row:")] - CGPoint GetCenterOfTile (nuint column, nuint row); + [Export ("tileColumnIndexFromPosition:")] + nuint GetTileColumnIndex (CGPoint position); - // Static Category from GameplayKit - [MacCatalyst (13, 1)] - [Static] - [Export ("tileMapNodesWithTileSet:columns:rows:tileSize:fromNoiseMap:tileTypeNoiseMapThresholds:")] - SKTileMapNode [] FromTileSet (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, GKNoiseMap noiseMap, NSNumber [] thresholds); + [Export ("tileRowIndexFromPosition:")] + nuint GetTileRowIndex (CGPoint position); - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [Export ("centerOfTileAtColumn:row:")] + CGPoint GetCenterOfTile (nuint column, nuint row); - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + // Static Category from GameplayKit + [MacCatalyst (13, 1)] + [Static] + [Export ("tileMapNodesWithTileSet:columns:rows:tileSize:fromNoiseMap:tileTypeNoiseMapThresholds:")] + SKTileMapNode [] FromTileSet (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, GKNoiseMap noiseMap, NSNumber [] thresholds); - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } -/// Represents the possible elements of a in the form of objects. -/// -/// An collects a set of related objects that may be placed on a . Additionally, it may define a default tile group and tile size. -/// -/// Apple documentation for SKTileSet -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKTileSet : NSCopying, NSSecureCoding { - [Static] - [Export ("tileSetWithTileGroups:")] - SKTileSet Create (SKTileGroup [] tileGroups); + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [Static] - [Export ("tileSetWithTileGroups:tileSetType:")] - SKTileSet Create (SKTileGroup [] tileGroups, SKTileSetType tileSetType); + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } - [Export ("initWithTileGroups:")] - NativeHandle Constructor (SKTileGroup [] tileGroups); + /// Represents the possible elements of a in the form of objects. + /// + /// An collects a set of related objects that may be placed on a . Additionally, it may define a default tile group and tile size. + /// + /// Apple documentation for SKTileSet + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKTileSet : NSCopying, NSSecureCoding { + [Static] + [Export ("tileSetWithTileGroups:")] + SKTileSet Create (SKTileGroup [] tileGroups); - [Export ("initWithTileGroups:tileSetType:")] - NativeHandle Constructor (SKTileGroup [] tileGroups, SKTileSetType tileSetType); + [Static] + [Export ("tileSetWithTileGroups:tileSetType:")] + SKTileSet Create (SKTileGroup [] tileGroups, SKTileSetType tileSetType); - [Static] - [Export ("tileSetNamed:")] - [return: NullAllowed] - SKTileSet FromName (string name); + [Export ("initWithTileGroups:")] + NativeHandle Constructor (SKTileGroup [] tileGroups); - [Static] - [Export ("tileSetFromURL:")] - [return: NullAllowed] - SKTileSet FromUrl (NSUrl url); + [Export ("initWithTileGroups:tileSetType:")] + NativeHandle Constructor (SKTileGroup [] tileGroups, SKTileSetType tileSetType); - [Export ("tileGroups", ArgumentSemantic.Copy)] - SKTileGroup [] TileGroups { get; set; } + [Static] + [Export ("tileSetNamed:")] + [return: NullAllowed] + SKTileSet FromName (string name); - [NullAllowed, Export ("name")] - string Name { get; set; } + [Static] + [Export ("tileSetFromURL:")] + [return: NullAllowed] + SKTileSet FromUrl (NSUrl url); - [Export ("type", ArgumentSemantic.Assign)] - SKTileSetType Type { get; set; } + [Export ("tileGroups", ArgumentSemantic.Copy)] + SKTileGroup [] TileGroups { get; set; } - [NullAllowed, Export ("defaultTileGroup", ArgumentSemantic.Assign)] - SKTileGroup DefaultTileGroup { get; set; } + [NullAllowed, Export ("name")] + string Name { get; set; } - [Export ("defaultTileSize", ArgumentSemantic.Assign)] - CGSize DefaultTileSize { get; set; } -} + [Export ("type", ArgumentSemantic.Assign)] + SKTileSetType Type { get; set; } -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKTileGroup : NSCopying, NSSecureCoding { - [Static] - [Export ("tileGroupWithTileDefinition:")] - SKTileGroup Create (SKTileDefinition tileDefinition); + [NullAllowed, Export ("defaultTileGroup", ArgumentSemantic.Assign)] + SKTileGroup DefaultTileGroup { get; set; } - [Static] - [Export ("tileGroupWithRules:")] - SKTileGroup Create (SKTileGroupRule [] rules); + [Export ("defaultTileSize", ArgumentSemantic.Assign)] + CGSize DefaultTileSize { get; set; } + } - [Static] - [Export ("emptyTileGroup")] - SKTileGroup CreateEmpty (); + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKTileGroup : NSCopying, NSSecureCoding { + [Static] + [Export ("tileGroupWithTileDefinition:")] + SKTileGroup Create (SKTileDefinition tileDefinition); - [Export ("initWithTileDefinition:")] - NativeHandle Constructor (SKTileDefinition tileDefinition); + [Static] + [Export ("tileGroupWithRules:")] + SKTileGroup Create (SKTileGroupRule [] rules); - [Export ("initWithRules:")] - NativeHandle Constructor (SKTileGroupRule [] rules); + [Static] + [Export ("emptyTileGroup")] + SKTileGroup CreateEmpty (); - [Export ("rules", ArgumentSemantic.Copy)] - SKTileGroupRule [] Rules { get; set; } + [Export ("initWithTileDefinition:")] + NativeHandle Constructor (SKTileDefinition tileDefinition); - [NullAllowed, Export ("name")] - string Name { get; set; } -} + [Export ("initWithRules:")] + NativeHandle Constructor (SKTileGroupRule [] rules); -/// Defines adjacency rules for tiles in an . -/// -/// Apple documentation for SKTileGroupRule -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKTileGroupRule : NSCopying, NSSecureCoding { - [Static] - [Export ("tileGroupRuleWithAdjacency:tileDefinitions:")] - SKTileGroupRule Create (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); + [Export ("rules", ArgumentSemantic.Copy)] + SKTileGroupRule [] Rules { get; set; } - [Export ("initWithAdjacency:tileDefinitions:")] - NativeHandle Constructor (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); + [NullAllowed, Export ("name")] + string Name { get; set; } + } - [Export ("adjacency", ArgumentSemantic.Assign)] - SKTileAdjacencyMask Adjacency { get; set; } + /// Defines adjacency rules for tiles in an . + /// + /// Apple documentation for SKTileGroupRule + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKTileGroupRule : NSCopying, NSSecureCoding { + [Static] + [Export ("tileGroupRuleWithAdjacency:tileDefinitions:")] + SKTileGroupRule Create (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); - [Export ("tileDefinitions", ArgumentSemantic.Copy)] - SKTileDefinition [] TileDefinitions { get; set; } + [Export ("initWithAdjacency:tileDefinitions:")] + NativeHandle Constructor (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); - [NullAllowed, Export ("name")] - string Name { get; set; } -} + [Export ("adjacency", ArgumentSemantic.Assign)] + SKTileAdjacencyMask Adjacency { get; set; } -/// Defines geometry deformation on objects. -/// -/// Apple documentation for SKWarpGeometry -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKWarpGeometry : NSCopying, NSSecureCoding { } - -/// Associates a and subdivision levels with an implementation. -[MacCatalyst (13, 1)] -[Protocol] -interface SKWarpable { - [Abstract] - [NullAllowed, Export ("warpGeometry", ArgumentSemantic.Assign)] - SKWarpGeometry WarpGeometry { get; set; } - - [Abstract] - [Export ("subdivisionLevels")] - nint SubdivisionLevels { get; set; } -} + [Export ("tileDefinitions", ArgumentSemantic.Copy)] + SKTileDefinition [] TileDefinitions { get; set; } -/// A subclass that defines a warpable grid. -/// -/// Apple documentation for SKWarpGeometryGrid -[MacCatalyst (13, 1)] -[BaseType (typeof (SKWarpGeometry))] -[DisableDefaultCtor] -interface SKWarpGeometryGrid : NSSecureCoding { - [Static] - [Export ("grid")] - SKWarpGeometryGrid GetGrid (); + [NullAllowed, Export ("name")] + string Name { get; set; } + } - [Static] - [Export ("gridWithColumns:rows:")] - SKWarpGeometryGrid Create (nint cols, nint rows); + /// Defines geometry deformation on objects. + /// + /// Apple documentation for SKWarpGeometry + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKWarpGeometry : NSCopying, NSSecureCoding { } - [Internal] - [Static] - [Export ("gridWithColumns:rows:sourcePositions:destPositions:")] - SKWarpGeometryGrid GridWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); + /// Associates a and subdivision levels with an implementation. + [MacCatalyst (13, 1)] + [Protocol] + interface SKWarpable { + [Abstract] + [NullAllowed, Export ("warpGeometry", ArgumentSemantic.Assign)] + SKWarpGeometry WarpGeometry { get; set; } - [Internal] - [DesignatedInitializer] - [Export ("initWithColumns:rows:sourcePositions:destPositions:")] - IntPtr InitWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); + [Abstract] + [Export ("subdivisionLevels")] + nint SubdivisionLevels { get; set; } + } - [Export ("numberOfColumns")] - nint NumberOfColumns { get; } + /// A subclass that defines a warpable grid. + /// + /// Apple documentation for SKWarpGeometryGrid + [MacCatalyst (13, 1)] + [BaseType (typeof (SKWarpGeometry))] + [DisableDefaultCtor] + interface SKWarpGeometryGrid : NSSecureCoding { + [Static] + [Export ("grid")] + SKWarpGeometryGrid GetGrid (); - [Export ("numberOfRows")] - nint NumberOfRows { get; } + [Static] + [Export ("gridWithColumns:rows:")] + SKWarpGeometryGrid Create (nint cols, nint rows); - [Export ("vertexCount")] - nint VertexCount { get; } + [Internal] + [Static] + [Export ("gridWithColumns:rows:sourcePositions:destPositions:")] + SKWarpGeometryGrid GridWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - [Export ("sourcePositionAtIndex:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector2 GetSourcePosition (nint index); + [Internal] + [DesignatedInitializer] + [Export ("initWithColumns:rows:sourcePositions:destPositions:")] + IntPtr InitWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - [Export ("destPositionAtIndex:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector2 GetDestPosition (nint index); + [Export ("numberOfColumns")] + nint NumberOfColumns { get; } - [Internal] - [Export ("gridByReplacingSourcePositions:")] - SKWarpGeometryGrid _GridByReplacingSourcePositions (IntPtr sourcePositions); + [Export ("numberOfRows")] + nint NumberOfRows { get; } - [Internal] - [Export ("gridByReplacingDestPositions:")] - SKWarpGeometryGrid _GridByReplacingDestPositions (IntPtr destPositions); -} + [Export ("vertexCount")] + nint VertexCount { get; } -// SKRenderer is not available for WatchKit apps and the iOS simulator -/// The class used to render SpriteKit. -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -interface SKRenderer { - [Static] - [Export ("rendererWithDevice:")] - SKRenderer FromDevice (IMTLDevice device); + [Export ("sourcePositionAtIndex:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector2 GetSourcePosition (nint index); - [Export ("renderWithViewport:commandBuffer:renderPassDescriptor:")] - void Render (CGRect viewport, IMTLCommandBuffer commandBuffer, MTLRenderPassDescriptor renderPassDescriptor); + [Export ("destPositionAtIndex:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector2 GetDestPosition (nint index); - [Export ("renderWithViewport:renderCommandEncoder:renderPassDescriptor:commandQueue:")] - void Render (CGRect viewport, IMTLRenderCommandEncoder renderCommandEncoder, MTLRenderPassDescriptor renderPassDescriptor, IMTLCommandQueue commandQueue); + [Internal] + [Export ("gridByReplacingSourcePositions:")] + SKWarpGeometryGrid _GridByReplacingSourcePositions (IntPtr sourcePositions); - [Export ("updateAtTime:")] - void Update (double currentTime); + [Internal] + [Export ("gridByReplacingDestPositions:")] + SKWarpGeometryGrid _GridByReplacingDestPositions (IntPtr destPositions); + } - [NullAllowed, Export ("scene", ArgumentSemantic.Assign)] - SKScene Scene { get; set; } + // SKRenderer is not available for WatchKit apps and the iOS simulator + /// The class used to render SpriteKit. + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + interface SKRenderer { + [Static] + [Export ("rendererWithDevice:")] + SKRenderer FromDevice (IMTLDevice device); - [Export ("ignoresSiblingOrder")] - bool IgnoresSiblingOrder { get; set; } + [Export ("renderWithViewport:commandBuffer:renderPassDescriptor:")] + void Render (CGRect viewport, IMTLCommandBuffer commandBuffer, MTLRenderPassDescriptor renderPassDescriptor); - [Export ("shouldCullNonVisibleNodes")] - bool ShouldCullNonVisibleNodes { get; set; } + [Export ("renderWithViewport:renderCommandEncoder:renderPassDescriptor:commandQueue:")] + void Render (CGRect viewport, IMTLRenderCommandEncoder renderCommandEncoder, MTLRenderPassDescriptor renderPassDescriptor, IMTLCommandQueue commandQueue); - [Export ("showsDrawCount")] - bool ShowsDrawCount { get; set; } + [Export ("updateAtTime:")] + void Update (double currentTime); - [Export ("showsNodeCount")] - bool ShowsNodeCount { get; set; } + [NullAllowed, Export ("scene", ArgumentSemantic.Assign)] + SKScene Scene { get; set; } - [Export ("showsQuadCount")] - bool ShowsQuadCount { get; set; } + [Export ("ignoresSiblingOrder")] + bool IgnoresSiblingOrder { get; set; } - [Export ("showsPhysics")] - bool ShowsPhysics { get; set; } + [Export ("shouldCullNonVisibleNodes")] + bool ShouldCullNonVisibleNodes { get; set; } - [Export ("showsFields")] - bool ShowsFields { get; set; } -} + [Export ("showsDrawCount")] + bool ShowsDrawCount { get; set; } -/// A that holds a geometric transform. -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKTransformNode { - [Export ("xRotation")] - nfloat XRotation { get; set; } + [Export ("showsNodeCount")] + bool ShowsNodeCount { get; set; } - [Export ("yRotation")] - nfloat YRotation { get; set; } + [Export ("showsQuadCount")] + bool ShowsQuadCount { get; set; } - [Export ("eulerAngles")] - VectorFloat3 EulerAngles { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [Export ("showsPhysics")] + bool ShowsPhysics { get; set; } - [Export ("rotationMatrix")] - MatrixFloat3x3 RotationMatrix { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; + [Export ("showsFields")] + bool ShowsFields { get; set; } } - [Export ("quaternion")] - Quaternion Quaternion { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; + /// A that holds a geometric transform. + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + interface SKTransformNode { + [Export ("xRotation")] + nfloat XRotation { get; set; } + + [Export ("yRotation")] + nfloat YRotation { get; set; } + + [Export ("eulerAngles")] + VectorFloat3 EulerAngles { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("rotationMatrix")] + MatrixFloat3x3 RotationMatrix { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("quaternion")] + Quaternion Quaternion { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } } } -} diff --git a/src/storekit.cs b/src/storekit.cs index 1b3269170981..1f273c0191f4 100644 --- a/src/storekit.cs +++ b/src/storekit.cs @@ -79,13 +79,17 @@ partial interface SKDownload { [Export ("state")] SKDownloadState State { get; } #if MONOMAC - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] [Obsolete ("Use 'State' instead.")] [Wrap ("State", IsVirtual = true)] - SKDownloadState DownloadState { get; } + SKDownloadState DownloadState { get; } - [NoiOS][NoTV][NoMacCatalyst] - [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'ExpectedContentLength' instead.")] + [NoiOS] + [NoTV] + [NoMacCatalyst] + [Deprecated (PlatformName.MacOSX, 10, 15, message: "Use 'ExpectedContentLength' instead.")] [Export ("contentLength", ArgumentSemantic.Copy)] NSNumber ContentLength { get; } #else @@ -374,8 +378,10 @@ interface SKProduct { string ProductIdentifier { get; } #if MONOMAC -[NoiOS][NoTV][NoMacCatalyst] - [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'IsDownloadable' instead.")] + [NoiOS] + [NoTV] + [NoMacCatalyst] + [Deprecated (PlatformName.MacOSX, 10, 15, message: "Use 'IsDownloadable' instead.")] [Export ("downloadable")] bool Downloadable { get; } #elif !NET diff --git a/src/tvmlkit.cs b/src/tvmlkit.cs index b63ba6ae19e7..ac782b340890 100644 --- a/src/tvmlkit.cs +++ b/src/tvmlkit.cs @@ -716,7 +716,8 @@ interface ITVBrowserViewControllerDataSource { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -734,7 +735,8 @@ interface ITVBrowserViewControllerDelegate { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -799,7 +801,8 @@ interface ITVDocumentViewControllerDelegate { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/uikit.cs b/src/uikit.cs index dc2a77d216f0..e88ec7e7c10a 100644 --- a/src/uikit.cs +++ b/src/uikit.cs @@ -15777,7 +15777,7 @@ interface UITableViewRowAction : NSCopying { // , Events=new Type [] {typeof(UITextFieldDelegate)})] custom logic needed, see https://bugzilla.xamarin.com/show_bug.cgi?id=53174 interface UITextField : UITextInput, UIContentSizeCategoryAdjusting, UILetterformAwareAdjusting #if IOS - , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting + , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting #endif // IOS { [Export ("initWithFrame:")] @@ -15993,7 +15993,7 @@ interface UITextFieldDelegate { [BaseType (typeof (UIScrollView), Delegates = new string [] { "WeakDelegate" }, Events = new Type [] { typeof (UITextViewDelegate) })] interface UITextView : UITextInput, NSCoding, UIContentSizeCategoryAdjusting, UILetterformAwareAdjusting #if IOS - , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting + , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting #endif // IOS { [Export ("initWithFrame:")] diff --git a/src/webkit.cs b/src/webkit.cs index 08a7e3be2435..3eb3bd941851 100644 --- a/src/webkit.cs +++ b/src/webkit.cs @@ -32,7 +32,7 @@ #if MONOMAC using AppKit; -using UIColor=AppKit.NSColor; +using UIColor = AppKit.NSColor; using UIScrollView = AppKit.NSScrollView; using UIImage = AppKit.NSImage; using IUIContextMenuInteractionCommitAnimating = Foundation.NSObject; @@ -2539,7 +2539,7 @@ partial interface WebUIDelegate { [Export ("webView:shouldPerformAction:fromSender:"), DelegateName ("WebViewPerformAction"), DefaultValue (null)] bool UIShouldPerformActionfromSender (WebView webView, Selector action, NSObject sender); #else - [Export ("webView:shouldPerformAction:fromSender:"), DelegateName("WebViewPerformAction"), DefaultValue (null)] + [Export ("webView:shouldPerformAction:fromSender:"), DelegateName ("WebViewPerformAction"), DefaultValue (null)] bool UIShouldPerformAction (WebView webView, Selector action, NSObject sender); #endif @@ -5760,7 +5760,7 @@ interface WKWindowFeatures { } #if MONOMAC - interface UIPreviewActionItem {} + interface UIPreviewActionItem { } #endif interface IWKPreviewActionItem { } diff --git a/src/xkit.cs b/src/xkit.cs index 6aa374e5d656..fb04b16ca6c7 100644 --- a/src/xkit.cs +++ b/src/xkit.cs @@ -44,21 +44,21 @@ using NSView = System.Object; using NSWindow = System.Object; #else -using UICollectionLayoutListConfiguration=System.Object; -using UIContentInsetsReference=System.Object; -using UIEdgeInsets=System.Object; -using UITraitCollection=System.Object; +using UICollectionLayoutListConfiguration = System.Object; +using UIContentInsetsReference = System.Object; +using UIEdgeInsets = System.Object; +using UITraitCollection = System.Object; #endif // !MONOMAC #if MONOMAC -using BezierPath=AppKit.NSBezierPath; -using Image=AppKit.NSImage; -using TextAlignment=AppKit.NSTextAlignment; -using LineBreakMode=AppKit.NSLineBreakMode; -using CollectionLayoutSectionOrthogonalScrollingBehavior=AppKit.NSCollectionLayoutSectionOrthogonalScrollingBehavior; -using CollectionElementCategory=AppKit.NSCollectionElementCategory; -using StringAttributes=AppKit.NSStringAttributes; -using View=AppKit.NSView; +using BezierPath = AppKit.NSBezierPath; +using Image = AppKit.NSImage; +using TextAlignment = AppKit.NSTextAlignment; +using LineBreakMode = AppKit.NSLineBreakMode; +using CollectionLayoutSectionOrthogonalScrollingBehavior = AppKit.NSCollectionLayoutSectionOrthogonalScrollingBehavior; +using CollectionElementCategory = AppKit.NSCollectionElementCategory; +using StringAttributes = AppKit.NSStringAttributes; +using View = AppKit.NSView; using UICollectionLayoutSectionOrthogonalScrollingProperties = System.Object; #else using BezierPath = UIKit.UIBezierPath; @@ -72,26 +72,26 @@ #endif #if MONOMAC - using IXWritingToolsCoordinatorDelegate = AppKit.INSWritingToolsCoordinatorDelegate; - using XWritingToolsBehavior = AppKit.NSWritingToolsBehavior; - using XWritingToolsCoordinator = AppKit.NSWritingToolsCoordinator; - using XWritingToolsCoordinatorAnimationParameters = AppKit.NSWritingToolsCoordinatorAnimationParameters; - using XWritingToolsCoordinatorContext = AppKit.NSWritingToolsCoordinatorContext; - using XWritingToolsCoordinatorContextScope = AppKit.NSWritingToolsCoordinatorContextScope; - using XWritingToolsCoordinatorDelegate = AppKit.NSWritingToolsCoordinatorDelegate; - using XWritingToolsCoordinatorDelegateReplaceRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateReplaceRangeCallback; - using XWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback; - using XWritingToolsCoordinatorDelegateRequestsContextsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsContextsCallback; - using XWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback; - using XWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback; - using XWritingToolsCoordinatorDelegateRequestsRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsRangeCallback; - using XWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback; - using XWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback; - using XWritingToolsCoordinatorState = AppKit.NSWritingToolsCoordinatorState; - using XWritingToolsCoordinatorTextAnimation = AppKit.NSWritingToolsCoordinatorTextAnimation; - using XWritingToolsCoordinatorTextReplacementReason = AppKit.NSWritingToolsCoordinatorTextReplacementReason; - using XWritingToolsCoordinatorTextUpdateReason = AppKit.NSWritingToolsCoordinatorTextUpdateReason; - using XWritingToolsResultOptions = AppKit.NSWritingToolsResultOptions; +using IXWritingToolsCoordinatorDelegate = AppKit.INSWritingToolsCoordinatorDelegate; +using XWritingToolsBehavior = AppKit.NSWritingToolsBehavior; +using XWritingToolsCoordinator = AppKit.NSWritingToolsCoordinator; +using XWritingToolsCoordinatorAnimationParameters = AppKit.NSWritingToolsCoordinatorAnimationParameters; +using XWritingToolsCoordinatorContext = AppKit.NSWritingToolsCoordinatorContext; +using XWritingToolsCoordinatorContextScope = AppKit.NSWritingToolsCoordinatorContextScope; +using XWritingToolsCoordinatorDelegate = AppKit.NSWritingToolsCoordinatorDelegate; +using XWritingToolsCoordinatorDelegateReplaceRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateReplaceRangeCallback; +using XWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback; +using XWritingToolsCoordinatorDelegateRequestsContextsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsContextsCallback; +using XWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback; +using XWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback; +using XWritingToolsCoordinatorDelegateRequestsRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsRangeCallback; +using XWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback; +using XWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback; +using XWritingToolsCoordinatorState = AppKit.NSWritingToolsCoordinatorState; +using XWritingToolsCoordinatorTextAnimation = AppKit.NSWritingToolsCoordinatorTextAnimation; +using XWritingToolsCoordinatorTextReplacementReason = AppKit.NSWritingToolsCoordinatorTextReplacementReason; +using XWritingToolsCoordinatorTextUpdateReason = AppKit.NSWritingToolsCoordinatorTextUpdateReason; +using XWritingToolsResultOptions = AppKit.NSWritingToolsResultOptions; #else using IXWritingToolsCoordinatorDelegate = UIKit.IUIWritingToolsCoordinatorDelegate; using XWritingToolsBehavior = UIKit.UIWritingToolsBehavior; @@ -4183,7 +4183,7 @@ interface NSTextList : NSCoding, NSCopying, NSSecureCoding { NativeHandle Constructor (NSTextListMarkerFormats format); #if NET - [BindAs (typeof (NSTextListMarkerFormats))] + [BindAs (typeof (NSTextListMarkerFormats))] #endif [Export ("markerFormat")] #if NET @@ -4733,20 +4733,20 @@ interface UIWritingToolsCoordinator : UIInteraction } #if MONOMAC - interface INSWritingToolsCoordinatorDelegate {} + interface INSWritingToolsCoordinatorDelegate { } #else interface IUIWritingToolsCoordinatorDelegate { } #endif #if MONOMAC - delegate void NSWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext[] contexts); + delegate void NSWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext [] contexts); delegate void NSWritingToolsCoordinatorDelegateReplaceRangeCallback ([NullAllowed] NSAttributedString replacementText); delegate void NSWritingToolsCoordinatorDelegateRequestsRangeCallback (NSRange range, NSUuid contextId); - delegate void NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback (BezierPath[] paths); - delegate void NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback (BezierPath[] paths); + delegate void NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback (BezierPath [] paths); + delegate void NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback (BezierPath [] paths); delegate void NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback ([NullAllowed] NSTextPreview [] view); // different signature vs other platforms delegate void NSWritingToolsCoordinatorDelegateRequestsPreviewCallback ([NullAllowed] NSTextPreview textPreview); // doesn't exist on other platforms - delegate void NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback (/* [BindAs (typeof (NSRange[]))] */ NSValue[] ranges); // BindAs doesn't work here + delegate void NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback (/* [BindAs (typeof (NSRange[]))] */ NSValue [] ranges); // BindAs doesn't work here delegate void NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback (View view); #else delegate void UIWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext [] contexts); From 7b72ef2281372fc519bc000021c5129431539335 Mon Sep 17 00:00:00 2001 From: GitHub Actions Autoformatter Date: Thu, 16 Jan 2025 08:23:53 +0000 Subject: [PATCH 2/5] Auto-format source code --- src/CoreFoundation/CFProxySupport.cs | 48 +- src/CoreMedia/CMSampleBuffer.cs | 2 +- src/CoreVideo/CVBuffer.cs | 4 +- src/Intents/INBillTypeResolutionResult.cs | 4 +- .../INCallRecordTypeResolutionResult.cs | 4 +- .../INCarSignalOptionsResolutionResult.cs | 4 +- ...MessageAttributeOptionsResolutionResult.cs | 4 +- .../INMessageAttributeResolutionResult.cs | 4 +- .../INPaymentStatusResolutionResult.cs | 4 +- src/Intents/INSpeakableString.cs | 2 +- .../INWorkoutGoalUnitTypeResolutionResult.cs | 4 +- .../INWorkoutLocationTypeResolutionResult.cs | 4 +- src/WebKit/WKPreferences.cs | 2 +- src/spritekit.cs | 5100 ++++++++--------- 14 files changed, 2595 insertions(+), 2595 deletions(-) diff --git a/src/CoreFoundation/CFProxySupport.cs b/src/CoreFoundation/CFProxySupport.cs index 3ccd9134be87..01feaaf66745 100644 --- a/src/CoreFoundation/CFProxySupport.cs +++ b/src/CoreFoundation/CFProxySupport.cs @@ -723,23 +723,23 @@ await Task.Run (() => { #else using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) #endif - using (var mode = new NSString ("Xamarin.iOS.Proxy")) { - - if (cancellationToken.IsCancellationRequested) - throw new OperationCanceledException ("Operation was cancelled."); - - cancellationToken.Register (() => { - //if user cancels, we invalidte the source, stop the runloop and remove the source - loopSource.Invalidate (); - runLoop.RemoveSource (loopSource, mode); - runLoop.Stop (); - }); - runLoop.AddSource (loopSource, mode); - // blocks until stop is called, will be done in the cb set previously - runLoop.RunInMode (mode, double.MaxValue, false); - // does not raise an error if source is not longer present, so no need to worry + using (var mode = new NSString ("Xamarin.iOS.Proxy")) { + + if (cancellationToken.IsCancellationRequested) + throw new OperationCanceledException ("Operation was cancelled."); + + cancellationToken.Register (() => { + //if user cancels, we invalidte the source, stop the runloop and remove the source + loopSource.Invalidate (); runLoop.RemoveSource (loopSource, mode); - } + runLoop.Stop (); + }); + runLoop.AddSource (loopSource, mode); + // blocks until stop is called, will be done in the cb set previously + runLoop.RunInMode (mode, double.MaxValue, false); + // does not raise an error if source is not longer present, so no need to worry + runLoop.RemoveSource (loopSource, mode); + } #if NET } // matches the unsafe block #endif @@ -787,14 +787,14 @@ await Task.Run (() => { #else using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) #endif - using (var mode = new NSString ("Xamarin.iOS.Proxy")) { - runLoop.AddSource (loopSource, mode); - runLoop.RunInMode (mode, double.MaxValue, false); - runLoop.RemoveSource (loopSource, mode); - } - pacCbData = Marshal.PtrToStructure (pacDataPtr)!; - // get data from the struct - outError = pacCbData.Error; + using (var mode = new NSString ("Xamarin.iOS.Proxy")) { + runLoop.AddSource (loopSource, mode); + runLoop.RunInMode (mode, double.MaxValue, false); + runLoop.RemoveSource (loopSource, mode); + } + pacCbData = Marshal.PtrToStructure (pacDataPtr)!; + // get data from the struct + outError = pacCbData.Error; #if NET } // unsafe #endif diff --git a/src/CoreMedia/CMSampleBuffer.cs b/src/CoreMedia/CMSampleBuffer.cs index c113833aae73..5ff8c4fab453 100644 --- a/src/CoreMedia/CMSampleBuffer.cs +++ b/src/CoreMedia/CMSampleBuffer.cs @@ -663,7 +663,7 @@ public CMSampleBufferError SetInvalidateCallback (Action invalid #if NET unsafe { #endif - return CMSampleBufferSetInvalidateCallback (Handle, null, 0); + return CMSampleBufferSetInvalidateCallback (Handle, null, 0); #if NET } #endif diff --git a/src/CoreVideo/CVBuffer.cs b/src/CoreVideo/CVBuffer.cs index 35284bd03ef8..8eebf4912d78 100644 --- a/src/CoreVideo/CVBuffer.cs +++ b/src/CoreVideo/CVBuffer.cs @@ -148,7 +148,7 @@ unsafe static IntPtr CVBufferCopyAttachment (IntPtr buffer, IntPtr key, out CVAt #if IOS || __MACCATALYST__ || TVOS if (SystemVersion.CheckiOS (15, 0)) #endif - return Runtime.GetINativeObject (CVBufferCopyAttachment (Handle, key.Handle, out attachmentMode), true); + return Runtime.GetINativeObject (CVBufferCopyAttachment (Handle, key.Handle, out attachmentMode), true); return Runtime.GetINativeObject (CVBufferGetAttachment (Handle, key.Handle, out attachmentMode), false); } #else @@ -201,7 +201,7 @@ unsafe static IntPtr CVBufferCopyAttachment (IntPtr buffer, IntPtr key, out CVAt #elif MONOMAC if (SystemVersion.CheckmacOS (12, 0)) #endif - return Runtime.GetINativeObject (CVBufferCopyAttachments (Handle, attachmentMode), true); + return Runtime.GetINativeObject (CVBufferCopyAttachments (Handle, attachmentMode), true); return Runtime.GetNSObject (CVBufferGetAttachments (Handle, attachmentMode), false); } diff --git a/src/Intents/INBillTypeResolutionResult.cs b/src/Intents/INBillTypeResolutionResult.cs index 9d33beb35a89..ea6e7a3a7e48 100644 --- a/src/Intents/INBillTypeResolutionResult.cs +++ b/src/Intents/INBillTypeResolutionResult.cs @@ -20,7 +20,7 @@ public static INBillTypeResolutionResult GetSuccess (INBillType resolvedValue) #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedBillType (resolvedValue); + return SuccessWithResolvedBillType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INBillTypeResolutionResult GetConfirmationRequired (INBillType val #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithBillTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithBillTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INCallRecordTypeResolutionResult.cs b/src/Intents/INCallRecordTypeResolutionResult.cs index a61cc33455e5..9246df1f7567 100644 --- a/src/Intents/INCallRecordTypeResolutionResult.cs +++ b/src/Intents/INCallRecordTypeResolutionResult.cs @@ -22,7 +22,7 @@ public static INCallRecordTypeResolutionResult GetSuccess (INCallRecordType reso #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return SuccessWithResolvedCallRecordType (resolvedValue); + return SuccessWithResolvedCallRecordType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -34,7 +34,7 @@ public static INCallRecordTypeResolutionResult GetConfirmationRequired (INCallRe #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return ConfirmationRequiredWithCallRecordTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithCallRecordTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INCarSignalOptionsResolutionResult.cs b/src/Intents/INCarSignalOptionsResolutionResult.cs index aa412bd8bdc4..bcdc2196ffc8 100644 --- a/src/Intents/INCarSignalOptionsResolutionResult.cs +++ b/src/Intents/INCarSignalOptionsResolutionResult.cs @@ -20,7 +20,7 @@ public static INCarSignalOptionsResolutionResult GetSuccess (INCarSignalOptions #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedCarSignalOptions (resolvedValue); + return SuccessWithResolvedCarSignalOptions (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INCarSignalOptionsResolutionResult GetConfirmationRequired (INCarS #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithCarSignalOptionsToConfirm (valueToConfirm); + return ConfirmationRequiredWithCarSignalOptionsToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INMessageAttributeOptionsResolutionResult.cs b/src/Intents/INMessageAttributeOptionsResolutionResult.cs index 68223a697189..ff6439b10fbc 100644 --- a/src/Intents/INMessageAttributeOptionsResolutionResult.cs +++ b/src/Intents/INMessageAttributeOptionsResolutionResult.cs @@ -23,7 +23,7 @@ public static INMessageAttributeOptionsResolutionResult GetSuccess (INMessageAtt #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return SuccessWithResolvedMessageAttributeOptions (resolvedValue); + return SuccessWithResolvedMessageAttributeOptions (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -35,7 +35,7 @@ public static INMessageAttributeOptionsResolutionResult GetConfirmationRequired #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return ConfirmationRequiredWithMessageAttributeOptionsToConfirm (valueToConfirm); + return ConfirmationRequiredWithMessageAttributeOptionsToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INMessageAttributeResolutionResult.cs b/src/Intents/INMessageAttributeResolutionResult.cs index 3c64ca4e8d65..5e8a2b8d8658 100644 --- a/src/Intents/INMessageAttributeResolutionResult.cs +++ b/src/Intents/INMessageAttributeResolutionResult.cs @@ -23,7 +23,7 @@ public static INMessageAttributeResolutionResult GetSuccess (INMessageAttribute #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return SuccessWithResolvedMessageAttribute (resolvedValue); + return SuccessWithResolvedMessageAttribute (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -35,7 +35,7 @@ public static INMessageAttributeResolutionResult GetConfirmationRequired (INMess #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - return ConfirmationRequiredWithMessageAttributeToConfirm (valueToConfirm); + return ConfirmationRequiredWithMessageAttributeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INPaymentStatusResolutionResult.cs b/src/Intents/INPaymentStatusResolutionResult.cs index 7c37db737020..05098efd515c 100644 --- a/src/Intents/INPaymentStatusResolutionResult.cs +++ b/src/Intents/INPaymentStatusResolutionResult.cs @@ -20,7 +20,7 @@ public static INPaymentStatusResolutionResult GetSuccess (INPaymentStatus resolv #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedPaymentStatus (resolvedValue); + return SuccessWithResolvedPaymentStatus (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INPaymentStatusResolutionResult GetConfirmationRequired (INPayment #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithPaymentStatusToConfirm (valueToConfirm); + return ConfirmationRequiredWithPaymentStatusToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INSpeakableString.cs b/src/Intents/INSpeakableString.cs index 8ad1f2dab945..7b6ed0e23a73 100644 --- a/src/Intents/INSpeakableString.cs +++ b/src/Intents/INSpeakableString.cs @@ -21,7 +21,7 @@ public INSpeakableString (string identifier, string spokenPhrase, string pronunc #elif MONOMAC if (SystemVersion.CheckmacOS (10, 13)) #endif - InitializeHandle (InitWithVocabularyIdentifier (identifier, spokenPhrase, pronunciationHint)); + InitializeHandle (InitWithVocabularyIdentifier (identifier, spokenPhrase, pronunciationHint)); #if !TVOS else InitializeHandle (InitWithIdentifier (identifier, spokenPhrase, pronunciationHint)); diff --git a/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs b/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs index 7992a54356d8..46020fca83a0 100644 --- a/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs +++ b/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs @@ -20,7 +20,7 @@ public static INWorkoutGoalUnitTypeResolutionResult GetSuccess (INWorkoutGoalUni #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedWorkoutGoalUnitType (resolvedValue); + return SuccessWithResolvedWorkoutGoalUnitType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INWorkoutGoalUnitTypeResolutionResult GetConfirmationRequired (INW #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithWorkoutGoalUnitTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithWorkoutGoalUnitTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/Intents/INWorkoutLocationTypeResolutionResult.cs b/src/Intents/INWorkoutLocationTypeResolutionResult.cs index 1fc4bcef3ba3..0afa363d03e1 100644 --- a/src/Intents/INWorkoutLocationTypeResolutionResult.cs +++ b/src/Intents/INWorkoutLocationTypeResolutionResult.cs @@ -20,7 +20,7 @@ public static INWorkoutLocationTypeResolutionResult GetSuccess (INWorkoutLocatio #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return SuccessWithResolvedWorkoutLocationType (resolvedValue); + return SuccessWithResolvedWorkoutLocationType (resolvedValue); else return SuccessWithResolvedValue (resolvedValue); } @@ -30,7 +30,7 @@ public static INWorkoutLocationTypeResolutionResult GetConfirmationRequired (INW #if IOS if (SystemVersion.CheckiOS (11, 0)) #endif - return ConfirmationRequiredWithWorkoutLocationTypeToConfirm (valueToConfirm); + return ConfirmationRequiredWithWorkoutLocationTypeToConfirm (valueToConfirm); else return ConfirmationRequiredWithValueToConfirm (valueToConfirm); } diff --git a/src/WebKit/WKPreferences.cs b/src/WebKit/WKPreferences.cs index b016487cc737..d498c8262456 100644 --- a/src/WebKit/WKPreferences.cs +++ b/src/WebKit/WKPreferences.cs @@ -28,7 +28,7 @@ public bool TextInteractionEnabled { #elif MONOMAC if (SystemVersion.CheckmacOS (12, 0)) #endif - return _NewGetTextInteractionEnabled (); + return _NewGetTextInteractionEnabled (); else return _OldTextInteractionEnabled; } diff --git a/src/spritekit.cs b/src/spritekit.cs index aa35388789f3..f832ac4342d9 100644 --- a/src/spritekit.cs +++ b/src/spritekit.cs @@ -140,205 +140,205 @@ partial interface SKNode : NSSecureCoding, NSCopying, UIFocusItem, UIFocusItemCo #else #error Unknown platform #endif - [DesignatedInitializer] - [Export ("init")] - NativeHandle Constructor (); - - [Static, Export ("node")] - SKNode Create (); - - [MacCatalyst (13, 1)] - [Static] - [Export ("nodeWithFileNamed:")] - [return: NullAllowed] - SKNode Create (string filename); - - [MacCatalyst (13, 1)] - [Internal] - [Static] - [Export ("nodeWithFileNamed:securelyWithClasses:andError:")] - [return: NullAllowed] - SKNode Create (string filename, IntPtr classesPtr, out NSError error); - - [Export ("frame")] + [DesignatedInitializer] + [Export ("init")] + NativeHandle Constructor (); + + [Static, Export ("node")] + SKNode Create (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("nodeWithFileNamed:")] + [return: NullAllowed] + SKNode Create (string filename); + + [MacCatalyst (13, 1)] + [Internal] + [Static] + [Export ("nodeWithFileNamed:securelyWithClasses:andError:")] + [return: NullAllowed] + SKNode Create (string filename, IntPtr classesPtr, out NSError error); + + [Export ("frame")] #if !MONOMAC - // For iOS+tvOS we also get this property from the UIFocusItem protocol, but we redefine it here to get the right availability attributes. - new + // For iOS+tvOS we also get this property from the UIFocusItem protocol, but we redefine it here to get the right availability attributes. + new #endif - CGRect Frame { get; } + CGRect Frame { get; } - [Export ("calculateAccumulatedFrame")] - CGRect CalculateAccumulatedFrame (); + [Export ("calculateAccumulatedFrame")] + CGRect CalculateAccumulatedFrame (); - [Export ("position")] - CGPoint Position { get; set; } + [Export ("position")] + CGPoint Position { get; set; } - [Export ("zPosition")] - nfloat ZPosition { get; set; } + [Export ("zPosition")] + nfloat ZPosition { get; set; } - [Export ("zRotation")] - nfloat ZRotation { get; set; } + [Export ("zRotation")] + nfloat ZRotation { get; set; } - [Export ("xScale")] - nfloat XScale { get; set; } + [Export ("xScale")] + nfloat XScale { get; set; } - [Export ("yScale")] - nfloat YScale { get; set; } + [Export ("yScale")] + nfloat YScale { get; set; } - [Export ("speed")] - nfloat Speed { get; set; } + [Export ("speed")] + nfloat Speed { get; set; } - [Export ("alpha")] - nfloat Alpha { get; set; } + [Export ("alpha")] + nfloat Alpha { get; set; } - [Export ("paused")] - bool Paused { [Bind ("isPaused")] get; set; } + [Export ("paused")] + bool Paused { [Bind ("isPaused")] get; set; } - [Export ("hidden")] - bool Hidden { [Bind ("isHidden")] get; set; } + [Export ("hidden")] + bool Hidden { [Bind ("isHidden")] get; set; } - [Export ("userInteractionEnabled")] - bool UserInteractionEnabled { [Bind ("isUserInteractionEnabled")] get; set; } + [Export ("userInteractionEnabled")] + bool UserInteractionEnabled { [Bind ("isUserInteractionEnabled")] get; set; } - [NoMac] - [MacCatalyst (13, 1)] - [Export ("focusBehavior", ArgumentSemantic.Assign)] - SKNodeFocusBehavior FocusBehavior { get; set; } + [NoMac] + [MacCatalyst (13, 1)] + [Export ("focusBehavior", ArgumentSemantic.Assign)] + SKNodeFocusBehavior FocusBehavior { get; set; } - [Export ("parent")] - [NullAllowed] - SKNode Parent { get; } + [Export ("parent")] + [NullAllowed] + SKNode Parent { get; } - [Export ("children")] - SKNode [] Children { get; } + [Export ("children")] + SKNode [] Children { get; } - [NullAllowed] // by default this property is null - [Export ("name", ArgumentSemantic.Copy)] - string Name { get; set; } + [NullAllowed] // by default this property is null + [Export ("name", ArgumentSemantic.Copy)] + string Name { get; set; } - [Export ("scene")] - [NullAllowed] - SKScene Scene { get; } + [Export ("scene")] + [NullAllowed] + SKScene Scene { get; } - [Export ("physicsBody", ArgumentSemantic.Retain), NullAllowed] - SKPhysicsBody PhysicsBody { get; set; } + [Export ("physicsBody", ArgumentSemantic.Retain), NullAllowed] + SKPhysicsBody PhysicsBody { get; set; } - [NullAllowed] // by default this property is null - [Export ("userData", ArgumentSemantic.Retain)] - NSMutableDictionary UserData { get; set; } + [NullAllowed] // by default this property is null + [Export ("userData", ArgumentSemantic.Retain)] + NSMutableDictionary UserData { get; set; } - [Export ("setScale:")] - void SetScale (nfloat scale); + [Export ("setScale:")] + void SetScale (nfloat scale); - [Export ("addChild:")] - [PostGet ("Children")] - void AddChild (SKNode node); + [Export ("addChild:")] + [PostGet ("Children")] + void AddChild (SKNode node); - [Export ("insertChild:atIndex:")] - [PostGet ("Children")] - void InsertChild (SKNode node, nint index); + [Export ("insertChild:atIndex:")] + [PostGet ("Children")] + void InsertChild (SKNode node, nint index); - [Export ("removeChildrenInArray:")] - [PostGet ("Children")] - void RemoveChildren (SKNode [] nodes); + [Export ("removeChildrenInArray:")] + [PostGet ("Children")] + void RemoveChildren (SKNode [] nodes); - [Export ("removeAllChildren")] - [PostGet ("Children")] - void RemoveAllChildren (); + [Export ("removeAllChildren")] + [PostGet ("Children")] + void RemoveAllChildren (); - [Export ("removeFromParent")] - void RemoveFromParent (); + [Export ("removeFromParent")] + void RemoveFromParent (); - [Export ("childNodeWithName:")] - [return: NullAllowed] - SKNode GetChildNode (string name); + [Export ("childNodeWithName:")] + [return: NullAllowed] + SKNode GetChildNode (string name); - [Export ("enumerateChildNodesWithName:usingBlock:")] - void EnumerateChildNodes (string name, SKNodeChildEnumeratorHandler enumerationHandler); + [Export ("enumerateChildNodesWithName:usingBlock:")] + void EnumerateChildNodes (string name, SKNodeChildEnumeratorHandler enumerationHandler); - [Export ("runAction:")] - void RunAction (SKAction action); + [Export ("runAction:")] + void RunAction (SKAction action); - [Async] - [Export ("runAction:completion:")] - void RunAction (SKAction action, Action completionHandler); + [Async] + [Export ("runAction:completion:")] + void RunAction (SKAction action, Action completionHandler); - [Export ("runAction:withKey:")] - void RunAction (SKAction action, string key); + [Export ("runAction:withKey:")] + void RunAction (SKAction action, string key); - [Export ("hasActions")] - bool HasActions { get; } + [Export ("hasActions")] + bool HasActions { get; } - [Export ("actionForKey:")] - [return: NullAllowed] - SKAction GetActionForKey (string key); + [Export ("actionForKey:")] + [return: NullAllowed] + SKAction GetActionForKey (string key); - [Export ("removeActionForKey:")] - void RemoveActionForKey (string key); + [Export ("removeActionForKey:")] + void RemoveActionForKey (string key); - [Export ("removeAllActions")] - void RemoveAllActions (); + [Export ("removeAllActions")] + void RemoveAllActions (); - [Export ("containsPoint:")] - bool ContainsPoint (CGPoint point); + [Export ("containsPoint:")] + bool ContainsPoint (CGPoint point); - [Export ("nodeAtPoint:")] - SKNode GetNodeAtPoint (CGPoint point); + [Export ("nodeAtPoint:")] + SKNode GetNodeAtPoint (CGPoint point); - [Export ("nodesAtPoint:")] - SKNode [] GetNodesAtPoint (CGPoint point); + [Export ("nodesAtPoint:")] + SKNode [] GetNodesAtPoint (CGPoint point); - [Export ("convertPoint:fromNode:")] - CGPoint ConvertPointFromNode (CGPoint point, SKNode sourceNode); + [Export ("convertPoint:fromNode:")] + CGPoint ConvertPointFromNode (CGPoint point, SKNode sourceNode); - [Export ("convertPoint:toNode:")] - CGPoint ConvertPointToNode (CGPoint point, SKNode sourceNode); + [Export ("convertPoint:toNode:")] + CGPoint ConvertPointToNode (CGPoint point, SKNode sourceNode); - [Export ("intersectsNode:")] - bool IntersectsNode (SKNode node); + [Export ("intersectsNode:")] + bool IntersectsNode (SKNode node); - [MacCatalyst (13, 1)] - [Export ("isEqualToNode:")] - bool IsEqual (SKNode node); + [MacCatalyst (13, 1)] + [Export ("isEqualToNode:")] + bool IsEqual (SKNode node); - [Export ("inParentHierarchy:")] - bool InParentHierarchy (SKNode node); + [Export ("inParentHierarchy:")] + bool InParentHierarchy (SKNode node); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("reachConstraints", ArgumentSemantic.Copy)] - SKReachConstraints ReachConstraints { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("reachConstraints", ArgumentSemantic.Copy)] + SKReachConstraints ReachConstraints { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("constraints", ArgumentSemantic.Copy)] - SKConstraint [] Constraints { get; set; } - - [MacCatalyst (13, 1)] - [Export ("objectForKeyedSubscript:")] - SKNode GetObjectsMatching (string nameExpression); - - [MacCatalyst (13, 1)] - [Export ("moveToParent:")] - void MoveToParent (SKNode parent); - - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodeBounds:")] - GKPolygonObstacle [] ObstaclesFromNodeBounds (SKNode [] nodes); - - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodePhysicsBodies:")] - GKPolygonObstacle [] ObstaclesFromNodePhysicsBodies (SKNode [] nodes); - - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromSpriteTextures:accuracy:")] - GKPolygonObstacle [] ObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("constraints", ArgumentSemantic.Copy)] + SKConstraint [] Constraints { get; set; } + + [MacCatalyst (13, 1)] + [Export ("objectForKeyedSubscript:")] + SKNode GetObjectsMatching (string nameExpression); + + [MacCatalyst (13, 1)] + [Export ("moveToParent:")] + void MoveToParent (SKNode parent); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodeBounds:")] + GKPolygonObstacle [] ObstaclesFromNodeBounds (SKNode [] nodes); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodePhysicsBodies:")] + GKPolygonObstacle [] ObstaclesFromNodePhysicsBodies (SKNode [] nodes); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromSpriteTextures:accuracy:")] + GKPolygonObstacle [] ObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); #if !NET [Deprecated (PlatformName.iOS, 10, 0, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] @@ -358,1496 +358,1496 @@ partial interface SKNode : NSSecureCoding, NSCopying, UIFocusItem, UIFocusItemCo void SetValue (SKAttributeValue value, string key); #endif - // Extensions from GameplayKit, inlined to avoid ugly static extension syntax - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromSpriteTextures:accuracy:")] - GKPolygonObstacle [] GetObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); - - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodeBounds:")] - GKPolygonObstacle [] GetObstaclesFromNodeBounds (SKNode [] nodes); - - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodePhysicsBodies:")] - GKPolygonObstacle [] GetObstaclesFromNodePhysicsBodies (SKNode [] nodes); - } - - [NoiOS] - [NoTV] - [NoMacCatalyst] - [Category, BaseType (typeof (NSEvent))] - partial interface SKNodeEvent_NSEvent { - - [Export ("locationInNode:")] - CGPoint LocationInNode (SKNode node); - } - - /// Extension methods for that aide with conversion to Sprite Kit coordinates. - [NoMac] + // Extensions from GameplayKit, inlined to avoid ugly static extension syntax [MacCatalyst (13, 1)] - [Category, BaseType (typeof (UITouch))] - partial interface SKNodeTouches_UITouch { - - [Export ("locationInNode:")] - CGPoint LocationInNode (SKNode node); - - [Export ("previousLocationInNode:")] - CGPoint PreviousLocationInNode (SKNode node); - } + [Static] + [Export ("obstaclesFromSpriteTextures:accuracy:")] + GKPolygonObstacle [] GetObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); - /// An that applies a Core Graphics to its output. - /// - /// Application developers should ensure that is . - /// Note that is a subclass of . - /// - /// Apple documentation for SKEffectNode [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - partial interface SKEffectNode : SKWarpable { + [Static] + [Export ("obstaclesFromNodeBounds:")] + GKPolygonObstacle [] GetObstaclesFromNodeBounds (SKNode [] nodes); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("filter", ArgumentSemantic.Retain)] - CIFilter Filter { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodePhysicsBodies:")] + GKPolygonObstacle [] GetObstaclesFromNodePhysicsBodies (SKNode [] nodes); +} - [Export ("shouldCenterFilter")] - bool ShouldCenterFilter { get; set; } +[NoiOS] +[NoTV] +[NoMacCatalyst] +[Category, BaseType (typeof (NSEvent))] +partial interface SKNodeEvent_NSEvent { - [Export ("shouldEnableEffects")] - bool ShouldEnableEffects { get; set; } + [Export ("locationInNode:")] + CGPoint LocationInNode (SKNode node); +} - [Export ("shouldRasterize")] - bool ShouldRasterize { get; set; } +/// Extension methods for that aide with conversion to Sprite Kit coordinates. +[NoMac] +[MacCatalyst (13, 1)] +[Category, BaseType (typeof (UITouch))] +partial interface SKNodeTouches_UITouch { - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [Export ("locationInNode:")] + CGPoint LocationInNode (SKNode node); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [Export ("previousLocationInNode:")] + CGPoint PreviousLocationInNode (SKNode node); +} - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } +/// An that applies a Core Graphics to its output. +/// +/// Application developers should ensure that is . +/// Note that is a subclass of . +/// +/// Apple documentation for SKEffectNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +partial interface SKEffectNode : SKWarpable { - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("filter", ArgumentSemantic.Retain)] + CIFilter Filter { get; set; } - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); - } + [Export ("shouldCenterFilter")] + bool ShouldCenterFilter { get; set; } - /// A method that derives a force by applying the physics of a field to a body that is within the field. - delegate Vector3 SKFieldForceEvaluator (/* vector_float3 */ Vector4 position, /* vector_float3 */ Vector4 velocity, float /* float, not CGFloat */ mass, float /* float, not CGFloat */ charge, double time); + [Export ("shouldEnableEffects")] + bool ShouldEnableEffects { get; set; } - /// Applies physics effects within a portion of a scene. - /// - /// Apple documentation for SKFieldNode - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - interface SKFieldNode { - [Export ("region", ArgumentSemantic.Retain)] - [NullAllowed] - SKRegion Region { get; set; } + [Export ("shouldRasterize")] + bool ShouldRasterize { get; set; } - [Export ("strength")] - float Strength { get; set; } /* float, not CGFloat */ + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [Export ("falloff")] - float Falloff { get; set; } /* float, not CGFloat */ + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - [Export ("minimumRadius")] + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - float MinimumRadius { get; set; } /* float, not CGFloat */ + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [Export ("enabled")] - bool Enabled { [Bind ("isEnabled")] get; set; } + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); +} - [Export ("exclusive")] - bool Exclusive { [Bind ("isExclusive")] get; set; } +/// A method that derives a force by applying the physics of a field to a body that is within the field. +delegate Vector3 SKFieldForceEvaluator (/* vector_float3 */ Vector4 position, /* vector_float3 */ Vector4 velocity, float /* float, not CGFloat */ mass, float /* float, not CGFloat */ charge, double time); - [Export ("categoryBitMask")] - uint CategoryBitMask { get; set; } /* uint32_t */ +/// Applies physics effects within a portion of a scene. +/// +/// Apple documentation for SKFieldNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +interface SKFieldNode { + [Export ("region", ArgumentSemantic.Retain)] + [NullAllowed] + SKRegion Region { get; set; } - [Export ("direction")] - /* This was typed as Vector4 since sizeof the native type (vector_float3) = 16 */ - Vector4 Direction { - [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] - set; - } + [Export ("strength")] + float Strength { get; set; } /* float, not CGFloat */ - [Export ("smoothness")] - float Smoothness { get; set; } /* float, not CGFloat */ + [Export ("falloff")] + float Falloff { get; set; } /* float, not CGFloat */ - [Export ("animationSpeed")] - float AnimationSpeed { get; set; } /* float, not CGFloat */ + [Export ("minimumRadius")] - [Export ("texture", ArgumentSemantic.Retain)] - [NullAllowed] - SKTexture Texture { get; set; } + float MinimumRadius { get; set; } /* float, not CGFloat */ - [Static, Export ("dragField")] - SKFieldNode CreateDragField (); + [Export ("enabled")] + bool Enabled { [Bind ("isEnabled")] get; set; } - [Static, Export ("vortexField")] - SKFieldNode CreateVortexField (); + [Export ("exclusive")] + bool Exclusive { [Bind ("isExclusive")] get; set; } - [Static, Export ("radialGravityField")] - SKFieldNode CreateRadialGravityField (); + [Export ("categoryBitMask")] + uint CategoryBitMask { get; set; } /* uint32_t */ - [Static, Export ("linearGravityFieldWithVector:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKFieldNode CreateLinearGravityField (/* vector_float3 */ Vector4 direction); + [Export ("direction")] + /* This was typed as Vector4 since sizeof the native type (vector_float3) = 16 */ + Vector4 Direction { + [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] + set; + } - [Static, Export ("velocityFieldWithVector:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKFieldNode CreateVelocityField (/* vector_float3 */ Vector4 direction); + [Export ("smoothness")] + float Smoothness { get; set; } /* float, not CGFloat */ - [Static, Export ("velocityFieldWithTexture:")] - SKFieldNode CreateVelocityField (SKTexture velocityTexture); + [Export ("animationSpeed")] + float AnimationSpeed { get; set; } /* float, not CGFloat */ - [Static, Export ("noiseFieldWithSmoothness:animationSpeed:")] - SKFieldNode CreateNoiseField (nfloat smoothness, nfloat speed); + [Export ("texture", ArgumentSemantic.Retain)] + [NullAllowed] + SKTexture Texture { get; set; } - [Static, Export ("turbulenceFieldWithSmoothness:animationSpeed:")] - SKFieldNode CreateTurbulenceField (nfloat smoothness, nfloat speed); + [Static, Export ("dragField")] + SKFieldNode CreateDragField (); - [Static, Export ("springField")] - SKFieldNode CreateSpringField (); + [Static, Export ("vortexField")] + SKFieldNode CreateVortexField (); - [Static, Export ("electricField")] - SKFieldNode CreateElectricField (); + [Static, Export ("radialGravityField")] + SKFieldNode CreateRadialGravityField (); - [Static, Export ("magneticField")] - SKFieldNode CreateMagneticField (); + [Static, Export ("linearGravityFieldWithVector:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKFieldNode CreateLinearGravityField (/* vector_float3 */ Vector4 direction); - [Static, Export ("customFieldWithEvaluationBlock:")] - SKFieldNode CreateCustomField (SKFieldForceEvaluator evaluator); - } + [Static, Export ("velocityFieldWithVector:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKFieldNode CreateVelocityField (/* vector_float3 */ Vector4 direction); - /// - [MacCatalyst (13, 1)] - [BaseType (typeof (SKEffectNode))] - interface SKScene - : GKSceneRootNodeType { - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [Static, Export ("velocityFieldWithTexture:")] + SKFieldNode CreateVelocityField (SKTexture velocityTexture); - [Static, Export ("sceneWithSize:")] - SKScene FromSize (CGSize size); + [Static, Export ("noiseFieldWithSmoothness:animationSpeed:")] + SKFieldNode CreateNoiseField (nfloat smoothness, nfloat speed); - [MacCatalyst (13, 1)] - [Export ("sceneDidLoad")] - void SceneDidLoad (); + [Static, Export ("turbulenceFieldWithSmoothness:animationSpeed:")] + SKFieldNode CreateTurbulenceField (nfloat smoothness, nfloat speed); - [Export ("size")] - CGSize Size { get; set; } + [Static, Export ("springField")] + SKFieldNode CreateSpringField (); - [Export ("scaleMode")] - SKSceneScaleMode ScaleMode { get; set; } + [Static, Export ("electricField")] + SKFieldNode CreateElectricField (); - [Export ("backgroundColor", ArgumentSemantic.Retain)] - UIColor BackgroundColor { get; set; } + [Static, Export ("magneticField")] + SKFieldNode CreateMagneticField (); - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } + [Static, Export ("customFieldWithEvaluationBlock:")] + SKFieldNode CreateCustomField (SKFieldForceEvaluator evaluator); +} - [Export ("physicsWorld")] - SKPhysicsWorld PhysicsWorld { get; } +/// +[MacCatalyst (13, 1)] +[BaseType (typeof (SKEffectNode))] +interface SKScene + : GKSceneRootNodeType { + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [MacCatalyst (13, 1)] - [Export ("convertPointFromView:")] - CGPoint ConvertPointFromView (CGPoint point); + [Static, Export ("sceneWithSize:")] + SKScene FromSize (CGSize size); - [MacCatalyst (13, 1)] - [Export ("convertPointToView:")] - CGPoint ConvertPointToView (CGPoint point); + [MacCatalyst (13, 1)] + [Export ("sceneDidLoad")] + void SceneDidLoad (); - [MacCatalyst (13, 1)] - [Export ("view", ArgumentSemantic.Weak)] - [NullAllowed] - SKView View { get; } + [Export ("size")] + CGSize Size { get; set; } - [Export ("update:")] - void Update (double currentTime); + [Export ("scaleMode")] + SKSceneScaleMode ScaleMode { get; set; } - [Export ("didEvaluateActions")] - void DidEvaluateActions (); + [Export ("backgroundColor", ArgumentSemantic.Retain)] + UIColor BackgroundColor { get; set; } - [Export ("didSimulatePhysics")] - void DidSimulatePhysics (); + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } - [MacCatalyst (13, 1)] - [Export ("didMoveToView:")] - void DidMoveToView (SKView view); + [Export ("physicsWorld")] + SKPhysicsWorld PhysicsWorld { get; } - [MacCatalyst (13, 1)] - [Export ("willMoveFromView:")] - void WillMoveFromView (SKView view); + [MacCatalyst (13, 1)] + [Export ("convertPointFromView:")] + CGPoint ConvertPointFromView (CGPoint point); - [Export ("didChangeSize:")] - void DidChangeSize (CGSize oldSize); + [MacCatalyst (13, 1)] + [Export ("convertPointToView:")] + CGPoint ConvertPointToView (CGPoint point); - [MacCatalyst (13, 1)] - [Export ("didApplyConstraints")] - void DidApplyConstraints (); + [MacCatalyst (13, 1)] + [Export ("view", ArgumentSemantic.Weak)] + [NullAllowed] + SKView View { get; } - [MacCatalyst (13, 1)] - [Export ("didFinishUpdate")] - void DidFinishUpdate (); + [Export ("update:")] + void Update (double currentTime); - [MacCatalyst (13, 1)] - [Export ("delegate", ArgumentSemantic.Weak), NullAllowed] - NSObject WeakDelegate { get; set; } + [Export ("didEvaluateActions")] + void DidEvaluateActions (); - [MacCatalyst (13, 1)] - [Wrap ("WeakDelegate")] - ISKSceneDelegate Delegate { get; set; } + [Export ("didSimulatePhysics")] + void DidSimulatePhysics (); - [MacCatalyst (13, 1)] - [Export ("audioEngine", ArgumentSemantic.Retain)] - AVAudioEngine AudioEngine { get; } + [MacCatalyst (13, 1)] + [Export ("didMoveToView:")] + void DidMoveToView (SKView view); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("camera", ArgumentSemantic.Weak)] - SKCameraNode Camera { get; set; } + [MacCatalyst (13, 1)] + [Export ("willMoveFromView:")] + void WillMoveFromView (SKView view); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("listener", ArgumentSemantic.Weak)] - SKNode Listener { get; set; } - } + [Export ("didChangeSize:")] + void DidChangeSize (CGSize oldSize); - /// Interface representing the required methods (if any) of the protocol . - /// - /// This interface contains the required methods (if any) from the protocol defined by . - /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. - /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. - /// - interface ISKSceneDelegate { } + [MacCatalyst (13, 1)] + [Export ("didApplyConstraints")] + void DidApplyConstraints (); - /// Delegate object for SKScene objects. Provides methods relating to animation events. - /// - /// Apple documentation for SKSceneDelegate [MacCatalyst (13, 1)] - [Protocol, Model] - [BaseType (typeof (NSObject))] - interface SKSceneDelegate { - [Export ("update:forScene:")] - void Update (double currentTime, SKScene scene); + [Export ("didFinishUpdate")] + void DidFinishUpdate (); - [Export ("didEvaluateActionsForScene:")] - void DidEvaluateActions (SKScene scene); + [MacCatalyst (13, 1)] + [Export ("delegate", ArgumentSemantic.Weak), NullAllowed] + NSObject WeakDelegate { get; set; } - [Export ("didSimulatePhysicsForScene:")] - void DidSimulatePhysics (SKScene scene); + [MacCatalyst (13, 1)] + [Wrap ("WeakDelegate")] + ISKSceneDelegate Delegate { get; set; } - [Export ("didApplyConstraintsForScene:")] - void DidApplyConstraints (SKScene scene); + [MacCatalyst (13, 1)] + [Export ("audioEngine", ArgumentSemantic.Retain)] + AVAudioEngine AudioEngine { get; } - [Export ("didFinishUpdateForScene:")] - void DidFinishUpdate (SKScene scene); - } + [MacCatalyst (13, 1)] + [NullAllowed, Export ("camera", ArgumentSemantic.Weak)] + SKCameraNode Camera { get; set; } - /// An OpenGL ES fragment shader. - /// - /// Apple documentation for SKShader [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKShader : NSCopying, NSSecureCoding { - [Export ("initWithSource:")] - NativeHandle Constructor (string shaderSourceCode); + [NullAllowed, Export ("listener", ArgumentSemantic.Weak)] + SKNode Listener { get; set; } +} - [Export ("initWithSource:uniforms:")] - NativeHandle Constructor (string sharedSourceCode, SKUniform [] uniforms); +/// Interface representing the required methods (if any) of the protocol . +/// +/// This interface contains the required methods (if any) from the protocol defined by . +/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. +/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. +/// +interface ISKSceneDelegate { } + +/// Delegate object for SKScene objects. Provides methods relating to animation events. +/// +/// Apple documentation for SKSceneDelegate +[MacCatalyst (13, 1)] +[Protocol, Model] +[BaseType (typeof (NSObject))] +interface SKSceneDelegate { + [Export ("update:forScene:")] + void Update (double currentTime, SKScene scene); + + [Export ("didEvaluateActionsForScene:")] + void DidEvaluateActions (SKScene scene); + + [Export ("didSimulatePhysicsForScene:")] + void DidSimulatePhysics (SKScene scene); + + [Export ("didApplyConstraintsForScene:")] + void DidApplyConstraints (SKScene scene); + + [Export ("didFinishUpdateForScene:")] + void DidFinishUpdate (SKScene scene); +} - [NullAllowed] // by default this property is null - [Export ("source")] - string Source { get; set; } +/// An OpenGL ES fragment shader. +/// +/// Apple documentation for SKShader +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKShader : NSCopying, NSSecureCoding { + [Export ("initWithSource:")] + NativeHandle Constructor (string shaderSourceCode); - // @property (copy) NSArray * uniforms; - [Export ("uniforms", ArgumentSemantic.Copy)] - SKUniform [] Uniforms { get; set; } + [Export ("initWithSource:uniforms:")] + NativeHandle Constructor (string sharedSourceCode, SKUniform [] uniforms); - // @required + (instancetype)shader; - [Static, Export ("shader")] - SKShader Create (); + [NullAllowed] // by default this property is null + [Export ("source")] + string Source { get; set; } - [Static, Export ("shaderWithSource:")] - SKShader FromShaderSourceCode (string source); + // @property (copy) NSArray * uniforms; + [Export ("uniforms", ArgumentSemantic.Copy)] + SKUniform [] Uniforms { get; set; } - [Static, Export ("shaderWithSource:uniforms:")] - SKShader FromShaderSourceCode (string source, SKUniform [] uniforms); + // @required + (instancetype)shader; + [Static, Export ("shader")] + SKShader Create (); - [Static, Export ("shaderWithFileNamed:")] - SKShader FromFile (string name); + [Static, Export ("shaderWithSource:")] + SKShader FromShaderSourceCode (string source); - [Export ("addUniform:")] - void AddUniform (SKUniform uniform); + [Static, Export ("shaderWithSource:uniforms:")] + SKShader FromShaderSourceCode (string source, SKUniform [] uniforms); - [Export ("uniformNamed:")] - [return: NullAllowed] - SKUniform GetUniform (string uniformName); + [Static, Export ("shaderWithFileNamed:")] + SKShader FromFile (string name); - [Export ("removeUniformNamed:")] - void RemoveUniform (string uniforName); + [Export ("addUniform:")] + void AddUniform (SKUniform uniform); - [MacCatalyst (13, 1)] - [Export ("attributes", ArgumentSemantic.Copy)] - SKAttribute [] Attributes { get; set; } - } + [Export ("uniformNamed:")] + [return: NullAllowed] + SKUniform GetUniform (string uniformName); - /// A that displays a textured, colored sprite. - /// - /// Apple documentation for SKSpriteNode - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - partial interface SKSpriteNode : SKWarpable { + [Export ("removeUniformNamed:")] + void RemoveUniform (string uniforName); - [Static, Export ("spriteNodeWithTexture:size:")] - SKSpriteNode FromTexture ([NullAllowed] SKTexture texture, CGSize size); + [MacCatalyst (13, 1)] + [Export ("attributes", ArgumentSemantic.Copy)] + SKAttribute [] Attributes { get; set; } +} - [Static, Export ("spriteNodeWithTexture:")] - SKSpriteNode FromTexture ([NullAllowed] SKTexture texture); +/// A that displays a textured, colored sprite. +/// +/// Apple documentation for SKSpriteNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +partial interface SKSpriteNode : SKWarpable { - [Static, Export ("spriteNodeWithImageNamed:")] - SKSpriteNode FromImageNamed (string name); + [Static, Export ("spriteNodeWithTexture:size:")] + SKSpriteNode FromTexture ([NullAllowed] SKTexture texture, CGSize size); - [Static, Export ("spriteNodeWithColor:size:")] - SKSpriteNode FromColor (UIColor color, CGSize size); + [Static, Export ("spriteNodeWithTexture:")] + SKSpriteNode FromTexture ([NullAllowed] SKTexture texture); - [DesignatedInitializer] - [Export ("initWithTexture:color:size:")] - NativeHandle Constructor ([NullAllowed] SKTexture texture, UIColor color, CGSize size); + [Static, Export ("spriteNodeWithImageNamed:")] + SKSpriteNode FromImageNamed (string name); - [Export ("initWithTexture:")] - NativeHandle Constructor ([NullAllowed] SKTexture texture); + [Static, Export ("spriteNodeWithColor:size:")] + SKSpriteNode FromColor (UIColor color, CGSize size); - // can't be null -> crash - [Export ("initWithImageNamed:")] - NativeHandle Constructor (string name); + [DesignatedInitializer] + [Export ("initWithTexture:color:size:")] + NativeHandle Constructor ([NullAllowed] SKTexture texture, UIColor color, CGSize size); - [Export ("initWithColor:size:")] - NativeHandle Constructor (UIColor color, CGSize size); + [Export ("initWithTexture:")] + NativeHandle Constructor ([NullAllowed] SKTexture texture); - [Export ("texture", ArgumentSemantic.Retain)] - [NullAllowed] - SKTexture Texture { get; set; } + // can't be null -> crash + [Export ("initWithImageNamed:")] + NativeHandle Constructor (string name); - [Export ("centerRect")] - CGRect CenterRect { get; set; } + [Export ("initWithColor:size:")] + NativeHandle Constructor (UIColor color, CGSize size); - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + [Export ("texture", ArgumentSemantic.Retain)] + [NullAllowed] + SKTexture Texture { get; set; } - [Export ("color", ArgumentSemantic.Retain)] - [NullAllowed] // it's actually null-resetable (see unit tests) - UIColor Color { get; set; } + [Export ("centerRect")] + CGRect CenterRect { get; set; } - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } + [Export ("color", ArgumentSemantic.Retain)] + [NullAllowed] // it's actually null-resetable (see unit tests) + UIColor Color { get; set; } - [Export ("size")] - CGSize Size { get; set; } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - // - // iOS 8 - // + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } + [Export ("size")] + CGSize Size { get; set; } - [MacCatalyst (13, 1)] - [Static, Export ("spriteNodeWithTexture:normalMap:")] - SKSpriteNode Create ([NullAllowed] SKTexture texture, [NullAllowed] SKTexture normalMap); + // + // iOS 8 + // - [MacCatalyst (13, 1)] - [Static, Export ("spriteNodeWithImageNamed:normalMapped:")] - SKSpriteNode Create (string imageName, bool generateNormalMap); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("normalTexture", ArgumentSemantic.Retain)] - SKTexture NormalTexture { get; set; } + [MacCatalyst (13, 1)] + [Static, Export ("spriteNodeWithTexture:normalMap:")] + SKSpriteNode Create ([NullAllowed] SKTexture texture, [NullAllowed] SKTexture normalMap); - [MacCatalyst (13, 1)] - [Export ("lightingBitMask")] - uint LightingBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Static, Export ("spriteNodeWithImageNamed:normalMapped:")] + SKSpriteNode Create (string imageName, bool generateNormalMap); - [MacCatalyst (13, 1)] - [Export ("shadowCastBitMask")] - uint ShadowCastBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("normalTexture", ArgumentSemantic.Retain)] + SKTexture NormalTexture { get; set; } - [MacCatalyst (13, 1)] - [Export ("shadowedBitMask")] - uint ShadowedBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("lightingBitMask")] + uint LightingBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("shader", ArgumentSemantic.Retain), NullAllowed] - SKShader Shader { get; set; } + [MacCatalyst (13, 1)] + [Export ("shadowCastBitMask")] + uint ShadowCastBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("scaleToSize:")] - void ScaleTo (CGSize size); + [MacCatalyst (13, 1)] + [Export ("shadowedBitMask")] + uint ShadowedBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [MacCatalyst (13, 1)] + [Export ("shader", ArgumentSemantic.Retain), NullAllowed] + SKShader Shader { get; set; } - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [MacCatalyst (13, 1)] + [Export ("scaleToSize:")] + void ScaleTo (CGSize size); - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); - } + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - /// An object that can control the properties of particles emitted by a . - /// - /// The total time of the sequence is normalized from 0.0 to 1.0. - /// - /// - /// - /// - /// - /// Apple documentation for SKKeyframeSequence [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - partial interface SKKeyframeSequence : NSSecureCoding, NSCopying { + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [DesignatedInitializer] - [Export ("initWithKeyframeValues:times:")] - [Internal] - NativeHandle Constructor ([NullAllowed] NSObject [] values, [NullAllowed] NSArray times); + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); +} - [Export ("initWithCapacity:")] - NativeHandle Constructor (nuint numItems); +/// An object that can control the properties of particles emitted by a . +/// +/// The total time of the sequence is normalized from 0.0 to 1.0. +/// +/// +/// +/// +/// +/// Apple documentation for SKKeyframeSequence +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +partial interface SKKeyframeSequence : NSSecureCoding, NSCopying { + + [DesignatedInitializer] + [Export ("initWithKeyframeValues:times:")] + [Internal] + NativeHandle Constructor ([NullAllowed] NSObject [] values, [NullAllowed] NSArray times); - [Export ("count")] - nuint Count { get; } + [Export ("initWithCapacity:")] + NativeHandle Constructor (nuint numItems); - [Export ("addKeyframeValue:time:")] - void AddKeyframeValue (NSObject value, nfloat time); + [Export ("count")] + nuint Count { get; } - [Export ("removeLastKeyframe")] - void RemoveLastKeyframe (); + [Export ("addKeyframeValue:time:")] + void AddKeyframeValue (NSObject value, nfloat time); - [Export ("removeKeyframeAtIndex:")] - void RemoveKeyframe (nuint index); + [Export ("removeLastKeyframe")] + void RemoveLastKeyframe (); - [Export ("setKeyframeValue:forIndex:")] - void SetKeyframeValue (NSObject value, nuint index); + [Export ("removeKeyframeAtIndex:")] + void RemoveKeyframe (nuint index); - [Export ("setKeyframeTime:forIndex:")] - void SetKeyframeTime (nfloat time, nuint index); + [Export ("setKeyframeValue:forIndex:")] + void SetKeyframeValue (NSObject value, nuint index); - [Export ("setKeyframeValue:time:forIndex:")] - void SetKeyframeValue (NSObject value, nfloat time, nuint index); + [Export ("setKeyframeTime:forIndex:")] + void SetKeyframeTime (nfloat time, nuint index); - [Export ("getKeyframeValueForIndex:")] - NSObject GetKeyframeValue (nuint index); + [Export ("setKeyframeValue:time:forIndex:")] + void SetKeyframeValue (NSObject value, nfloat time, nuint index); - [Export ("getKeyframeTimeForIndex:")] - nfloat GetKeyframeTime (nuint index); + [Export ("getKeyframeValueForIndex:")] + NSObject GetKeyframeValue (nuint index); - [Export ("sampleAtTime:")] - [return: NullAllowed] - NSObject SampleAtTime (nfloat time); + [Export ("getKeyframeTimeForIndex:")] + nfloat GetKeyframeTime (nuint index); - [Export ("interpolationMode")] - SKInterpolationMode InterpolationMode { get; set; } + [Export ("sampleAtTime:")] + [return: NullAllowed] + NSObject SampleAtTime (nfloat time); - [Export ("repeatMode")] - SKRepeatMode RepeatMode { get; set; } - } + [Export ("interpolationMode")] + SKInterpolationMode InterpolationMode { get; set; } - /// A that produces colored and textured particles. - /// - /// Emitted particles are not directly accessible to the application developer; their behavior can be controlled either via the creation parameters configurable in or by a . - /// - /// Apple documentation for SKEmitterNode - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - partial interface SKEmitterNode { + [Export ("repeatMode")] + SKRepeatMode RepeatMode { get; set; } +} - [Export ("advanceSimulationTime:")] - void AdvanceSimulationTime (double sec); +/// A that produces colored and textured particles. +/// +/// Emitted particles are not directly accessible to the application developer; their behavior can be controlled either via the creation parameters configurable in or by a . +/// +/// Apple documentation for SKEmitterNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +partial interface SKEmitterNode { - [Export ("resetSimulation")] - void ResetSimulation (); + [Export ("advanceSimulationTime:")] + void AdvanceSimulationTime (double sec); - [NullAllowed] // by default this property is null - [Export ("particleTexture", ArgumentSemantic.Retain)] - SKTexture ParticleTexture { get; set; } + [Export ("resetSimulation")] + void ResetSimulation (); - [Export ("particleZPosition")] - nfloat ParticleZPosition { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleTexture", ArgumentSemantic.Retain)] + SKTexture ParticleTexture { get; set; } - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 8, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("particleZPositionRange")] - nfloat ParticleZPositionRange { get; set; } + [Export ("particleZPosition")] + nfloat ParticleZPosition { get; set; } - [Export ("particleBlendMode")] - SKBlendMode ParticleBlendMode { get; set; } + [Deprecated (PlatformName.iOS, 8, 0)] + [Deprecated (PlatformName.TvOS, 8, 0)] + [Deprecated (PlatformName.MacOSX, 10, 10)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("particleZPositionRange")] + nfloat ParticleZPositionRange { get; set; } - [Export ("particleColor", ArgumentSemantic.Retain)] - UIColor ParticleColor { get; set; } + [Export ("particleBlendMode")] + SKBlendMode ParticleBlendMode { get; set; } - [Export ("particleColorRedRange")] - nfloat ParticleColorRedRange { get; set; } + [Export ("particleColor", ArgumentSemantic.Retain)] + UIColor ParticleColor { get; set; } - [Export ("particleColorGreenRange")] - nfloat ParticleColorGreenRange { get; set; } + [Export ("particleColorRedRange")] + nfloat ParticleColorRedRange { get; set; } - [Export ("particleColorBlueRange")] - nfloat ParticleColorBlueRange { get; set; } + [Export ("particleColorGreenRange")] + nfloat ParticleColorGreenRange { get; set; } - [Export ("particleColorAlphaRange")] - nfloat ParticleColorAlphaRange { get; set; } + [Export ("particleColorBlueRange")] + nfloat ParticleColorBlueRange { get; set; } - [Export ("particleColorRedSpeed")] - nfloat ParticleColorRedSpeed { get; set; } + [Export ("particleColorAlphaRange")] + nfloat ParticleColorAlphaRange { get; set; } - [Export ("particleColorGreenSpeed")] - nfloat ParticleColorGreenSpeed { get; set; } + [Export ("particleColorRedSpeed")] + nfloat ParticleColorRedSpeed { get; set; } - [Export ("particleColorBlueSpeed")] - nfloat ParticleColorBlueSpeed { get; set; } + [Export ("particleColorGreenSpeed")] + nfloat ParticleColorGreenSpeed { get; set; } - [Export ("particleColorAlphaSpeed")] - nfloat ParticleColorAlphaSpeed { get; set; } + [Export ("particleColorBlueSpeed")] + nfloat ParticleColorBlueSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleColorSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleColorSequence { get; set; } + [Export ("particleColorAlphaSpeed")] + nfloat ParticleColorAlphaSpeed { get; set; } - [Export ("particleColorBlendFactor")] - nfloat ParticleColorBlendFactor { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleColorSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleColorSequence { get; set; } - [Export ("particleColorBlendFactorRange")] - nfloat ParticleColorBlendFactorRange { get; set; } + [Export ("particleColorBlendFactor")] + nfloat ParticleColorBlendFactor { get; set; } - [Export ("particleColorBlendFactorSpeed")] - nfloat ParticleColorBlendFactorSpeed { get; set; } + [Export ("particleColorBlendFactorRange")] + nfloat ParticleColorBlendFactorRange { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleColorBlendFactorSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleColorBlendFactorSequence { get; set; } + [Export ("particleColorBlendFactorSpeed")] + nfloat ParticleColorBlendFactorSpeed { get; set; } - [Export ("particlePosition")] - CGPoint ParticlePosition { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleColorBlendFactorSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleColorBlendFactorSequence { get; set; } - [Export ("particlePositionRange")] - CGVector ParticlePositionRange { get; set; } + [Export ("particlePosition")] + CGPoint ParticlePosition { get; set; } - [Export ("particleSpeed")] - nfloat ParticleSpeed { get; set; } + [Export ("particlePositionRange")] + CGVector ParticlePositionRange { get; set; } - [Export ("particleSpeedRange")] - nfloat ParticleSpeedRange { get; set; } + [Export ("particleSpeed")] + nfloat ParticleSpeed { get; set; } - [Export ("emissionAngle")] - nfloat EmissionAngle { get; set; } + [Export ("particleSpeedRange")] + nfloat ParticleSpeedRange { get; set; } - [Export ("emissionAngleRange")] - nfloat EmissionAngleRange { get; set; } + [Export ("emissionAngle")] + nfloat EmissionAngle { get; set; } - [Export ("xAcceleration")] - nfloat XAcceleration { get; set; } + [Export ("emissionAngleRange")] + nfloat EmissionAngleRange { get; set; } - [Export ("yAcceleration")] - nfloat YAcceleration { get; set; } + [Export ("xAcceleration")] + nfloat XAcceleration { get; set; } - [Export ("particleBirthRate")] - nfloat ParticleBirthRate { get; set; } + [Export ("yAcceleration")] + nfloat YAcceleration { get; set; } - [Export ("numParticlesToEmit")] - nuint NumParticlesToEmit { get; set; } + [Export ("particleBirthRate")] + nfloat ParticleBirthRate { get; set; } - [Export ("particleLifetime")] - nfloat ParticleLifetime { get; set; } + [Export ("numParticlesToEmit")] + nuint NumParticlesToEmit { get; set; } - [Export ("particleLifetimeRange")] - nfloat ParticleLifetimeRange { get; set; } + [Export ("particleLifetime")] + nfloat ParticleLifetime { get; set; } - [Export ("particleRotation")] - nfloat ParticleRotation { get; set; } + [Export ("particleLifetimeRange")] + nfloat ParticleLifetimeRange { get; set; } - [Export ("particleRotationRange")] - nfloat ParticleRotationRange { get; set; } + [Export ("particleRotation")] + nfloat ParticleRotation { get; set; } - [Export ("particleRotationSpeed")] - nfloat ParticleRotationSpeed { get; set; } + [Export ("particleRotationRange")] + nfloat ParticleRotationRange { get; set; } - [Export ("particleSize")] - CGSize ParticleSize { get; set; } + [Export ("particleRotationSpeed")] + nfloat ParticleRotationSpeed { get; set; } - [Export ("particleScale")] - nfloat ParticleScale { get; set; } + [Export ("particleSize")] + CGSize ParticleSize { get; set; } - [Export ("particleScaleRange")] - nfloat ParticleScaleRange { get; set; } + [Export ("particleScale")] + nfloat ParticleScale { get; set; } - [Export ("particleScaleSpeed")] - nfloat ParticleScaleSpeed { get; set; } + [Export ("particleScaleRange")] + nfloat ParticleScaleRange { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleScaleSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleScaleSequence { get; set; } + [Export ("particleScaleSpeed")] + nfloat ParticleScaleSpeed { get; set; } - [Export ("particleAlpha")] - nfloat ParticleAlpha { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleScaleSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleScaleSequence { get; set; } - [Export ("particleAlphaRange")] - nfloat ParticleAlphaRange { get; set; } + [Export ("particleAlpha")] + nfloat ParticleAlpha { get; set; } - [Export ("particleAlphaSpeed")] - nfloat ParticleAlphaSpeed { get; set; } + [Export ("particleAlphaRange")] + nfloat ParticleAlphaRange { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleAlphaSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleAlphaSequence { get; set; } + [Export ("particleAlphaSpeed")] + nfloat ParticleAlphaSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleAction", ArgumentSemantic.Copy)] - SKAction ParticleAction { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleAlphaSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleAlphaSequence { get; set; } - [NullAllowed] // by default this property is null - [Export ("targetNode", ArgumentSemantic.Weak)] - SKNode TargetNode { get; set; } - - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Export ("fieldBitMask")] - uint FieldBitMask { get; set; } /* uint32_t */ - - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 8, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("particleZPositionSpeed")] - nfloat ParticleZPositionSpeed { get; set; } - - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleAction", ArgumentSemantic.Copy)] + SKAction ParticleAction { get; set; } - [MacCatalyst (13, 1)] - [Export ("particleRenderOrder", ArgumentSemantic.Assign)] - SKParticleRenderOrder ParticleRenderOrder { get; set; } + [NullAllowed] // by default this property is null + [Export ("targetNode", ArgumentSemantic.Weak)] + SKNode TargetNode { get; set; } - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("fieldBitMask")] + uint FieldBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [Deprecated (PlatformName.iOS, 8, 0)] + [Deprecated (PlatformName.TvOS, 8, 0)] + [Deprecated (PlatformName.MacOSX, 10, 10)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("particleZPositionSpeed")] + nfloat ParticleZPositionSpeed { get; set; } - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); - } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - /// A defined by a Core Graphics . - /// - /// Apple documentation for SKShapeNode [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - partial interface SKShapeNode { + [Export ("particleRenderOrder", ArgumentSemantic.Assign)] + SKParticleRenderOrder ParticleRenderOrder { get; set; } - [NullAllowed] - [Export ("path")] - CGPath Path { get; set; } + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [Export ("strokeColor", ArgumentSemantic.Retain)] - UIColor StrokeColor { get; set; } + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [Export ("fillColor", ArgumentSemantic.Retain)] - UIColor FillColor { get; set; } + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); +} - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } +/// A defined by a Core Graphics . +/// +/// Apple documentation for SKShapeNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +partial interface SKShapeNode { - [Export ("antialiased")] - bool Antialiased { [Bind ("isAntialiased")] get; set; } + [NullAllowed] + [Export ("path")] + CGPath Path { get; set; } - [Export ("lineWidth")] - nfloat LineWidth { get; set; } + [Export ("strokeColor", ArgumentSemantic.Retain)] + UIColor StrokeColor { get; set; } - [Export ("glowWidth")] - nfloat GlowWidth { get; set; } + [Export ("fillColor", ArgumentSemantic.Retain)] + UIColor FillColor { get; set; } - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("fillTexture", ArgumentSemantic.Retain)] - SKTexture FillTexture { get; set; } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("fillShader", ArgumentSemantic.Retain)] - SKShader FillShader { get; set; } + [Export ("antialiased")] + bool Antialiased { [Bind ("isAntialiased")] get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("strokeTexture", ArgumentSemantic.Retain)] - SKTexture StrokeTexture { get; set; } + [Export ("lineWidth")] + nfloat LineWidth { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("strokeShader", ArgumentSemantic.Retain)] - SKShader StrokeShader { get; set; } - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPath:")] - SKShapeNode FromPath (CGPath path); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPath:centered:")] - SKShapeNode FromPath (CGPath path, bool centered); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRect:")] - SKShapeNode FromRect (CGRect rect); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRectOfSize:")] - SKShapeNode FromRect (CGSize size); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRect:cornerRadius:")] - SKShapeNode FromRect (CGRect rect, nfloat cornerRadius); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRectOfSize:cornerRadius:")] - SKShapeNode FromRect (CGSize size, nfloat cornerRadius); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithCircleOfRadius:")] - SKShapeNode FromCircle (nfloat radius); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithEllipseInRect:")] - SKShapeNode FromEllipse (CGRect rect); - - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithEllipseOfSize:")] - SKShapeNode FromEllipse (CGSize size); - - // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 - [Internal] - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPoints:count:")] - SKShapeNode FromPoints (ref CGPoint points, nuint numPoints); - - // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 - [Internal] - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithSplinePoints:count:")] - SKShapeNode FromSplinePoints (ref CGPoint points, nuint numPoints); - - [MacCatalyst (13, 1)] - [Export ("lineCap")] - CGLineCap LineCap { get; set; } - - [MacCatalyst (13, 1)] - [Export ("lineJoin")] - CGLineJoin LineJoin { get; set; } - - [MacCatalyst (13, 1)] - [Export ("miterLimit")] - nfloat MiterLimit { get; set; } - - [MacCatalyst (13, 1)] - [Export ("lineLength")] - nfloat LineLength { get; } - - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } - - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); - - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); - } + [Export ("glowWidth")] + nfloat GlowWidth { get; set; } - /// A range of motion used with inverse kinematics. - /// - /// Apple documentation for SKReachConstraints + // + // iOS 8 + // [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKReachConstraints : NSSecureCoding { - [DesignatedInitializer] - [Export ("initWithLowerAngleLimit:upperAngleLimit:")] - NativeHandle Constructor (nfloat lowerAngleLimit, nfloat upperAngleLimit); + [NullAllowed] // by default this property is null + [Export ("fillTexture", ArgumentSemantic.Retain)] + SKTexture FillTexture { get; set; } - [Export ("lowerAngleLimit", ArgumentSemantic.UnsafeUnretained)] - nfloat LowerAngleLimit { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("fillShader", ArgumentSemantic.Retain)] + SKShader FillShader { get; set; } - [Export ("upperAngleLimit", ArgumentSemantic.UnsafeUnretained)] - nfloat UpperAngleLimit { get; set; } - } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("strokeTexture", ArgumentSemantic.Retain)] + SKTexture StrokeTexture { get; set; } - /// A path-defined area. Typically used for hit-testing and physics-field extents. - /// - /// Apple documentation for SKRegion [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKRegion : NSCopying, NSSecureCoding { - [Export ("initWithRadius:")] - NativeHandle Constructor (float /* float, not CGFloat */ radius); + [NullAllowed] // by default this property is null + [Export ("strokeShader", ArgumentSemantic.Retain)] + SKShader StrokeShader { get; set; } - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPath:")] + SKShapeNode FromPath (CGPath path); - [Export ("initWithPath:")] - NativeHandle Constructor (CGPath path); + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPath:centered:")] + SKShapeNode FromPath (CGPath path, bool centered); - [Export ("path")] - [NullAllowed] - CGPath Path { get; } + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRect:")] + SKShapeNode FromRect (CGRect rect); - [Static, Export ("infiniteRegion")] - SKRegion InfiniteRegion { get; } + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRectOfSize:")] + SKShapeNode FromRect (CGSize size); - [Export ("inverseRegion")] - SKRegion InverseRegion (); + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRect:cornerRadius:")] + SKShapeNode FromRect (CGRect rect, nfloat cornerRadius); - [Export ("regionByUnionWithRegion:")] - SKRegion CreateUnion (SKRegion region); + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRectOfSize:cornerRadius:")] + SKShapeNode FromRect (CGSize size, nfloat cornerRadius); - [Export ("regionByDifferenceFromRegion:")] - SKRegion CreateDifference (SKRegion region); + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithCircleOfRadius:")] + SKShapeNode FromCircle (nfloat radius); - [Export ("regionByIntersectionWithRegion:")] - SKRegion CreateIntersection (SKRegion region); + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithEllipseInRect:")] + SKShapeNode FromEllipse (CGRect rect); - [Export ("containsPoint:")] - bool ContainsPoint (CGPoint point); - } + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithEllipseOfSize:")] + SKShapeNode FromEllipse (CGSize size); - /// A that displays a string. - /// - /// Apple documentation for SKLabelNode + // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 + [Internal] [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - partial interface SKLabelNode { + [Static, Export ("shapeNodeWithPoints:count:")] + SKShapeNode FromPoints (ref CGPoint points, nuint numPoints); - [Static, Export ("labelNodeWithFontNamed:")] - SKLabelNode FromFont ([NullAllowed] string fontName); + // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 + [Internal] + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithSplinePoints:count:")] + SKShapeNode FromSplinePoints (ref CGPoint points, nuint numPoints); - [Export ("initWithFontNamed:")] - NativeHandle Constructor ([NullAllowed] string fontName); + [MacCatalyst (13, 1)] + [Export ("lineCap")] + CGLineCap LineCap { get; set; } - [MacCatalyst (13, 1)] - [Static, Export ("labelNodeWithText:")] - SKLabelNode FromText ([NullAllowed] string text); + [MacCatalyst (13, 1)] + [Export ("lineJoin")] + CGLineJoin LineJoin { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("labelNodeWithAttributedText:")] - SKLabelNode FromText ([NullAllowed] NSAttributedString attributedText); + [MacCatalyst (13, 1)] + [Export ("miterLimit")] + nfloat MiterLimit { get; set; } - [Export ("verticalAlignmentMode")] - SKLabelVerticalAlignmentMode VerticalAlignmentMode { get; set; } + [MacCatalyst (13, 1)] + [Export ("lineLength")] + nfloat LineLength { get; } - [Export ("horizontalAlignmentMode")] - SKLabelHorizontalAlignmentMode HorizontalAlignmentMode { get; set; } + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [MacCatalyst (13, 1)] - [Export ("numberOfLines")] - nint NumberOfLines { get; set; } + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [MacCatalyst (13, 1)] - [Export ("lineBreakMode", ArgumentSemantic.Assign)] - NSLineBreakMode LineBreakMode { get; set; } + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); +} - [MacCatalyst (13, 1)] - [Export ("preferredMaxLayoutWidth")] - nfloat PreferredMaxLayoutWidth { get; set; } +/// A range of motion used with inverse kinematics. +/// +/// Apple documentation for SKReachConstraints +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKReachConstraints : NSSecureCoding { + [DesignatedInitializer] + [Export ("initWithLowerAngleLimit:upperAngleLimit:")] + NativeHandle Constructor (nfloat lowerAngleLimit, nfloat upperAngleLimit); + + [Export ("lowerAngleLimit", ArgumentSemantic.UnsafeUnretained)] + nfloat LowerAngleLimit { get; set; } + + [Export ("upperAngleLimit", ArgumentSemantic.UnsafeUnretained)] + nfloat UpperAngleLimit { get; set; } +} - [Export ("fontName", ArgumentSemantic.Copy)] - [NullAllowed] - string FontName { get; set; } +/// A path-defined area. Typically used for hit-testing and physics-field extents. +/// +/// Apple documentation for SKRegion +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKRegion : NSCopying, NSSecureCoding { + [Export ("initWithRadius:")] + NativeHandle Constructor (float /* float, not CGFloat */ radius); - [Export ("text", ArgumentSemantic.Copy)] - [NullAllowed] // nullable in Xcode7 headers and caught by introspection tests - string Text { get; set; } + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("attributedText", ArgumentSemantic.Copy)] - NSAttributedString AttributedText { get; set; } + [Export ("initWithPath:")] + NativeHandle Constructor (CGPath path); - [Export ("fontSize")] - nfloat FontSize { get; set; } + [Export ("path")] + [NullAllowed] + CGPath Path { get; } - [Export ("fontColor", ArgumentSemantic.Retain)] - [NullAllowed] - UIColor FontColor { get; set; } + [Static, Export ("infiniteRegion")] + SKRegion InfiniteRegion { get; } - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + [Export ("inverseRegion")] + SKRegion InverseRegion (); - [NullAllowed] // by default this property is null - [Export ("color", ArgumentSemantic.Retain)] - UIColor Color { get; set; } + [Export ("regionByUnionWithRegion:")] + SKRegion CreateUnion (SKRegion region); - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } - } + [Export ("regionByDifferenceFromRegion:")] + SKRegion CreateDifference (SKRegion region); - /// A node that creates a lighting effect within a scene. - /// - /// Apple documentation for SKLightNode - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - interface SKLightNode { - [Export ("enabled")] - bool Enabled { [Bind ("isEnabled")] get; set; } + [Export ("regionByIntersectionWithRegion:")] + SKRegion CreateIntersection (SKRegion region); - [Export ("lightColor")] - UIColor LightColor { get; set; } + [Export ("containsPoint:")] + bool ContainsPoint (CGPoint point); +} - [Export ("ambientColor")] - UIColor AmbientColor { get; set; } +/// A that displays a string. +/// +/// Apple documentation for SKLabelNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +partial interface SKLabelNode { - [Export ("shadowColor")] - UIColor ShadowColor { get; set; } + [Static, Export ("labelNodeWithFontNamed:")] + SKLabelNode FromFont ([NullAllowed] string fontName); - [Export ("falloff")] - nfloat Falloff { get; set; } + [Export ("initWithFontNamed:")] + NativeHandle Constructor ([NullAllowed] string fontName); - [Export ("categoryBitMask")] - uint CategoryBitMask { get; set; } /* uint32_t */ - } + [MacCatalyst (13, 1)] + [Static, Export ("labelNodeWithText:")] + SKLabelNode FromText ([NullAllowed] string text); - /// A that displays video. - /// - /// Apple documentation for SKVideoNode [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - partial interface SKVideoNode { - [Static, Export ("videoNodeWithAVPlayer:")] - SKVideoNode FromPlayer (AVPlayer player); + [Static] + [Export ("labelNodeWithAttributedText:")] + SKLabelNode FromText ([NullAllowed] NSAttributedString attributedText); - [Static, Export ("videoNodeWithVideoFileNamed:"), Internal] - SKVideoNode VideoNodeWithVideoFileNamed (string videoFile); + [Export ("verticalAlignmentMode")] + SKLabelVerticalAlignmentMode VerticalAlignmentMode { get; set; } - [Static, Export ("videoNodeWithFileNamed:"), Internal] - SKVideoNode VideoNodeWithFileNamed (string videoFile); + [Export ("horizontalAlignmentMode")] + SKLabelHorizontalAlignmentMode HorizontalAlignmentMode { get; set; } - [Static, Export ("videoNodeWithVideoURL:"), Internal] - SKVideoNode VideoNodeWithVideoURL (NSUrl videoURL); + [MacCatalyst (13, 1)] + [Export ("numberOfLines")] + nint NumberOfLines { get; set; } - [Static, Export ("videoNodeWithURL:"), Internal] - SKVideoNode VideoNodeWithURL (NSUrl videoURL); + [MacCatalyst (13, 1)] + [Export ("lineBreakMode", ArgumentSemantic.Assign)] + NSLineBreakMode LineBreakMode { get; set; } - [DesignatedInitializer] - [Export ("initWithAVPlayer:")] - NativeHandle Constructor (AVPlayer player); + [MacCatalyst (13, 1)] + [Export ("preferredMaxLayoutWidth")] + nfloat PreferredMaxLayoutWidth { get; set; } - [Export ("initWithVideoFileNamed:"), Internal] - IntPtr InitWithVideoFileNamed (string videoFile); + [Export ("fontName", ArgumentSemantic.Copy)] + [NullAllowed] + string FontName { get; set; } - [Export ("initWithFileNamed:"), Internal] - IntPtr InitWithFileNamed (string videoFile); + [Export ("text", ArgumentSemantic.Copy)] + [NullAllowed] // nullable in Xcode7 headers and caught by introspection tests + string Text { get; set; } - [Export ("initWithVideoURL:"), Internal] - IntPtr InitWithVideoURL (NSUrl url); + [MacCatalyst (13, 1)] + [NullAllowed, Export ("attributedText", ArgumentSemantic.Copy)] + NSAttributedString AttributedText { get; set; } - [Export ("initWithURL:"), Internal] - IntPtr InitWithURL (NSUrl url); + [Export ("fontSize")] + nfloat FontSize { get; set; } - [Export ("play")] - void Play (); + [Export ("fontColor", ArgumentSemantic.Retain)] + [NullAllowed] + UIColor FontColor { get; set; } - [Export ("pause")] - void Pause (); + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("size")] - CGSize Size { get; set; } + [NullAllowed] // by default this property is null + [Export ("color", ArgumentSemantic.Retain)] + UIColor Color { get; set; } - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } - } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } +} - /// Mathematical constraint on a node's position or orientation. - /// - /// Apple documentation for SKConstraint - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKConstraint : NSSecureCoding, NSCopying { - [Export ("enabled")] - bool Enabled { get; set; } +/// A node that creates a lighting effect within a scene. +/// +/// Apple documentation for SKLightNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +interface SKLightNode { + [Export ("enabled")] + bool Enabled { [Bind ("isEnabled")] get; set; } - [NullAllowed] // by default this property is null - [Export ("referenceNode", ArgumentSemantic.Retain)] - SKNode ReferenceNode { get; set; } + [Export ("lightColor")] + UIColor LightColor { get; set; } - [Static, Export ("positionX:")] - SKConstraint CreateXRestriction (SKRange range); + [Export ("ambientColor")] + UIColor AmbientColor { get; set; } - [Static, Export ("positionY:")] - SKConstraint CreateYRestriction (SKRange range); + [Export ("shadowColor")] + UIColor ShadowColor { get; set; } - [Static, Export ("positionX:Y:")] - SKConstraint CreateRestriction (SKRange xRange, SKRange yRange); + [Export ("falloff")] + nfloat Falloff { get; set; } - [Static, Export ("distance:toNode:")] - SKConstraint CreateDistance (SKRange range, SKNode node); + [Export ("categoryBitMask")] + uint CategoryBitMask { get; set; } /* uint32_t */ +} - [Static, Export ("distance:toPoint:")] - SKConstraint CreateDistance (SKRange range, CGPoint point); +/// A that displays video. +/// +/// Apple documentation for SKVideoNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +partial interface SKVideoNode { + [Static, Export ("videoNodeWithAVPlayer:")] + SKVideoNode FromPlayer (AVPlayer player); - [Static, Export ("distance:toPoint:inNode:")] - SKConstraint CreateDistance (SKRange range, CGPoint point, SKNode node); + [Static, Export ("videoNodeWithVideoFileNamed:"), Internal] + SKVideoNode VideoNodeWithVideoFileNamed (string videoFile); - [Static, Export ("zRotation:")] - SKConstraint CreateZRotation (SKRange zRange); + [Static, Export ("videoNodeWithFileNamed:"), Internal] + SKVideoNode VideoNodeWithFileNamed (string videoFile); - [Static, Export ("orientToNode:offset:")] - SKConstraint CreateOrientToNode (SKNode node, SKRange radians); + [Static, Export ("videoNodeWithVideoURL:"), Internal] + SKVideoNode VideoNodeWithVideoURL (NSUrl videoURL); - [Static, Export ("orientToPoint:offset:")] - SKConstraint CreateOrientToPoint (CGPoint point, SKRange radians); + [Static, Export ("videoNodeWithURL:"), Internal] + SKVideoNode VideoNodeWithURL (NSUrl videoURL); - [Static, Export ("orientToPoint:inNode:offset:")] - SKConstraint CreateOrientToPoint (CGPoint point, SKNode node, SKRange radians); - } + [DesignatedInitializer] + [Export ("initWithAVPlayer:")] + NativeHandle Constructor (AVPlayer player); - /// A node that masks its children's pixels. - /// - /// An masks pixels outside of the area defined by its node. Pixels that fall outside of that area are not passed up towards the root of the . - /// - /// - /// Apple documentation for SKCropNode - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - partial interface SKCropNode { + [Export ("initWithVideoFileNamed:"), Internal] + IntPtr InitWithVideoFileNamed (string videoFile); - [NullAllowed] // by default this property is null - [Export ("maskNode", ArgumentSemantic.Retain)] - SKNode MaskNode { get; set; } - } + [Export ("initWithFileNamed:"), Internal] + IntPtr InitWithFileNamed (string videoFile); - /// A that displays a . - /// - /// Application developers should note the availability of debugging properties, such as . - /// - /// Apple documentation for SKView - [MacCatalyst (13, 1)] - [BaseType (typeof (UIView))] - [DisableDefaultCtor] -#if MONOMAC - partial interface SKView : NSSecureCoding { -#else - partial interface SKView { -#endif - [Export ("initWithFrame:")] - NativeHandle Constructor (CGRect frame); + [Export ("initWithVideoURL:"), Internal] + IntPtr InitWithVideoURL (NSUrl url); - [Export ("paused")] - bool Paused { [Bind ("isPaused")] get; set; } + [Export ("initWithURL:"), Internal] + IntPtr InitWithURL (NSUrl url); - [Export ("showsFPS")] - bool ShowsFPS { get; set; } + [Export ("play")] + void Play (); - [Export ("showsDrawCount")] - bool ShowsDrawCount { get; set; } + [Export ("pause")] + void Pause (); - [Export ("showsNodeCount")] - bool ShowsNodeCount { get; set; } + [Export ("size")] + CGSize Size { get; set; } - [MacCatalyst (13, 1)] - [Export ("showsPhysics")] - bool ShowsPhysics { get; set; } + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } +} - [Export ("asynchronous")] - bool Asynchronous { [Bind ("isAsynchronous")] get; set; } +/// Mathematical constraint on a node's position or orientation. +/// +/// Apple documentation for SKConstraint +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKConstraint : NSSecureCoding, NSCopying { + [Export ("enabled")] + bool Enabled { get; set; } - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("frameInterval")] - nint FrameInterval { get; set; } + [NullAllowed] // by default this property is null + [Export ("referenceNode", ArgumentSemantic.Retain)] + SKNode ReferenceNode { get; set; } - [Export ("presentScene:")] - void PresentScene ([NullAllowed] SKScene scene); + [Static, Export ("positionX:")] + SKConstraint CreateXRestriction (SKRange range); - [Export ("presentScene:transition:")] - void PresentScene (SKScene scene, SKTransition transition); + [Static, Export ("positionY:")] + SKConstraint CreateYRestriction (SKRange range); - [Export ("scene")] - [NullAllowed] - SKScene Scene { get; } + [Static, Export ("positionX:Y:")] + SKConstraint CreateRestriction (SKRange xRange, SKRange yRange); - [Export ("textureFromNode:")] - [return: NullAllowed] - SKTexture TextureFromNode (SKNode node); + [Static, Export ("distance:toNode:")] + SKConstraint CreateDistance (SKRange range, SKNode node); - [Export ("convertPoint:toScene:")] - CGPoint ConvertPointToScene (CGPoint point, SKScene scene); + [Static, Export ("distance:toPoint:")] + SKConstraint CreateDistance (SKRange range, CGPoint point); - [Export ("convertPoint:fromScene:")] - CGPoint ConvertPointFromScene (CGPoint point, SKScene scene); + [Static, Export ("distance:toPoint:inNode:")] + SKConstraint CreateDistance (SKRange range, CGPoint point, SKNode node); - [Export ("ignoresSiblingOrder")] - bool IgnoresSiblingOrder { get; set; } + [Static, Export ("zRotation:")] + SKConstraint CreateZRotation (SKRange zRange); - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Export ("allowsTransparency")] - bool AllowsTransparency { get; set; } + [Static, Export ("orientToNode:offset:")] + SKConstraint CreateOrientToNode (SKNode node, SKRange radians); - [MacCatalyst (13, 1)] - [Export ("shouldCullNonVisibleNodes")] - bool ShouldCullNonVisibleNodes { get; set; } + [Static, Export ("orientToPoint:offset:")] + SKConstraint CreateOrientToPoint (CGPoint point, SKRange radians); - [MacCatalyst (13, 1)] - [Export ("showsFields")] - bool ShowsFields { get; set; } + [Static, Export ("orientToPoint:inNode:offset:")] + SKConstraint CreateOrientToPoint (CGPoint point, SKNode node, SKRange radians); +} - [MacCatalyst (13, 1)] - [Export ("showsQuadCount")] - bool ShowsQuadCount { get; set; } +/// A node that masks its children's pixels. +/// +/// An masks pixels outside of the area defined by its node. Pixels that fall outside of that area are not passed up towards the root of the . +/// +/// +/// Apple documentation for SKCropNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +partial interface SKCropNode { + + [NullAllowed] // by default this property is null + [Export ("maskNode", ArgumentSemantic.Retain)] + SKNode MaskNode { get; set; } +} - [MacCatalyst (13, 1)] - [Export ("textureFromNode:crop:")] - [return: NullAllowed] - SKTexture TextureFromNode (SKNode node, CGRect crop); +/// A that displays a . +/// +/// Application developers should note the availability of debugging properties, such as . +/// +/// Apple documentation for SKView +[MacCatalyst (13, 1)] +[BaseType (typeof (UIView))] +[DisableDefaultCtor] +#if MONOMAC + partial interface SKView : NSSecureCoding { +#else +partial interface SKView { +#endif + [Export ("initWithFrame:")] + NativeHandle Constructor (CGRect frame); - [MacCatalyst (13, 1)] - [Export ("preferredFramesPerSecond")] - nint PreferredFramesPerSecond { get; set; } + [Export ("paused")] + bool Paused { [Bind ("isPaused")] get; set; } - [MacCatalyst (13, 1)] - [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] - ISKViewDelegate Delegate { get; set; } + [Export ("showsFPS")] + bool ShowsFPS { get; set; } - [iOS (14, 0)] - [TV (14, 0)] - [MacCatalyst (14, 0)] - [Export ("disableDepthStencilBuffer")] - bool DisableDepthStencilBuffer { get; set; } - } + [Export ("showsDrawCount")] + bool ShowsDrawCount { get; set; } - /// Interface representing the required methods (if any) of the protocol . - /// - /// This interface contains the required methods (if any) from the protocol defined by . - /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. - /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. - /// - interface ISKViewDelegate { } + [Export ("showsNodeCount")] + bool ShowsNodeCount { get; set; } - /// Delegate object for objects, allowing the developer to control the frame rate. - /// - /// Apple documentation for SKViewDelegate [MacCatalyst (13, 1)] - [Protocol, Model] - [BaseType (typeof (NSObject))] - interface SKViewDelegate { - [Export ("view:shouldRenderAtTime:")] - bool ShouldRender (SKView view, double time); - } + [Export ("showsPhysics")] + bool ShowsPhysics { get; set; } - /// Transitions that can be used between s. Used with the method. - /// - /// Apple documentation for SKTransition - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] - partial interface SKTransition : NSCopying { + [Export ("asynchronous")] + bool Asynchronous { [Bind ("isAsynchronous")] get; set; } - [Static, Export ("crossFadeWithDuration:")] - SKTransition CrossFadeWithDuration (double sec); + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("frameInterval")] + nint FrameInterval { get; set; } - [Static, Export ("fadeWithDuration:")] - SKTransition FadeWithDuration (double sec); + [Export ("presentScene:")] + void PresentScene ([NullAllowed] SKScene scene); - [Static, Export ("fadeWithColor:duration:")] - SKTransition FadeWithColor (UIColor color, double sec); + [Export ("presentScene:transition:")] + void PresentScene (SKScene scene, SKTransition transition); - [Static, Export ("flipHorizontalWithDuration:")] - SKTransition FlipHorizontalWithDuration (double sec); + [Export ("scene")] + [NullAllowed] + SKScene Scene { get; } - [Static, Export ("flipVerticalWithDuration:")] - SKTransition FlipVerticalWithDuration (double sec); + [Export ("textureFromNode:")] + [return: NullAllowed] + SKTexture TextureFromNode (SKNode node); - [Static, Export ("revealWithDirection:duration:")] - SKTransition RevealWithDirection (SKTransitionDirection direction, double sec); + [Export ("convertPoint:toScene:")] + CGPoint ConvertPointToScene (CGPoint point, SKScene scene); - [Static, Export ("moveInWithDirection:duration:")] - SKTransition MoveInWithDirection (SKTransitionDirection direction, double sec); + [Export ("convertPoint:fromScene:")] + CGPoint ConvertPointFromScene (CGPoint point, SKScene scene); - [Static, Export ("pushWithDirection:duration:")] - SKTransition PushWithDirection (SKTransitionDirection direction, double sec); + [Export ("ignoresSiblingOrder")] + bool IgnoresSiblingOrder { get; set; } - [Static, Export ("doorsOpenHorizontalWithDuration:")] - SKTransition DoorsOpenHorizontalWithDuration (double sec); + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("allowsTransparency")] + bool AllowsTransparency { get; set; } - [Static, Export ("doorsOpenVerticalWithDuration:")] - SKTransition DoorsOpenVerticalWithDuration (double sec); + [MacCatalyst (13, 1)] + [Export ("shouldCullNonVisibleNodes")] + bool ShouldCullNonVisibleNodes { get; set; } - [Static, Export ("doorsCloseHorizontalWithDuration:")] - SKTransition DoorsCloseHorizontalWithDuration (double sec); + [MacCatalyst (13, 1)] + [Export ("showsFields")] + bool ShowsFields { get; set; } - [Static, Export ("doorsCloseVerticalWithDuration:")] - SKTransition DoorsCloseVerticalWithDuration (double sec); + [MacCatalyst (13, 1)] + [Export ("showsQuadCount")] + bool ShowsQuadCount { get; set; } - [Static, Export ("doorwayWithDuration:")] - SKTransition DoorwayWithDuration (double sec); + [MacCatalyst (13, 1)] + [Export ("textureFromNode:crop:")] + [return: NullAllowed] + SKTexture TextureFromNode (SKNode node, CGRect crop); - [MacCatalyst (13, 1)] - [Static, Export ("transitionWithCIFilter:duration:")] - SKTransition TransitionWithCIFilter (CIFilter filter, double sec); + [MacCatalyst (13, 1)] + [Export ("preferredFramesPerSecond")] + nint PreferredFramesPerSecond { get; set; } - [Export ("pausesIncomingScene")] - bool PausesIncomingScene { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] + ISKViewDelegate Delegate { get; set; } + + [iOS (14, 0)] + [TV (14, 0)] + [MacCatalyst (14, 0)] + [Export ("disableDepthStencilBuffer")] + bool DisableDepthStencilBuffer { get; set; } +} - [Export ("pausesOutgoingScene")] - bool PausesOutgoingScene { get; set; } - } +/// Interface representing the required methods (if any) of the protocol . +/// +/// This interface contains the required methods (if any) from the protocol defined by . +/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. +/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. +/// +interface ISKViewDelegate { } + +/// Delegate object for objects, allowing the developer to control the frame rate. +/// +/// Apple documentation for SKViewDelegate +[MacCatalyst (13, 1)] +[Protocol, Model] +[BaseType (typeof (NSObject))] +interface SKViewDelegate { + [Export ("view:shouldRenderAtTime:")] + bool ShouldRender (SKView view, double time); +} + +/// Transitions that can be used between s. Used with the method. +/// +/// Apple documentation for SKTransition +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +partial interface SKTransition : NSCopying { + + [Static, Export ("crossFadeWithDuration:")] + SKTransition CrossFadeWithDuration (double sec); + + [Static, Export ("fadeWithDuration:")] + SKTransition FadeWithDuration (double sec); + + [Static, Export ("fadeWithColor:duration:")] + SKTransition FadeWithColor (UIColor color, double sec); + + [Static, Export ("flipHorizontalWithDuration:")] + SKTransition FlipHorizontalWithDuration (double sec); + + [Static, Export ("flipVerticalWithDuration:")] + SKTransition FlipVerticalWithDuration (double sec); + + [Static, Export ("revealWithDirection:duration:")] + SKTransition RevealWithDirection (SKTransitionDirection direction, double sec); + + [Static, Export ("moveInWithDirection:duration:")] + SKTransition MoveInWithDirection (SKTransitionDirection direction, double sec); + + [Static, Export ("pushWithDirection:duration:")] + SKTransition PushWithDirection (SKTransitionDirection direction, double sec); + + [Static, Export ("doorsOpenHorizontalWithDuration:")] + SKTransition DoorsOpenHorizontalWithDuration (double sec); + + [Static, Export ("doorsOpenVerticalWithDuration:")] + SKTransition DoorsOpenVerticalWithDuration (double sec); + + [Static, Export ("doorsCloseHorizontalWithDuration:")] + SKTransition DoorsCloseHorizontalWithDuration (double sec); + + [Static, Export ("doorsCloseVerticalWithDuration:")] + SKTransition DoorsCloseVerticalWithDuration (double sec); + + [Static, Export ("doorwayWithDuration:")] + SKTransition DoorwayWithDuration (double sec); - /// An image that can be used with one or more s and particles. - /// - /// Sprite Kit attempts to be efficient with the memory associated with textures. Textures are lazy-loaded from their source files and in preparation for loading onto the graphics hardware. This lazy-loading can be overridden with the Preload* methods. - /// - /// - /// Apple documentation for SKTexture [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] - partial interface SKTexture : NSSecureCoding, NSCopying { + [Static, Export ("transitionWithCIFilter:duration:")] + SKTransition TransitionWithCIFilter (CIFilter filter, double sec); - [Static, Export ("textureWithImageNamed:")] - SKTexture FromImageNamed (string name); + [Export ("pausesIncomingScene")] + bool PausesIncomingScene { get; set; } - [Static, Export ("textureWithRect:inTexture:")] - SKTexture FromRectangle (CGRect rect, SKTexture texture); + [Export ("pausesOutgoingScene")] + bool PausesOutgoingScene { get; set; } +} - [Static, Export ("textureWithCGImage:")] - SKTexture FromImage (CGImage image); +/// An image that can be used with one or more s and particles. +/// +/// Sprite Kit attempts to be efficient with the memory associated with textures. Textures are lazy-loaded from their source files and in preparation for loading onto the graphics hardware. This lazy-loading can be overridden with the Preload* methods. +/// +/// +/// Apple documentation for SKTexture +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +partial interface SKTexture : NSSecureCoding, NSCopying { - [Static, Export ("textureWithImage:")] - SKTexture FromImage (UIImage image); + [Static, Export ("textureWithImageNamed:")] + SKTexture FromImageNamed (string name); - [Static, Export ("textureWithData:size:")] - SKTexture FromData (NSData pixelData, CGSize size); + [Static, Export ("textureWithRect:inTexture:")] + SKTexture FromRectangle (CGRect rect, SKTexture texture); - [Static, Export ("textureWithData:size:rowLength:alignment:")] - SKTexture FromData (NSData pixelData, CGSize size, uint /* unsigned int*/ rowLength, uint /* unsigned int */ alignment); + [Static, Export ("textureWithCGImage:")] + SKTexture FromImage (CGImage image); - [MacCatalyst (13, 1)] - [Export ("textureByApplyingCIFilter:")] - SKTexture TextureByApplyingCIFilter (CIFilter filter); + [Static, Export ("textureWithImage:")] + SKTexture FromImage (UIImage image); - [Export ("textureRect")] - CGRect TextureRect { get; } + [Static, Export ("textureWithData:size:")] + SKTexture FromData (NSData pixelData, CGSize size); - [Export ("size")] - CGSize Size { get; } + [Static, Export ("textureWithData:size:rowLength:alignment:")] + SKTexture FromData (NSData pixelData, CGSize size, uint /* unsigned int*/ rowLength, uint /* unsigned int */ alignment); - [Export ("filteringMode")] - SKTextureFilteringMode FilteringMode { get; set; } + [MacCatalyst (13, 1)] + [Export ("textureByApplyingCIFilter:")] + SKTexture TextureByApplyingCIFilter (CIFilter filter); - [Export ("usesMipmaps")] - bool UsesMipmaps { get; set; } + [Export ("textureRect")] + CGRect TextureRect { get; } - [Static] - [Export ("preloadTextures:withCompletionHandler:")] - [Async] - // note: unlike SKTextureAtlas completion can't be null (or it crash) - void PreloadTextures (SKTexture [] textures, Action completion); + [Export ("size")] + CGSize Size { get; } - [Export ("preloadWithCompletionHandler:")] - [Async] - // note: unlike SKTextureAtlas completion can't be null (or it crash) - void Preload (Action completion); + [Export ("filteringMode")] + SKTextureFilteringMode FilteringMode { get; set; } - [MacCatalyst (13, 1)] - [Export ("textureByGeneratingNormalMap")] - SKTexture CreateTextureByGeneratingNormalMap (); + [Export ("usesMipmaps")] + bool UsesMipmaps { get; set; } - [MacCatalyst (13, 1)] - [Export ("textureByGeneratingNormalMapWithSmoothness:contrast:")] - SKTexture CreateTextureByGeneratingNormalMap (nfloat smoothness, nfloat contrast); + [Static] + [Export ("preloadTextures:withCompletionHandler:")] + [Async] + // note: unlike SKTextureAtlas completion can't be null (or it crash) + void PreloadTextures (SKTexture [] textures, Action completion); - [MacCatalyst (13, 1)] - [Static, Export ("textureVectorNoiseWithSmoothness:size:")] - SKTexture FromTextureVectorNoise (nfloat smoothness, CGSize size); + [Export ("preloadWithCompletionHandler:")] + [Async] + // note: unlike SKTextureAtlas completion can't be null (or it crash) + void Preload (Action completion); - [MacCatalyst (13, 1)] - [Static, Export ("textureNoiseWithSmoothness:size:grayscale:")] - SKTexture FromTextureNoise (nfloat smoothness, CGSize size, bool grayscale); + [MacCatalyst (13, 1)] + [Export ("textureByGeneratingNormalMap")] + SKTexture CreateTextureByGeneratingNormalMap (); - [MacCatalyst (13, 1)] - [Static, Export ("textureWithData:size:flipped:")] - SKTexture FromData (NSData pixelData, CGSize size, bool flipped); + [MacCatalyst (13, 1)] + [Export ("textureByGeneratingNormalMapWithSmoothness:contrast:")] + SKTexture CreateTextureByGeneratingNormalMap (nfloat smoothness, nfloat contrast); - [MacCatalyst (13, 1)] - [Export ("CGImage")] - CGImage CGImage { get; } + [MacCatalyst (13, 1)] + [Static, Export ("textureVectorNoiseWithSmoothness:size:")] + SKTexture FromTextureVectorNoise (nfloat smoothness, CGSize size); - // Static Category from GameplayKit - [MacCatalyst (13, 1)] - [Static] - [Export ("textureWithNoiseMap:")] - SKTexture FromNoiseMap (GKNoiseMap noiseMap); - } + [MacCatalyst (13, 1)] + [Static, Export ("textureNoiseWithSmoothness:size:grayscale:")] + SKTexture FromTextureNoise (nfloat smoothness, CGSize size, bool grayscale); + + [MacCatalyst (13, 1)] + [Static, Export ("textureWithData:size:flipped:")] + SKTexture FromData (NSData pixelData, CGSize size, bool flipped); - /// A method that modifies a texture in place. - delegate void SKTextureModify (IntPtr pixelData, nuint lengthInBytes); + [MacCatalyst (13, 1)] + [Export ("CGImage")] + CGImage CGImage { get; } - /// A texture that can be modified after assignment. - /// - /// Apple documentation for SKMutableTexture + // Static Category from GameplayKit [MacCatalyst (13, 1)] - [BaseType (typeof (SKTexture))] - [DisableDefaultCtor] // cannot be created (like SKTexture) by calling `init` - interface SKMutableTexture { - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [Static] + [Export ("textureWithNoiseMap:")] + SKTexture FromNoiseMap (GKNoiseMap noiseMap); +} - [Export ("initWithSize:pixelFormat:")] - NativeHandle Constructor (CGSize size, CVPixelFormatType pixelFormat); +/// A method that modifies a texture in place. +delegate void SKTextureModify (IntPtr pixelData, nuint lengthInBytes); - [Static, Export ("mutableTextureWithSize:")] - SKMutableTexture Create (CGSize size); +/// A texture that can be modified after assignment. +/// +/// Apple documentation for SKMutableTexture +[MacCatalyst (13, 1)] +[BaseType (typeof (SKTexture))] +[DisableDefaultCtor] // cannot be created (like SKTexture) by calling `init` +interface SKMutableTexture { + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [Export ("modifyPixelDataWithBlock:")] - void ModifyPixelData (SKTextureModify modifyMethod); - } + [Export ("initWithSize:pixelFormat:")] + NativeHandle Constructor (CGSize size, CVPixelFormatType pixelFormat); - delegate void SKTextureAtlasLoadCallback (NSError error, SKTextureAtlas foundAtlases); + [Static, Export ("mutableTextureWithSize:")] + SKMutableTexture Create (CGSize size); + + [Export ("modifyPixelDataWithBlock:")] + void ModifyPixelData (SKTextureModify modifyMethod); +} + +delegate void SKTextureAtlasLoadCallback (NSError error, SKTextureAtlas foundAtlases); + +/// A collection of s that are loaded from a single source. +/// +/// +/// Apple documentation for SKTextureAtlas +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +partial interface SKTextureAtlas : NSSecureCoding { + + [Static, Export ("atlasNamed:")] + SKTextureAtlas FromName (string name); + + [Export ("textureNamed:")] + SKTexture TextureNamed (string name); + + [Export ("textureNames")] + string [] TextureNames { get; } + + [Static] + [Export ("preloadTextureAtlases:withCompletionHandler:")] + [Async] + // Unfortunate name, should have been PreloadTextureAtlases + void PreloadTextures (SKTextureAtlas [] textures, Action completion); - /// A collection of s that are loaded from a single source. - /// - /// - /// Apple documentation for SKTextureAtlas [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - partial interface SKTextureAtlas : NSSecureCoding { + [Static] + [Export ("preloadTextureAtlasesNamed:withCompletionHandler:")] + [Async (ResultTypeName = "SKTextureAtlasLoadResult")] + void PreloadTextureAtlases (string [] atlasNames, SKTextureAtlasLoadCallback completionHandler); - [Static, Export ("atlasNamed:")] - SKTextureAtlas FromName (string name); + [Export ("preloadWithCompletionHandler:")] + [Async] + void Preload (Action completion); - [Export ("textureNamed:")] - SKTexture TextureNamed (string name); + [MacCatalyst (13, 1)] + [Static, Export ("atlasWithDictionary:")] + SKTextureAtlas FromDictionary (NSDictionary properties); - [Export ("textureNames")] - string [] TextureNames { get; } +} - [Static] - [Export ("preloadTextureAtlases:withCompletionHandler:")] - [Async] - // Unfortunate name, should have been PreloadTextureAtlases - void PreloadTextures (SKTextureAtlas [] textures, Action completion); +/// Holds shareable uniform data for SKShader objects. +/// +/// Apple documentation for SKUniform +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKUniform : NSCopying, NSSecureCoding { + [Export ("initWithName:")] + NativeHandle Constructor (string name); - [MacCatalyst (13, 1)] - [Static] - [Export ("preloadTextureAtlasesNamed:withCompletionHandler:")] - [Async (ResultTypeName = "SKTextureAtlasLoadResult")] - void PreloadTextureAtlases (string [] atlasNames, SKTextureAtlasLoadCallback completionHandler); + [Export ("initWithName:texture:")] + NativeHandle Constructor (string name, [NullAllowed] SKTexture texture); - [Export ("preloadWithCompletionHandler:")] - [Async] - void Preload (Action completion); + [Export ("initWithName:float:")] + NativeHandle Constructor (string name, float /* float, not CGFloat */ value); - [MacCatalyst (13, 1)] - [Static, Export ("atlasWithDictionary:")] - SKTextureAtlas FromDictionary (NSDictionary properties); + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector2:")] + IntPtr InitWithNameFloatVector2 (string name, Vector2 value); - } + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [MarshalNativeExceptions] + [Internal] + IntPtr InitWithNameVectorFloat2 (string name, Vector2 value); - /// Holds shareable uniform data for SKShader objects. - /// - /// Apple documentation for SKUniform - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKUniform : NSCopying, NSSecureCoding { - [Export ("initWithName:")] - NativeHandle Constructor (string name); - - [Export ("initWithName:texture:")] - NativeHandle Constructor (string name, [NullAllowed] SKTexture texture); - - [Export ("initWithName:float:")] - NativeHandle Constructor (string name, float /* float, not CGFloat */ value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector2:")] - IntPtr InitWithNameFloatVector2 (string name, Vector2 value); - - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [MarshalNativeExceptions] - [Internal] - IntPtr InitWithNameVectorFloat2 (string name, Vector2 value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector3:")] - IntPtr InitWithNameFloatVector3 (string name, Vector3 value); - - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameVectorFloat3 (string name, Vector3 value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector4:")] - IntPtr InitWithNameFloatVector4 (string name, Vector4 value); - - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameVectorFloat4 (string name, Vector4 value); + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector3:")] + IntPtr InitWithNameFloatVector3 (string name, Vector3 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [Internal] + IntPtr InitWithNameVectorFloat3 (string name, Vector3 value); + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector4:")] + IntPtr InitWithNameFloatVector4 (string name, Vector4 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [Internal] + IntPtr InitWithNameVectorFloat4 (string name, Vector4 value); #if !NET [Internal] @@ -1867,10 +1867,10 @@ interface SKUniform : NSCopying, NSSecureCoding { IntPtr InitWithNameMatrixFloat2x2 (string name, Matrix2 value); #endif // !NET - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat2x2 value); + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat2x2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + NativeHandle Constructor (string name, MatrixFloat2x2 value); #if !NET [Internal] @@ -1888,10 +1888,10 @@ interface SKUniform : NSCopying, NSSecureCoding { IntPtr InitWithNameMatrixFloat3x3 (string name, Matrix3 value); #endif // !NET - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat3x3 value); + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat3x3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + NativeHandle Constructor (string name, MatrixFloat3x3 value); #if !NET [Internal] @@ -1911,80 +1911,80 @@ interface SKUniform : NSCopying, NSSecureCoding { IntPtr InitWithNameMatrixFloat4x4 (string name, Matrix4 value); #endif // !NET - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat4x4:")] + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat4x4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + NativeHandle Constructor (string name, MatrixFloat4x4 value); + + [Export ("name")] + string Name { get; } + + [Export ("uniformType")] + SKUniformType UniformType { get; } + + [Export ("textureValue")] + [NullAllowed] + SKTexture TextureValue { get; set; } + + [Export ("floatValue")] + float FloatValue { get; set; } /* float, not CGFloat */ + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector2Value")] + Vector2 _FloatVector2Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] + [Internal] + Vector2 _VectorFloat2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector3Value")] + Vector3 _FloatVector3Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] + [Internal] + Vector3 _VectorFloat3Value { [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat4x4 value); - - [Export ("name")] - string Name { get; } - - [Export ("uniformType")] - SKUniformType UniformType { get; } - - [Export ("textureValue")] - [NullAllowed] - SKTexture TextureValue { get; set; } - - [Export ("floatValue")] - float FloatValue { get; set; } /* float, not CGFloat */ - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector2Value")] - Vector2 _FloatVector2Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] - [Internal] - Vector2 _VectorFloat2Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector3Value")] - Vector3 _FloatVector3Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] - [Internal] - Vector3 _VectorFloat3Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector4Value")] - Vector4 _FloatVector4Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] - [Internal] - Vector4 _VectorFloat4Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector4Value")] + Vector4 _FloatVector4Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] + [Internal] + Vector4 _VectorFloat4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } #if !NET [Internal] @@ -1995,14 +1995,14 @@ Vector4 _VectorFloat4Value { Matrix2 _FloatMatrix2Value { get; set; } #endif // !NET - [MacCatalyst (13, 1)] - [Export ("matrixFloat2x2Value", ArgumentSemantic.Assign)] - MatrixFloat2x2 MatrixFloat2x2Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [MacCatalyst (13, 1)] + [Export ("matrixFloat2x2Value", ArgumentSemantic.Assign)] + MatrixFloat2x2 MatrixFloat2x2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } #if !NET [Internal] @@ -2013,14 +2013,14 @@ MatrixFloat2x2 MatrixFloat2x2Value { Matrix3 _FloatMatrix3Value { get; set; } #endif // !NET - [MacCatalyst (13, 1)] - [Export ("matrixFloat3x3Value", ArgumentSemantic.Assign)] - MatrixFloat3x3 MatrixFloat3x3Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [MacCatalyst (13, 1)] + [Export ("matrixFloat3x3Value", ArgumentSemantic.Assign)] + MatrixFloat3x3 MatrixFloat3x3Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } #if !NET [Internal] @@ -2031,42 +2031,42 @@ MatrixFloat3x3 MatrixFloat3x3Value { Matrix4 _FloatMatrix4Value { get; set; } #endif // !NET - [MacCatalyst (13, 1)] - [Export ("matrixFloat4x4Value", ArgumentSemantic.Assign)] - MatrixFloat4x4 MatrixFloat4x4Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [MacCatalyst (13, 1)] + [Export ("matrixFloat4x4Value", ArgumentSemantic.Assign)] + MatrixFloat4x4 MatrixFloat4x4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } - [Static, Export ("uniformWithName:")] - SKUniform Create (string name); + [Static, Export ("uniformWithName:")] + SKUniform Create (string name); - [Static, Export ("uniformWithName:texture:")] - SKUniform Create (string name, [NullAllowed] SKTexture texture); + [Static, Export ("uniformWithName:texture:")] + SKUniform Create (string name, [NullAllowed] SKTexture texture); - [Static, Export ("uniformWithName:float:")] - SKUniform Create (string name, float /* float, not CGFloat */ value); + [Static, Export ("uniformWithName:float:")] + SKUniform Create (string name, float /* float, not CGFloat */ value); - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [MarshalNativeExceptions] - SKUniform Create (string name, Vector2 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + [MarshalNativeExceptions] + SKUniform Create (string name, Vector2 value); - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Vector3 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, Vector3 value); - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Vector4 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, Vector4 value); #if !NET [Obsolete ("Use the '(string, MatrixFloat2x2)' overload instead.")] @@ -2076,11 +2076,11 @@ MatrixFloat4x4 MatrixFloat4x4Value { SKUniform Create (string name, Matrix2 value); #endif // !NET - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat2x2 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat2x2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, MatrixFloat2x2 value); #if !NET [Obsolete ("Use the '(string, MatrixFloat3x3)' overload instead.")] @@ -2090,11 +2090,11 @@ MatrixFloat4x4 MatrixFloat4x4Value { SKUniform Create (string name, Matrix3 value); #endif - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat3x3 value); + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat3x3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, MatrixFloat3x3 value); #if !NET [Obsolete ("Use 'the '(string, MatrixFloat4x4)' overload instead.")] @@ -2104,1415 +2104,1415 @@ MatrixFloat4x4 MatrixFloat4x4Value { SKUniform Create (string name, Matrix4 value); #endif // !NET - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat4x4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat4x4 value); - } + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat4x4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, MatrixFloat4x4 value); +} - /// The delegate for a custom action, used with . - delegate void SKActionDurationHandler (SKNode node, nfloat elapsedTime); +/// The delegate for a custom action, used with . +delegate void SKActionDurationHandler (SKNode node, nfloat elapsedTime); - /// - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] // To create an action, call the class method for the action you are interested in. - partial interface SKAction : NSSecureCoding, NSCopying { +/// +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] // To create an action, call the class method for the action you are interested in. +partial interface SKAction : NSSecureCoding, NSCopying { - [Export ("duration")] - double Duration { get; set; } + [Export ("duration")] + double Duration { get; set; } - [Export ("timingMode")] - SKActionTimingMode TimingMode { get; set; } + [Export ("timingMode")] + SKActionTimingMode TimingMode { get; set; } - [Export ("speed")] - nfloat Speed { get; set; } + [Export ("speed")] + nfloat Speed { get; set; } - [Export ("reversedAction")] - SKAction ReversedAction { get; } + [Export ("reversedAction")] + SKAction ReversedAction { get; } - // These are in a category - [Static, Export ("moveByX:y:duration:")] - SKAction MoveBy (nfloat deltaX, nfloat deltaY, double sec); + // These are in a category + [Static, Export ("moveByX:y:duration:")] + SKAction MoveBy (nfloat deltaX, nfloat deltaY, double sec); - [Static, Export ("moveBy:duration:")] - SKAction MoveBy (CGVector delta, double duration); + [Static, Export ("moveBy:duration:")] + SKAction MoveBy (CGVector delta, double duration); - [Static, Export ("moveTo:duration:")] - SKAction MoveTo (CGPoint location, double sec); + [Static, Export ("moveTo:duration:")] + SKAction MoveTo (CGPoint location, double sec); - [Static, Export ("moveToX:duration:")] - SKAction MoveToX (nfloat x, double sec); + [Static, Export ("moveToX:duration:")] + SKAction MoveToX (nfloat x, double sec); - [Static, Export ("moveToY:duration:")] - SKAction MoveToY (nfloat y, double sec); + [Static, Export ("moveToY:duration:")] + SKAction MoveToY (nfloat y, double sec); - [Static, Export ("rotateByAngle:duration:")] - SKAction RotateByAngle (nfloat radians, double sec); + [Static, Export ("rotateByAngle:duration:")] + SKAction RotateByAngle (nfloat radians, double sec); - [Static, Export ("rotateToAngle:duration:")] - SKAction RotateToAngle (nfloat radians, double sec); + [Static, Export ("rotateToAngle:duration:")] + SKAction RotateToAngle (nfloat radians, double sec); - [Static, Export ("rotateToAngle:duration:shortestUnitArc:")] - SKAction RotateToAngle (nfloat radians, double sec, bool shortedUnitArc); + [Static, Export ("rotateToAngle:duration:shortestUnitArc:")] + SKAction RotateToAngle (nfloat radians, double sec, bool shortedUnitArc); - [Static, Export ("resizeByWidth:height:duration:")] - SKAction ResizeByWidth (nfloat width, nfloat height, double duration); + [Static, Export ("resizeByWidth:height:duration:")] + SKAction ResizeByWidth (nfloat width, nfloat height, double duration); - [Static, Export ("resizeToWidth:height:duration:")] - SKAction ResizeTo (nfloat width, nfloat height, double duration); + [Static, Export ("resizeToWidth:height:duration:")] + SKAction ResizeTo (nfloat width, nfloat height, double duration); - [Static, Export ("resizeToWidth:duration:")] - SKAction ResizeToWidth (nfloat width, double duration); + [Static, Export ("resizeToWidth:duration:")] + SKAction ResizeToWidth (nfloat width, double duration); - [Static, Export ("resizeToHeight:duration:")] - SKAction ResizeToHeight (nfloat height, double duration); + [Static, Export ("resizeToHeight:duration:")] + SKAction ResizeToHeight (nfloat height, double duration); - [Static, Export ("scaleBy:duration:")] - SKAction ScaleBy (nfloat scale, double sec); + [Static, Export ("scaleBy:duration:")] + SKAction ScaleBy (nfloat scale, double sec); - [Static, Export ("scaleXBy:y:duration:")] - SKAction ScaleBy (nfloat xScale, nfloat yScale, double sec); + [Static, Export ("scaleXBy:y:duration:")] + SKAction ScaleBy (nfloat xScale, nfloat yScale, double sec); - [Static, Export ("scaleTo:duration:")] - SKAction ScaleTo (nfloat scale, double sec); + [Static, Export ("scaleTo:duration:")] + SKAction ScaleTo (nfloat scale, double sec); - [Static, Export ("scaleXTo:y:duration:")] - SKAction ScaleTo (nfloat xScale, nfloat yScale, double sec); + [Static, Export ("scaleXTo:y:duration:")] + SKAction ScaleTo (nfloat xScale, nfloat yScale, double sec); - [Static, Export ("scaleXTo:duration:")] - SKAction ScaleXTo (nfloat scale, double sec); + [Static, Export ("scaleXTo:duration:")] + SKAction ScaleXTo (nfloat scale, double sec); - [Static, Export ("scaleYTo:duration:")] - SKAction ScaleYTo (nfloat scale, double sec); + [Static, Export ("scaleYTo:duration:")] + SKAction ScaleYTo (nfloat scale, double sec); - [MacCatalyst (13, 1)] - [Static] - [Export ("scaleToSize:duration:")] - SKAction ScaleTo (CGSize size, double sec); + [MacCatalyst (13, 1)] + [Static] + [Export ("scaleToSize:duration:")] + SKAction ScaleTo (CGSize size, double sec); - [Static, Export ("sequence:")] - SKAction Sequence ([Params] SKAction [] actions); + [Static, Export ("sequence:")] + SKAction Sequence ([Params] SKAction [] actions); - [Static, Export ("group:")] - SKAction Group ([Params] SKAction [] actions); + [Static, Export ("group:")] + SKAction Group ([Params] SKAction [] actions); - [Static, Export ("repeatAction:count:")] - SKAction RepeatAction (SKAction action, nuint count); + [Static, Export ("repeatAction:count:")] + SKAction RepeatAction (SKAction action, nuint count); - [Static, Export ("repeatActionForever:")] - SKAction RepeatActionForever (SKAction action); + [Static, Export ("repeatActionForever:")] + SKAction RepeatActionForever (SKAction action); - [Static, Export ("fadeInWithDuration:")] - SKAction FadeInWithDuration (double sec); + [Static, Export ("fadeInWithDuration:")] + SKAction FadeInWithDuration (double sec); - [Static, Export ("fadeOutWithDuration:")] - SKAction FadeOutWithDuration (double sec); + [Static, Export ("fadeOutWithDuration:")] + SKAction FadeOutWithDuration (double sec); - [Static, Export ("fadeAlphaBy:duration:")] - SKAction FadeAlphaBy (nfloat factor, double sec); + [Static, Export ("fadeAlphaBy:duration:")] + SKAction FadeAlphaBy (nfloat factor, double sec); - [Static, Export ("fadeAlphaTo:duration:")] - SKAction FadeAlphaTo (nfloat alpha, double sec); + [Static, Export ("fadeAlphaTo:duration:")] + SKAction FadeAlphaTo (nfloat alpha, double sec); - [MacCatalyst (13, 1)] - [Static, Export ("setTexture:")] - SKAction SetTexture (SKTexture texture); + [MacCatalyst (13, 1)] + [Static, Export ("setTexture:")] + SKAction SetTexture (SKTexture texture); - [MacCatalyst (13, 1)] - [Static, Export ("setTexture:resize:")] - SKAction SetTexture (SKTexture texture, bool resize); + [MacCatalyst (13, 1)] + [Static, Export ("setTexture:resize:")] + SKAction SetTexture (SKTexture texture, bool resize); - [Static, Export ("animateWithTextures:timePerFrame:")] - SKAction AnimateWithTextures (SKTexture [] textures, double sec); + [Static, Export ("animateWithTextures:timePerFrame:")] + SKAction AnimateWithTextures (SKTexture [] textures, double sec); - [Static, Export ("animateWithTextures:timePerFrame:resize:restore:")] - SKAction AnimateWithTextures (SKTexture [] textures, double sec, bool resize, bool restore); + [Static, Export ("animateWithTextures:timePerFrame:resize:restore:")] + SKAction AnimateWithTextures (SKTexture [] textures, double sec, bool resize, bool restore); - [Static, Export ("playSoundFileNamed:waitForCompletion:")] - SKAction PlaySoundFileNamed (string soundFile, bool wait); + [Static, Export ("playSoundFileNamed:waitForCompletion:")] + SKAction PlaySoundFileNamed (string soundFile, bool wait); - [Static, Export ("colorizeWithColor:colorBlendFactor:duration:")] - SKAction ColorizeWithColor (UIColor color, nfloat colorBlendFactor, double sec); + [Static, Export ("colorizeWithColor:colorBlendFactor:duration:")] + SKAction ColorizeWithColor (UIColor color, nfloat colorBlendFactor, double sec); - [Static, Export ("colorizeWithColorBlendFactor:duration:")] - SKAction ColorizeWithColorBlendFactor (nfloat colorBlendFactor, double sec); + [Static, Export ("colorizeWithColorBlendFactor:duration:")] + SKAction ColorizeWithColorBlendFactor (nfloat colorBlendFactor, double sec); - [Static, Export ("followPath:duration:")] - SKAction FollowPath (CGPath path, double sec); + [Static, Export ("followPath:duration:")] + SKAction FollowPath (CGPath path, double sec); - [Static, Export ("followPath:asOffset:orientToPath:duration:")] + [Static, Export ("followPath:asOffset:orientToPath:duration:")] #if XAMCORE_5_0 SKAction FollowPath (CGPath path, bool offset, bool orientToPath, double sec); #else - SKAction FollowPath (CGPath path, bool offset, bool orient, double sec); + SKAction FollowPath (CGPath path, bool offset, bool orient, double sec); #endif - [MacCatalyst (13, 1)] - [Static, Export ("followPath:speed:")] - SKAction FollowPath (CGPath path, nfloat speed); + [MacCatalyst (13, 1)] + [Static, Export ("followPath:speed:")] + SKAction FollowPath (CGPath path, nfloat speed); - [MacCatalyst (13, 1)] - [Static, Export ("followPath:asOffset:orientToPath:speed:")] + [MacCatalyst (13, 1)] + [Static, Export ("followPath:asOffset:orientToPath:speed:")] #if XAMCORE_5_0 SKAction FollowPath (CGPath path, bool offset, bool orientToPath, nfloat speed); #else - SKAction FollowPath (CGPath path, bool offset, bool orient, nfloat speed); + SKAction FollowPath (CGPath path, bool offset, bool orient, nfloat speed); #endif - [Static, Export ("speedBy:duration:")] - SKAction SpeedBy (nfloat speed, double sec); + [Static, Export ("speedBy:duration:")] + SKAction SpeedBy (nfloat speed, double sec); - [Static, Export ("speedTo:duration:")] - SKAction SpeedTo (nfloat speed, double sec); + [Static, Export ("speedTo:duration:")] + SKAction SpeedTo (nfloat speed, double sec); - [Static, Export ("waitForDuration:")] - SKAction WaitForDuration (double sec); + [Static, Export ("waitForDuration:")] + SKAction WaitForDuration (double sec); - [Static, Export ("waitForDuration:withRange:")] - SKAction WaitForDuration (double sec, double durationRange); - - [Static, Export ("removeFromParent")] - SKAction RemoveFromParent (); - - [Static, Export ("performSelector:onTarget:")] - SKAction PerformSelector (Selector selector, NSObject target); + [Static, Export ("waitForDuration:withRange:")] + SKAction WaitForDuration (double sec, double durationRange); - [Static, Export ("runBlock:")] - SKAction Run (Action block); - - [Static, Export ("runBlock:queue:")] - SKAction Run (Action block, DispatchQueue queue); - - [Static, Export ("runAction:onChildWithName:")] - SKAction RunAction (SKAction action, string name); - - [Static, Export ("customActionWithDuration:actionBlock:")] - SKAction CustomActionWithDuration (double seconds, SKActionDurationHandler actionHandler); - - // - // iOS 8 cluster (a few more are above, as part of their family - // - [MacCatalyst (13, 1)] - [Static, Export ("hide")] - SKAction Hide (); - - [MacCatalyst (13, 1)] - [Static, Export ("unhide")] - SKAction Unhide (); - - [MacCatalyst (13, 1)] - [Static, Export ("reachTo:rootNode:duration:")] - SKAction ReachTo (CGPoint position, SKNode rootNode, double secs); - - [MacCatalyst (13, 1)] - [Static, Export ("reachTo:rootNode:velocity:")] - SKAction ReachTo (CGPoint position, SKNode rootNode, nfloat velocity); - - [MacCatalyst (13, 1)] - [Static, Export ("reachToNode:rootNode:duration:")] - SKAction ReachToNode (SKNode node, SKNode rootNode, double sec); - - [MacCatalyst (13, 1)] - [Static, Export ("reachToNode:rootNode:velocity:")] - SKAction ReachToNode (SKNode node, SKNode rootNode, nfloat velocity); - - [MacCatalyst (13, 1)] - [Static, Export ("strengthTo:duration:")] - SKAction StrengthTo (float /* float, not CGFloat */ strength, double sec); - - [MacCatalyst (13, 1)] - [Static, Export ("strengthBy:duration:")] - SKAction StrengthBy (float /* float, not CGFloat */ strength, double sec); - - [MacCatalyst (13, 1)] - [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] - SKActionTimingFunction2 TimingFunction2 { get; set; } - - [MacCatalyst (13, 1)] - [Static, Export ("falloffBy:duration:")] - SKAction FalloffBy (float /* float, not CGFloat */ to, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("falloffTo:duration:")] - SKAction FalloffTo (float falloff, double sec); - - // iOS 9 cluster - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:")] - [return: NullAllowed] - SKAction Create (string name); - - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:duration:")] - [return: NullAllowed] - SKAction Create (string name, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:fromURL:")] - [return: NullAllowed] - SKAction Create (string name, NSUrl url); - - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:fromURL:duration:")] - [return: NullAllowed] - SKAction Create (string name, NSUrl url, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("setNormalTexture:")] - SKAction SetNormalTexture (SKTexture texture); - - [MacCatalyst (13, 1)] - [Static] - [Export ("setNormalTexture:resize:")] - SKAction SetNormalTexture (SKTexture texture, bool resize); - - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithNormalTextures:timePerFrame:")] - SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame); - - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithNormalTextures:timePerFrame:resize:restore:")] - SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame, bool resize, bool restore); - - [MacCatalyst (13, 1)] - [Static] - [Export ("play")] - SKAction CreatePlay (); - - [MacCatalyst (13, 1)] - [Static] - [Export ("pause")] - SKAction CreatePause (); - - [MacCatalyst (13, 1)] - [Static] - [Export ("stop")] - SKAction CreateStop (); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changePlaybackRateTo:duration:")] - SKAction CreateChangePlaybackRate (float playbackRate, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changePlaybackRateBy:duration:")] - SKAction CreateChangePlaybackRateBy (float playbackRate, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeVolumeTo:duration:")] - SKAction CreateChangeVolume (float newVolume, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeVolumeBy:duration:")] - SKAction CreateChangeVolumeBy (float by, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeChargeTo:duration:")] - SKAction CreateChangeChargeTo (float newCharge, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeChargeBy:duration:")] - SKAction CreateChangeChargeBy (float by, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeMassTo:duration:")] - SKAction CreateChangeMassTo (float newMass, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeMassBy:duration:")] - SKAction CreateChangeMassBy (float by, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("applyForce:duration:")] - SKAction CreateApplyForce (CGVector force, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("applyForce:atPoint:duration:")] - SKAction CreateApplyForce (CGVector force, CGPoint point, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("applyTorque:duration:")] - SKAction CreateApplyTorque (nfloat torque, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("applyImpulse:duration:")] - SKAction CreateApplyImpulse (CGVector impulse, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("applyImpulse:atPoint:duration:")] - SKAction CreateApplyImpulse (CGVector impulse, CGPoint point, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("applyAngularImpulse:duration:")] - SKAction CreateApplyAngularImpulse (nfloat impulse, double duration); - - // SKAction_SKAudioNode inlined - - [MacCatalyst (13, 1)] - [Static] - [Export ("stereoPanTo:duration:")] - SKAction CreateStereoPanTo (float target, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("stereoPanBy:duration:")] - SKAction CreateStereoPanBy (float by, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeReverbTo:duration:")] - SKAction CreateChangeReverbTo (float target, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeReverbBy:duration:")] - SKAction CreateChangeReverbBy (float by, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeObstructionTo:duration:")] - SKAction CreateChangeObstructionTo (float target, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeObstructionBy:duration:")] - SKAction CreateChangeObstructionBy (float by, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeOcclusionTo:duration:")] - SKAction CreateChangeOcclusionTo (float target, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("changeOcclusionBy:duration:")] - SKAction CreateChangeOcclusionBy (float by, double duration); - - // SKAction_SKWarpable - - [MacCatalyst (13, 1)] - [Static] - [Export ("warpTo:duration:")] - [return: NullAllowed] - SKAction WarpTo (SKWarpGeometry warp, double duration); - - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithWarps:times:")] - [return: NullAllowed] - SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times); - - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithWarps:times:restore:")] - [return: NullAllowed] - SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times, bool restore); - } + [Static, Export ("removeFromParent")] + SKAction RemoveFromParent (); + + [Static, Export ("performSelector:onTarget:")] + SKAction PerformSelector (Selector selector, NSObject target); + + [Static, Export ("runBlock:")] + SKAction Run (Action block); + + [Static, Export ("runBlock:queue:")] + SKAction Run (Action block, DispatchQueue queue); - /// + [Static, Export ("runAction:onChildWithName:")] + SKAction RunAction (SKAction action, string name); + + [Static, Export ("customActionWithDuration:actionBlock:")] + SKAction CustomActionWithDuration (double seconds, SKActionDurationHandler actionHandler); + + // + // iOS 8 cluster (a few more are above, as part of their family + // [MacCatalyst (13, 1)] - [DisableDefaultCtor] // see https://bugzilla.xamarin.com/show_bug.cgi?id=14502 - [BaseType (typeof (NSObject))] - partial interface SKPhysicsBody : NSSecureCoding, NSCopying { + [Static, Export ("hide")] + SKAction Hide (); - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithBodies:")] - SKPhysicsBody FromBodies (SKPhysicsBody [] bodies); + [MacCatalyst (13, 1)] + [Static, Export ("unhide")] + SKAction Unhide (); - [Static, Export ("bodyWithCircleOfRadius:")] - SKPhysicsBody CreateCircularBody (nfloat radius); + [MacCatalyst (13, 1)] + [Static, Export ("reachTo:rootNode:duration:")] + SKAction ReachTo (CGPoint position, SKNode rootNode, double secs); - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithCircleOfRadius:center:")] - SKPhysicsBody CreateCircularBody (nfloat radius, CGPoint center); + [MacCatalyst (13, 1)] + [Static, Export ("reachTo:rootNode:velocity:")] + SKAction ReachTo (CGPoint position, SKNode rootNode, nfloat velocity); - [Static, Export ("bodyWithRectangleOfSize:")] - SKPhysicsBody CreateRectangularBody (CGSize size); + [MacCatalyst (13, 1)] + [Static, Export ("reachToNode:rootNode:duration:")] + SKAction ReachToNode (SKNode node, SKNode rootNode, double sec); - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithRectangleOfSize:center:")] - SKPhysicsBody CreateRectangularBody (CGSize size, CGPoint center); + [MacCatalyst (13, 1)] + [Static, Export ("reachToNode:rootNode:velocity:")] + SKAction ReachToNode (SKNode node, SKNode rootNode, nfloat velocity); - [Static, Export ("bodyWithPolygonFromPath:")] - SKPhysicsBody CreateBodyFromPath (CGPath path); + [MacCatalyst (13, 1)] + [Static, Export ("strengthTo:duration:")] + SKAction StrengthTo (float /* float, not CGFloat */ strength, double sec); - [Static, Export ("bodyWithEdgeFromPoint:toPoint:")] - SKPhysicsBody CreateEdge (CGPoint fromPoint, CGPoint toPoint); + [MacCatalyst (13, 1)] + [Static, Export ("strengthBy:duration:")] + SKAction StrengthBy (float /* float, not CGFloat */ strength, double sec); - [Static, Export ("bodyWithEdgeChainFromPath:")] - SKPhysicsBody CreateEdgeChain (CGPath path); + [MacCatalyst (13, 1)] + [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] + SKActionTimingFunction2 TimingFunction2 { get; set; } - [Static, Export ("bodyWithEdgeLoopFromPath:")] - SKPhysicsBody CreateEdgeLoop (CGPath path); + [MacCatalyst (13, 1)] + [Static, Export ("falloffBy:duration:")] + SKAction FalloffBy (float /* float, not CGFloat */ to, double duration); - [Static, Export ("bodyWithEdgeLoopFromRect:")] - SKPhysicsBody CreateEdgeLoop (CGRect rect); + [MacCatalyst (13, 1)] + [Static] + [Export ("falloffTo:duration:")] + SKAction FalloffTo (float falloff, double sec); - [Export ("dynamic")] - bool Dynamic { [Bind ("isDynamic")] get; set; } + // iOS 9 cluster + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:")] + [return: NullAllowed] + SKAction Create (string name); - [Export ("usesPreciseCollisionDetection")] - bool UsesPreciseCollisionDetection { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:duration:")] + [return: NullAllowed] + SKAction Create (string name, double duration); - [Export ("allowsRotation")] - bool AllowsRotation { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:fromURL:")] + [return: NullAllowed] + SKAction Create (string name, NSUrl url); - [Export ("resting")] - bool Resting { [Bind ("isResting")] get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:fromURL:duration:")] + [return: NullAllowed] + SKAction Create (string name, NSUrl url, double duration); - [Export ("friction")] - nfloat Friction { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("setNormalTexture:")] + SKAction SetNormalTexture (SKTexture texture); - [Export ("restitution")] - nfloat Restitution { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("setNormalTexture:resize:")] + SKAction SetNormalTexture (SKTexture texture, bool resize); - [Export ("linearDamping", ArgumentSemantic.Assign)] - nfloat LinearDamping { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithNormalTextures:timePerFrame:")] + SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame); - [Export ("angularDamping", ArgumentSemantic.Assign)] - nfloat AngularDamping { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithNormalTextures:timePerFrame:resize:restore:")] + SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame, bool resize, bool restore); - [Export ("density")] - nfloat Density { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("play")] + SKAction CreatePlay (); - [Export ("mass")] - nfloat Mass { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("pause")] + SKAction CreatePause (); - [Export ("area")] - nfloat Area { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("stop")] + SKAction CreateStop (); - [Export ("affectedByGravity", ArgumentSemantic.Assign)] - bool AffectedByGravity { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changePlaybackRateTo:duration:")] + SKAction CreateChangePlaybackRate (float playbackRate, double duration); - [Export ("categoryBitMask", ArgumentSemantic.Assign)] - uint CategoryBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Static] + [Export ("changePlaybackRateBy:duration:")] + SKAction CreateChangePlaybackRateBy (float playbackRate, double duration); - [Export ("collisionBitMask", ArgumentSemantic.Assign)] - uint CollisionBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Static] + [Export ("changeVolumeTo:duration:")] + SKAction CreateChangeVolume (float newVolume, double duration); - [Export ("contactTestBitMask", ArgumentSemantic.Assign)] - uint ContactTestBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Static] + [Export ("changeVolumeBy:duration:")] + SKAction CreateChangeVolumeBy (float by, double duration); - [Export ("joints")] - SKPhysicsJoint [] Joints { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeChargeTo:duration:")] + SKAction CreateChangeChargeTo (float newCharge, double duration); - [Export ("node", ArgumentSemantic.Weak)] - [NullAllowed] - SKNode Node { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeChargeBy:duration:")] + SKAction CreateChangeChargeBy (float by, double duration); - [Export ("velocity")] - CGVector Velocity { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeMassTo:duration:")] + SKAction CreateChangeMassTo (float newMass, double duration); - [Export ("angularVelocity")] - nfloat AngularVelocity { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeMassBy:duration:")] + SKAction CreateChangeMassBy (float by, double duration); - [Export ("applyForce:")] - void ApplyForce (CGVector force); + [MacCatalyst (13, 1)] + [Static] + [Export ("applyForce:duration:")] + SKAction CreateApplyForce (CGVector force, double duration); - [Export ("applyForce:atPoint:")] - void ApplyForce (CGVector force, CGPoint point); + [MacCatalyst (13, 1)] + [Static] + [Export ("applyForce:atPoint:duration:")] + SKAction CreateApplyForce (CGVector force, CGPoint point, double duration); - [Export ("applyTorque:")] - void ApplyTorque (nfloat torque); + [MacCatalyst (13, 1)] + [Static] + [Export ("applyTorque:duration:")] + SKAction CreateApplyTorque (nfloat torque, double duration); - [Export ("applyImpulse:")] - void ApplyImpulse (CGVector impulse); + [MacCatalyst (13, 1)] + [Static] + [Export ("applyImpulse:duration:")] + SKAction CreateApplyImpulse (CGVector impulse, double duration); - [Export ("applyImpulse:atPoint:")] - void ApplyImpulse (CGVector impulse, CGPoint point); + [MacCatalyst (13, 1)] + [Static] + [Export ("applyImpulse:atPoint:duration:")] + SKAction CreateApplyImpulse (CGVector impulse, CGPoint point, double duration); - [Export ("applyAngularImpulse:")] - void ApplyAngularImpulse (nfloat impulse); + [MacCatalyst (13, 1)] + [Static] + [Export ("applyAngularImpulse:duration:")] + SKAction CreateApplyAngularImpulse (nfloat impulse, double duration); - [Export ("allContactedBodies")] - SKPhysicsBody [] AllContactedBodies { get; } + // SKAction_SKAudioNode inlined - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithTexture:size:")] - SKPhysicsBody Create (SKTexture texture, CGSize size); + [MacCatalyst (13, 1)] + [Static] + [Export ("stereoPanTo:duration:")] + SKAction CreateStereoPanTo (float target, double duration); - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithTexture:alphaThreshold:size:")] - SKPhysicsBody Create (SKTexture texture, float /* float, not CGFloat */ alphaThreshold, CGSize size); + [MacCatalyst (13, 1)] + [Static] + [Export ("stereoPanBy:duration:")] + SKAction CreateStereoPanBy (float by, double duration); - [MacCatalyst (13, 1)] - [Export ("charge")] - nfloat Charge { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeReverbTo:duration:")] + SKAction CreateChangeReverbTo (float target, double duration); - [MacCatalyst (13, 1)] - [Export ("fieldBitMask")] - uint FieldBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Static] + [Export ("changeReverbBy:duration:")] + SKAction CreateChangeReverbBy (float by, double duration); - [MacCatalyst (13, 1)] - [Export ("pinned")] - bool Pinned { get; set; } - } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeObstructionTo:duration:")] + SKAction CreateChangeObstructionTo (float target, double duration); - /// Encapsulates the data of a collision between two s. - /// - /// - /// Apple documentation for SKPhysicsContact [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] // An SKPhysicsContact object is created automatically by Scene Kit - partial interface SKPhysicsContact { + [Static] + [Export ("changeObstructionBy:duration:")] + SKAction CreateChangeObstructionBy (float by, double duration); - [Export ("bodyA")] - SKPhysicsBody BodyA { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeOcclusionTo:duration:")] + SKAction CreateChangeOcclusionTo (float target, double duration); - [Export ("bodyB")] - SKPhysicsBody BodyB { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("changeOcclusionBy:duration:")] + SKAction CreateChangeOcclusionBy (float by, double duration); - [Export ("contactPoint")] - CGPoint ContactPoint { get; } + // SKAction_SKWarpable - [Export ("collisionImpulse")] - nfloat CollisionImpulse { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("warpTo:duration:")] + [return: NullAllowed] + SKAction WarpTo (SKWarpGeometry warp, double duration); - [MacCatalyst (13, 1)] - [Export ("contactNormal")] - CGVector ContactNormal { get; } + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithWarps:times:")] + [return: NullAllowed] + SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times); - } + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithWarps:times:restore:")] + [return: NullAllowed] + SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times, bool restore); +} - /// Interface representing the required methods (if any) of the protocol . - /// - /// This interface contains the required methods (if any) from the protocol defined by . - /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. - /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. - /// - interface ISKPhysicsContactDelegate { } +/// +[MacCatalyst (13, 1)] +[DisableDefaultCtor] // see https://bugzilla.xamarin.com/show_bug.cgi?id=14502 +[BaseType (typeof (NSObject))] +partial interface SKPhysicsBody : NSSecureCoding, NSCopying { - /// [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [Model] - [Protocol] - partial interface SKPhysicsContactDelegate { + [Static, Export ("bodyWithBodies:")] + SKPhysicsBody FromBodies (SKPhysicsBody [] bodies); - [Export ("didBeginContact:")] - void DidBeginContact (SKPhysicsContact contact); + [Static, Export ("bodyWithCircleOfRadius:")] + SKPhysicsBody CreateCircularBody (nfloat radius); - [Export ("didEndContact:")] - void DidEndContact (SKPhysicsContact contact); - } + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithCircleOfRadius:center:")] + SKPhysicsBody CreateCircularBody (nfloat radius, CGPoint center); - /// - delegate void SKPhysicsWorldBodiesEnumeratorHandler (SKPhysicsBody body, out bool stop); - /// The delegate used for enumerating bodies that fall along a ray when used with M:SpriteKit.SKPhysicsWorld.EnumerateBodies(System.Drawing.PointF,System.Drawing.PointF,SpriteKit.SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler*. - delegate void SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler (SKPhysicsBody body, CGPoint point, CGVector normal, out bool stop); + [Static, Export ("bodyWithRectangleOfSize:")] + SKPhysicsBody CreateRectangularBody (CGSize size); - /// [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject), - Delegates = new string [] { "WeakContactDelegate" }, - Events = new Type [] { typeof (SKPhysicsContactDelegate) })] - [DisableDefaultCtor] // You do not create SKPhysicsWorld objects directly; instead, read the physicsWorld property of an SKScene object. - partial interface SKPhysicsWorld : NSSecureCoding { + [Static, Export ("bodyWithRectangleOfSize:center:")] + SKPhysicsBody CreateRectangularBody (CGSize size, CGPoint center); - [Export ("gravity")] - CGVector Gravity { get; set; } + [Static, Export ("bodyWithPolygonFromPath:")] + SKPhysicsBody CreateBodyFromPath (CGPath path); - [Export ("speed")] - nfloat Speed { get; set; } + [Static, Export ("bodyWithEdgeFromPoint:toPoint:")] + SKPhysicsBody CreateEdge (CGPoint fromPoint, CGPoint toPoint); - [Export ("contactDelegate", ArgumentSemantic.Assign), NullAllowed] - NSObject WeakContactDelegate { get; set; } + [Static, Export ("bodyWithEdgeChainFromPath:")] + SKPhysicsBody CreateEdgeChain (CGPath path); - [Wrap ("WeakContactDelegate")] - ISKPhysicsContactDelegate ContactDelegate { get; set; } + [Static, Export ("bodyWithEdgeLoopFromPath:")] + SKPhysicsBody CreateEdgeLoop (CGPath path); - [Export ("addJoint:")] - void AddJoint (SKPhysicsJoint joint); + [Static, Export ("bodyWithEdgeLoopFromRect:")] + SKPhysicsBody CreateEdgeLoop (CGRect rect); - [Export ("removeJoint:")] - void RemoveJoint (SKPhysicsJoint joint); + [Export ("dynamic")] + bool Dynamic { [Bind ("isDynamic")] get; set; } - [Export ("removeAllJoints")] - void RemoveAllJoints (); + [Export ("usesPreciseCollisionDetection")] + bool UsesPreciseCollisionDetection { get; set; } - [Export ("bodyAtPoint:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGPoint point); + [Export ("allowsRotation")] + bool AllowsRotation { get; set; } - [Export ("bodyInRect:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGRect rect); + [Export ("resting")] + bool Resting { [Bind ("isResting")] get; set; } - [Export ("bodyAlongRayStart:end:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGPoint rayStart, CGPoint rayEnd); + [Export ("friction")] + nfloat Friction { get; set; } - [Export ("enumerateBodiesAtPoint:usingBlock:")] - void EnumerateBodies (CGPoint point, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + [Export ("restitution")] + nfloat Restitution { get; set; } - [Export ("enumerateBodiesInRect:usingBlock:")] - void EnumerateBodies (CGRect rect, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + [Export ("linearDamping", ArgumentSemantic.Assign)] + nfloat LinearDamping { get; set; } - [Export ("enumerateBodiesAlongRayStart:end:usingBlock:")] - void EnumerateBodies (CGPoint start, CGPoint end, SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler enumeratorHandler); + [Export ("angularDamping", ArgumentSemantic.Assign)] + nfloat AngularDamping { get; set; } - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Export ("sampleFieldsAt:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector3 SampleFields (/* vector_float3 */ Vector3 position); - } + [Export ("density")] + nfloat Density { get; set; } - /// - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [Abstract] // You never instantiate objects of this class directly - partial interface SKPhysicsJoint : NSSecureCoding { + [Export ("mass")] + nfloat Mass { get; set; } - [Export ("bodyA", ArgumentSemantic.Retain)] - SKPhysicsBody BodyA { get; set; } + [Export ("area")] + nfloat Area { get; } - [Export ("bodyB", ArgumentSemantic.Retain)] - SKPhysicsBody BodyB { get; set; } + [Export ("affectedByGravity", ArgumentSemantic.Assign)] + bool AffectedByGravity { get; set; } - [MacCatalyst (13, 1)] - [Export ("reactionForce")] - CGVector ReactionForce { get; } + [Export ("categoryBitMask", ArgumentSemantic.Assign)] + uint CategoryBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("reactionTorque")] - nfloat ReactionTorque { get; } - } + [Export ("collisionBitMask", ArgumentSemantic.Assign)] + uint CollisionBitMask { get; set; } /* uint32_t */ - /// A that pins two bodies to a common point. - /// - /// Apple documentation for SKPhysicsJointPin - [MacCatalyst (13, 1)] - [BaseType (typeof (SKPhysicsJoint))] - [DisableDefaultCtor] // impossible to set the `anchor` using the default ctor (see #14511) - partial interface SKPhysicsJointPin { + [Export ("contactTestBitMask", ArgumentSemantic.Assign)] + uint ContactTestBitMask { get; set; } /* uint32_t */ - [Static, Export ("jointWithBodyA:bodyB:anchor:")] - SKPhysicsJointPin Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); + [Export ("joints")] + SKPhysicsJoint [] Joints { get; } - [Export ("shouldEnableLimits")] - bool ShouldEnableLimits { get; set; } + [Export ("node", ArgumentSemantic.Weak)] + [NullAllowed] + SKNode Node { get; } - [Export ("lowerAngleLimit")] - nfloat LowerAngleLimit { get; set; } + [Export ("velocity")] + CGVector Velocity { get; set; } - [Export ("upperAngleLimit")] - nfloat UpperAngleLimit { get; set; } + [Export ("angularVelocity")] + nfloat AngularVelocity { get; set; } - [Export ("frictionTorque")] - nfloat FrictionTorque { get; set; } + [Export ("applyForce:")] + void ApplyForce (CGVector force); - [MacCatalyst (13, 1)] - [Export ("rotationSpeed")] - nfloat RotationSpeed { get; set; } - } + [Export ("applyForce:atPoint:")] + void ApplyForce (CGVector force, CGPoint point); - /// A that connects two bodies as if by a spring. - /// - /// Apple documentation for SKPhysicsJointSpring - [MacCatalyst (13, 1)] - [BaseType (typeof (SKPhysicsJoint))] - [DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) - partial interface SKPhysicsJointSpring { + [Export ("applyTorque:")] + void ApplyTorque (nfloat torque); - [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] - SKPhysicsJointSpring Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); + [Export ("applyImpulse:")] + void ApplyImpulse (CGVector impulse); - [Export ("damping")] - nfloat Damping { get; set; } + [Export ("applyImpulse:atPoint:")] + void ApplyImpulse (CGVector impulse, CGPoint point); - [Export ("frequency")] - nfloat Frequency { get; set; } - } + [Export ("applyAngularImpulse:")] + void ApplyAngularImpulse (nfloat impulse); - /// A that rigidly connects two bodies. - /// - /// At least one of the s must have its property set to or this will not behave properly. - /// - /// Apple documentation for SKPhysicsJointFixed + [Export ("allContactedBodies")] + SKPhysicsBody [] AllContactedBodies { get; } + + // + // iOS 8 + // [MacCatalyst (13, 1)] - [BaseType (typeof (SKPhysicsJoint))] - [DisableDefaultCtor] // https://bugzilla.xamarin.com/show_bug.cgi?id=14511 - partial interface SKPhysicsJointFixed { + [Static, Export ("bodyWithTexture:size:")] + SKPhysicsBody Create (SKTexture texture, CGSize size); - [Static, Export ("jointWithBodyA:bodyB:anchor:")] - SKPhysicsJointFixed Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); - } + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithTexture:alphaThreshold:size:")] + SKPhysicsBody Create (SKTexture texture, float /* float, not CGFloat */ alphaThreshold, CGSize size); - /// A that connects two bodies as if by a sliding rod. - /// - /// Apple documentation for SKPhysicsJointSliding [MacCatalyst (13, 1)] - [BaseType (typeof (SKPhysicsJoint))] - [DisableDefaultCtor] // impossible to set the `anchor` and `axis` using the default ctor (see #14511) - partial interface SKPhysicsJointSliding { + [Export ("charge")] + nfloat Charge { get; set; } - [Static, Export ("jointWithBodyA:bodyB:anchor:axis:")] - SKPhysicsJointSliding Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor, CGVector axis); + [MacCatalyst (13, 1)] + [Export ("fieldBitMask")] + uint FieldBitMask { get; set; } /* uint32_t */ - [Export ("shouldEnableLimits")] - bool ShouldEnableLimits { get; set; } + [MacCatalyst (13, 1)] + [Export ("pinned")] + bool Pinned { get; set; } +} - [Export ("lowerDistanceLimit")] - nfloat LowerDistanceLimit { get; set; } +/// Encapsulates the data of a collision between two s. +/// +/// +/// Apple documentation for SKPhysicsContact +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] // An SKPhysicsContact object is created automatically by Scene Kit +partial interface SKPhysicsContact { - [Export ("upperDistanceLimit")] - nfloat UpperDistanceLimit { get; set; } - } + [Export ("bodyA")] + SKPhysicsBody BodyA { get; } - /// A that connects two bodies as if by a rope. - /// - /// Apple documentation for SKPhysicsJointLimit - [MacCatalyst (13, 1)] - [BaseType (typeof (SKPhysicsJoint))] - [DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) - partial interface SKPhysicsJointLimit { + [Export ("bodyB")] + SKPhysicsBody BodyB { get; } - [Export ("maxLength")] - nfloat MaxLength { get; set; } + [Export ("contactPoint")] + CGPoint ContactPoint { get; } - [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] - SKPhysicsJointLimit Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); - } + [Export ("collisionImpulse")] + nfloat CollisionImpulse { get; } - /// Defines a range for acceptable float values. - /// - /// Apple documentation for SKRange [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKRange : NSSecureCoding, NSCopying { - [DesignatedInitializer] - [Export ("initWithLowerLimit:upperLimit:")] - NativeHandle Constructor (nfloat lowerLimit, nfloat upperLimier); + [Export ("contactNormal")] + CGVector ContactNormal { get; } - [Export ("lowerLimit")] - nfloat LowerLimit { get; set; } +} - [Export ("upperLimit")] - nfloat UpperLimit { get; set; } +/// Interface representing the required methods (if any) of the protocol . +/// +/// This interface contains the required methods (if any) from the protocol defined by . +/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. +/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. +/// +interface ISKPhysicsContactDelegate { } + +/// +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[Model] +[Protocol] +partial interface SKPhysicsContactDelegate { + + [Export ("didBeginContact:")] + void DidBeginContact (SKPhysicsContact contact); + + [Export ("didEndContact:")] + void DidEndContact (SKPhysicsContact contact); +} - [Static, Export ("rangeWithLowerLimit:upperLimit:")] - SKRange Create (nfloat lower, nfloat upper); +/// +delegate void SKPhysicsWorldBodiesEnumeratorHandler (SKPhysicsBody body, out bool stop); +/// The delegate used for enumerating bodies that fall along a ray when used with M:SpriteKit.SKPhysicsWorld.EnumerateBodies(System.Drawing.PointF,System.Drawing.PointF,SpriteKit.SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler*. +delegate void SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler (SKPhysicsBody body, CGPoint point, CGVector normal, out bool stop); - [Static, Export ("rangeWithLowerLimit:")] - SKRange CreateWithLowerLimit (nfloat lower); +/// +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject), + Delegates = new string [] { "WeakContactDelegate" }, + Events = new Type [] { typeof (SKPhysicsContactDelegate) })] +[DisableDefaultCtor] // You do not create SKPhysicsWorld objects directly; instead, read the physicsWorld property of an SKScene object. +partial interface SKPhysicsWorld : NSSecureCoding { - [Static, Export ("rangeWithUpperLimit:")] - SKRange CreateWithUpperLimit (nfloat upper); + [Export ("gravity")] + CGVector Gravity { get; set; } - [Static, Export ("rangeWithConstantValue:")] - SKRange CreateConstant (nfloat value); + [Export ("speed")] + nfloat Speed { get; set; } - [Static, Export ("rangeWithValue:variance:")] - SKRange CreateWithVariance (nfloat value, nfloat variance); + [Export ("contactDelegate", ArgumentSemantic.Assign), NullAllowed] + NSObject WeakContactDelegate { get; set; } - [Static, Export ("rangeWithNoLimits")] - SKRange CreateUnlimited (); - } + [Wrap ("WeakContactDelegate")] + ISKPhysicsContactDelegate ContactDelegate { get; set; } - /// A that holds audio information. - /// - /// Apple documentation for SKAudioNode - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - [DisableDefaultCtor] - interface SKAudioNode : NSSecureCoding { - [Export ("initWithAVAudioNode:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] AVAudioNode node); + [Export ("addJoint:")] + void AddJoint (SKPhysicsJoint joint); - [Export ("initWithFileNamed:")] - NativeHandle Constructor (string fileName); + [Export ("removeJoint:")] + void RemoveJoint (SKPhysicsJoint joint); - [Export ("initWithURL:")] - NativeHandle Constructor (NSUrl url); + [Export ("removeAllJoints")] + void RemoveAllJoints (); - [NullAllowed, Export ("avAudioNode", ArgumentSemantic.Retain)] - AVAudioNode AvAudioNode { get; set; } + [Export ("bodyAtPoint:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGPoint point); - [Export ("autoplayLooped")] - bool AutoplayLooped { get; set; } + [Export ("bodyInRect:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGRect rect); - [Export ("positional")] - bool Positional { [Bind ("isPositional")] get; set; } - } + [Export ("bodyAlongRayStart:end:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGPoint rayStart, CGPoint rayEnd); - /// A node that specifies the position inside a from which it can be rendered. - /// - /// Apple documentation for SKCameraNode + [Export ("enumerateBodiesAtPoint:usingBlock:")] + void EnumerateBodies (CGPoint point, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + + [Export ("enumerateBodiesInRect:usingBlock:")] + void EnumerateBodies (CGRect rect, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + + [Export ("enumerateBodiesAlongRayStart:end:usingBlock:")] + void EnumerateBodies (CGPoint start, CGPoint end, SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler enumeratorHandler); + + // + // iOS 8 + // [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - interface SKCameraNode { - [Export ("containsNode:")] - bool Contains (SKNode node); + [Export ("sampleFieldsAt:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector3 SampleFields (/* vector_float3 */ Vector3 position); +} - [Export ("containedNodeSet")] - NSSet ContainedNodeSet { get; } - } +/// +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[Abstract] // You never instantiate objects of this class directly +partial interface SKPhysicsJoint : NSSecureCoding { + + [Export ("bodyA", ArgumentSemantic.Retain)] + SKPhysicsBody BodyA { get; set; } + + [Export ("bodyB", ArgumentSemantic.Retain)] + SKPhysicsBody BodyB { get; set; } - /// A that holds an archived collection of child nodes that can be used in multiple places throughout the game. - /// - /// Apple documentation for SKReferenceNode [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - [DisableDefaultCtor] - interface SKReferenceNode { - [Export ("initWithURL:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] NSUrl url); + [Export ("reactionForce")] + CGVector ReactionForce { get; } - [Export ("initWithFileNamed:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] string fileName); + [MacCatalyst (13, 1)] + [Export ("reactionTorque")] + nfloat ReactionTorque { get; } +} - [Static] - [Export ("referenceNodeWithFileNamed:")] - SKReferenceNode FromFile (string fileName); +/// A that pins two bodies to a common point. +/// +/// Apple documentation for SKPhysicsJointPin +[MacCatalyst (13, 1)] +[BaseType (typeof (SKPhysicsJoint))] +[DisableDefaultCtor] // impossible to set the `anchor` using the default ctor (see #14511) +partial interface SKPhysicsJointPin { - [Static] - [Export ("referenceNodeWithURL:")] - SKReferenceNode FromUrl (NSUrl referenceUrl); + [Static, Export ("jointWithBodyA:bodyB:anchor:")] + SKPhysicsJointPin Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); - [Export ("didLoadReferenceNode:")] - void DidLoadReferenceNode ([NullAllowed] SKNode node); + [Export ("shouldEnableLimits")] + bool ShouldEnableLimits { get; set; } - [Export ("resolveReferenceNode")] - void Resolve (); - } + [Export ("lowerAngleLimit")] + nfloat LowerAngleLimit { get; set; } + + [Export ("upperAngleLimit")] + nfloat UpperAngleLimit { get; set; } + + [Export ("frictionTorque")] + nfloat FrictionTorque { get; set; } - /// Holds per-node data to be used with a custom shader. - /// - /// Apple documentation for SKAttribute [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] - interface SKAttribute : NSSecureCoding { - [Static] - [Export ("attributeWithName:type:")] - SKAttribute Create (string name, SKAttributeType type); + [Export ("rotationSpeed")] + nfloat RotationSpeed { get; set; } +} - [Export ("initWithName:type:")] - [DesignatedInitializer] - NativeHandle Constructor (string name, SKAttributeType type); +/// A that connects two bodies as if by a spring. +/// +/// Apple documentation for SKPhysicsJointSpring +[MacCatalyst (13, 1)] +[BaseType (typeof (SKPhysicsJoint))] +[DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) +partial interface SKPhysicsJointSpring { - [Export ("name")] - string Name { get; } + [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] + SKPhysicsJointSpring Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); - [Export ("type")] - SKAttributeType Type { get; } - } + [Export ("damping")] + nfloat Damping { get; set; } - /// Holds the value, of the appropriate , for an . - /// - /// Apple documentation for SKAttributeValue - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] // DesignatedInitializer below - interface SKAttributeValue : NSSecureCoding { - [DesignatedInitializer] - [Export ("init")] - NativeHandle Constructor (); + [Export ("frequency")] + nfloat Frequency { get; set; } +} + +/// A that rigidly connects two bodies. +/// +/// At least one of the s must have its property set to or this will not behave properly. +/// +/// Apple documentation for SKPhysicsJointFixed +[MacCatalyst (13, 1)] +[BaseType (typeof (SKPhysicsJoint))] +[DisableDefaultCtor] // https://bugzilla.xamarin.com/show_bug.cgi?id=14511 +partial interface SKPhysicsJointFixed { + + [Static, Export ("jointWithBodyA:bodyB:anchor:")] + SKPhysicsJointFixed Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); +} + +/// A that connects two bodies as if by a sliding rod. +/// +/// Apple documentation for SKPhysicsJointSliding +[MacCatalyst (13, 1)] +[BaseType (typeof (SKPhysicsJoint))] +[DisableDefaultCtor] // impossible to set the `anchor` and `axis` using the default ctor (see #14511) +partial interface SKPhysicsJointSliding { + + [Static, Export ("jointWithBodyA:bodyB:anchor:axis:")] + SKPhysicsJointSliding Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor, CGVector axis); + + [Export ("shouldEnableLimits")] + bool ShouldEnableLimits { get; set; } + + [Export ("lowerDistanceLimit")] + nfloat LowerDistanceLimit { get; set; } + + [Export ("upperDistanceLimit")] + nfloat UpperDistanceLimit { get; set; } +} + +/// A that connects two bodies as if by a rope. +/// +/// Apple documentation for SKPhysicsJointLimit +[MacCatalyst (13, 1)] +[BaseType (typeof (SKPhysicsJoint))] +[DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) +partial interface SKPhysicsJointLimit { + + [Export ("maxLength")] + nfloat MaxLength { get; set; } + + [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] + SKPhysicsJointLimit Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); +} + +/// Defines a range for acceptable float values. +/// +/// Apple documentation for SKRange +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKRange : NSSecureCoding, NSCopying { + [DesignatedInitializer] + [Export ("initWithLowerLimit:upperLimit:")] + NativeHandle Constructor (nfloat lowerLimit, nfloat upperLimier); + + [Export ("lowerLimit")] + nfloat LowerLimit { get; set; } + + [Export ("upperLimit")] + nfloat UpperLimit { get; set; } + + [Static, Export ("rangeWithLowerLimit:upperLimit:")] + SKRange Create (nfloat lower, nfloat upper); + + [Static, Export ("rangeWithLowerLimit:")] + SKRange CreateWithLowerLimit (nfloat lower); + + [Static, Export ("rangeWithUpperLimit:")] + SKRange CreateWithUpperLimit (nfloat upper); + + [Static, Export ("rangeWithConstantValue:")] + SKRange CreateConstant (nfloat value); + + [Static, Export ("rangeWithValue:variance:")] + SKRange CreateWithVariance (nfloat value, nfloat variance); + + [Static, Export ("rangeWithNoLimits")] + SKRange CreateUnlimited (); +} + +/// A that holds audio information. +/// +/// Apple documentation for SKAudioNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +[DisableDefaultCtor] +interface SKAudioNode : NSSecureCoding { + [Export ("initWithAVAudioNode:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] AVAudioNode node); + + [Export ("initWithFileNamed:")] + NativeHandle Constructor (string fileName); - [Static] - [Export ("valueWithFloat:")] - SKAttributeValue Create (float value); + [Export ("initWithURL:")] + NativeHandle Constructor (NSUrl url); - [Static] - [Export ("valueWithVectorFloat2:")] + [NullAllowed, Export ("avAudioNode", ArgumentSemantic.Retain)] + AVAudioNode AvAudioNode { get; set; } + + [Export ("autoplayLooped")] + bool AutoplayLooped { get; set; } + + [Export ("positional")] + bool Positional { [Bind ("isPositional")] get; set; } +} + +/// A node that specifies the position inside a from which it can be rendered. +/// +/// Apple documentation for SKCameraNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +interface SKCameraNode { + [Export ("containsNode:")] + bool Contains (SKNode node); + + [Export ("containedNodeSet")] + NSSet ContainedNodeSet { get; } +} + +/// A that holds an archived collection of child nodes that can be used in multiple places throughout the game. +/// +/// Apple documentation for SKReferenceNode +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +[DisableDefaultCtor] +interface SKReferenceNode { + [Export ("initWithURL:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] NSUrl url); + + [Export ("initWithFileNamed:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] string fileName); + + [Static] + [Export ("referenceNodeWithFileNamed:")] + SKReferenceNode FromFile (string fileName); + + [Static] + [Export ("referenceNodeWithURL:")] + SKReferenceNode FromUrl (NSUrl referenceUrl); + + [Export ("didLoadReferenceNode:")] + void DidLoadReferenceNode ([NullAllowed] SKNode node); + + [Export ("resolveReferenceNode")] + void Resolve (); +} + +/// Holds per-node data to be used with a custom shader. +/// +/// Apple documentation for SKAttribute +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface SKAttribute : NSSecureCoding { + [Static] + [Export ("attributeWithName:type:")] + SKAttribute Create (string name, SKAttributeType type); + + [Export ("initWithName:type:")] + [DesignatedInitializer] + NativeHandle Constructor (string name, SKAttributeType type); + + [Export ("name")] + string Name { get; } + + [Export ("type")] + SKAttributeType Type { get; } +} + +/// Holds the value, of the appropriate , for an . +/// +/// Apple documentation for SKAttributeValue +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] // DesignatedInitializer below +interface SKAttributeValue : NSSecureCoding { + [DesignatedInitializer] + [Export ("init")] + NativeHandle Constructor (); + + [Static] + [Export ("valueWithFloat:")] + SKAttributeValue Create (float value); + + [Static] + [Export ("valueWithVectorFloat2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKAttributeValue Create (Vector2 value); + + [Static] + [Export ("valueWithVectorFloat3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKAttributeValue Create (Vector3 value); + + [Static] + [Export ("valueWithVectorFloat4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKAttributeValue Create (Vector4 value); + + [Export ("floatValue")] + float FloatValue { get; set; } + + [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] + Vector2 VectorFloat2Value { [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector2 value); + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } - [Static] - [Export ("valueWithVectorFloat3:")] + [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] + Vector3 VectorFloat3Value { [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector3 value); + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } - [Static] - [Export ("valueWithVectorFloat4:")] + [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] + Vector4 VectorFloat4Value { [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector4 value); - - [Export ("floatValue")] - float FloatValue { get; set; } - - [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] - Vector2 VectorFloat2Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] - Vector3 VectorFloat3Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] - Vector4 VectorFloat4Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; } +} - /// A single kind of tile in a tile map. - /// - /// Apple documentation for SKTileDefinition - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] - interface SKTileDefinition : NSCopying, NSSecureCoding { - [Static] - [Export ("tileDefinitionWithTexture:")] - SKTileDefinition Create (SKTexture texture); +/// A single kind of tile in a tile map. +/// +/// Apple documentation for SKTileDefinition +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface SKTileDefinition : NSCopying, NSSecureCoding { + [Static] + [Export ("tileDefinitionWithTexture:")] + SKTileDefinition Create (SKTexture texture); + + [Static] + [Export ("tileDefinitionWithTexture:size:")] + SKTileDefinition Create (SKTexture texture, CGSize size); + + [Static] + [Export ("tileDefinitionWithTexture:normalTexture:size:")] + SKTileDefinition Create (SKTexture texture, SKTexture normalTexture, CGSize size); - [Static] - [Export ("tileDefinitionWithTexture:size:")] - SKTileDefinition Create (SKTexture texture, CGSize size); + [Static] + [Export ("tileDefinitionWithTextures:size:timePerFrame:")] + SKTileDefinition Create (SKTexture [] textures, CGSize size, nfloat timePerFrame); - [Static] - [Export ("tileDefinitionWithTexture:normalTexture:size:")] - SKTileDefinition Create (SKTexture texture, SKTexture normalTexture, CGSize size); + [Static] + [Export ("tileDefinitionWithTextures:normalTextures:size:timePerFrame:")] + SKTileDefinition Create (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); - [Static] - [Export ("tileDefinitionWithTextures:size:timePerFrame:")] - SKTileDefinition Create (SKTexture [] textures, CGSize size, nfloat timePerFrame); + [Export ("initWithTexture:")] + NativeHandle Constructor (SKTexture texture); - [Static] - [Export ("tileDefinitionWithTextures:normalTextures:size:timePerFrame:")] - SKTileDefinition Create (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); + [Export ("initWithTexture:size:")] + NativeHandle Constructor (SKTexture texture, CGSize size); - [Export ("initWithTexture:")] - NativeHandle Constructor (SKTexture texture); + [Export ("initWithTexture:normalTexture:size:")] + NativeHandle Constructor (SKTexture texture, SKTexture normalTexture, CGSize size); - [Export ("initWithTexture:size:")] - NativeHandle Constructor (SKTexture texture, CGSize size); + [Export ("initWithTextures:size:timePerFrame:")] + NativeHandle Constructor (SKTexture [] textures, CGSize size, nfloat timePerFrame); - [Export ("initWithTexture:normalTexture:size:")] - NativeHandle Constructor (SKTexture texture, SKTexture normalTexture, CGSize size); + [Export ("initWithTextures:normalTextures:size:timePerFrame:")] + NativeHandle Constructor (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); - [Export ("initWithTextures:size:timePerFrame:")] - NativeHandle Constructor (SKTexture [] textures, CGSize size, nfloat timePerFrame); + [Export ("textures", ArgumentSemantic.Copy)] + SKTexture [] Textures { get; set; } - [Export ("initWithTextures:normalTextures:size:timePerFrame:")] - NativeHandle Constructor (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); + [Export ("normalTextures", ArgumentSemantic.Copy)] + SKTexture [] NormalTextures { get; set; } - [Export ("textures", ArgumentSemantic.Copy)] - SKTexture [] Textures { get; set; } + [NullAllowed, Export ("userData", ArgumentSemantic.Retain)] + NSMutableDictionary UserData { get; set; } - [Export ("normalTextures", ArgumentSemantic.Copy)] - SKTexture [] NormalTextures { get; set; } + [NullAllowed, Export ("name")] + string Name { get; set; } - [NullAllowed, Export ("userData", ArgumentSemantic.Retain)] - NSMutableDictionary UserData { get; set; } + [Export ("size", ArgumentSemantic.Assign)] + CGSize Size { get; set; } - [NullAllowed, Export ("name")] - string Name { get; set; } + [Export ("timePerFrame")] + nfloat TimePerFrame { get; set; } - [Export ("size", ArgumentSemantic.Assign)] - CGSize Size { get; set; } + [Export ("placementWeight")] + nuint PlacementWeight { get; set; } - [Export ("timePerFrame")] - nfloat TimePerFrame { get; set; } + [Export ("rotation", ArgumentSemantic.Assign)] + SKTileDefinitionRotation Rotation { get; set; } - [Export ("placementWeight")] - nuint PlacementWeight { get; set; } + [Export ("flipVertically")] + bool FlipVertically { get; set; } - [Export ("rotation", ArgumentSemantic.Assign)] - SKTileDefinitionRotation Rotation { get; set; } + [Export ("flipHorizontally")] + bool FlipHorizontally { get; set; } +} - [Export ("flipVertically")] - bool FlipVertically { get; set; } +/// +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +interface SKTileMapNode : NSCopying, NSSecureCoding { + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); - [Export ("flipHorizontally")] - bool FlipHorizontally { get; set; } - } + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); - /// - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - interface SKTileMapNode : NSCopying, NSSecureCoding { - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:tileGroupLayout:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); + [Export ("initWithTileSet:columns:rows:tileSize:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:tileGroupLayout:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); + [Export ("initWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); - [Export ("initWithTileSet:columns:rows:tileSize:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); + [Export ("initWithTileSet:columns:rows:tileSize:tileGroupLayout:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); - [Export ("initWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); + [Export ("numberOfColumns")] + nuint NumberOfColumns { get; set; } - [Export ("initWithTileSet:columns:rows:tileSize:tileGroupLayout:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); + [Export ("numberOfRows")] + nuint NumberOfRows { get; set; } - [Export ("numberOfColumns")] - nuint NumberOfColumns { get; set; } + [Export ("tileSize", ArgumentSemantic.Assign)] + CGSize TileSize { get; set; } - [Export ("numberOfRows")] - nuint NumberOfRows { get; set; } + [Export ("mapSize")] + CGSize MapSize { get; } - [Export ("tileSize", ArgumentSemantic.Assign)] - CGSize TileSize { get; set; } + [Export ("tileSet", ArgumentSemantic.Assign)] + SKTileSet TileSet { get; set; } - [Export ("mapSize")] - CGSize MapSize { get; } + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("tileSet", ArgumentSemantic.Assign)] - SKTileSet TileSet { get; set; } + [Export ("color", ArgumentSemantic.Retain)] + UIColor Color { get; set; } - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + [Export ("blendMode", ArgumentSemantic.Assign)] + SKBlendMode BlendMode { get; set; } - [Export ("color", ArgumentSemantic.Retain)] - UIColor Color { get; set; } + [Export ("anchorPoint", ArgumentSemantic.Assign)] + CGPoint AnchorPoint { get; set; } - [Export ("blendMode", ArgumentSemantic.Assign)] - SKBlendMode BlendMode { get; set; } + [NullAllowed, Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - [Export ("anchorPoint", ArgumentSemantic.Assign)] - CGPoint AnchorPoint { get; set; } + [Export ("lightingBitMask")] + uint LightingBitMask { get; set; } - [NullAllowed, Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [Export ("enableAutomapping")] + bool EnableAutomapping { get; set; } - [Export ("lightingBitMask")] - uint LightingBitMask { get; set; } + [Export ("fillWithTileGroup:")] + void Fill ([NullAllowed] SKTileGroup tileGroup); - [Export ("enableAutomapping")] - bool EnableAutomapping { get; set; } + [Export ("tileDefinitionAtColumn:row:")] + [return: NullAllowed] + SKTileDefinition GetTileDefinition (nuint column, nuint row); - [Export ("fillWithTileGroup:")] - void Fill ([NullAllowed] SKTileGroup tileGroup); + [Export ("tileGroupAtColumn:row:")] + [return: NullAllowed] + SKTileGroup GetTileGroup (nuint column, nuint row); - [Export ("tileDefinitionAtColumn:row:")] - [return: NullAllowed] - SKTileDefinition GetTileDefinition (nuint column, nuint row); + [Export ("setTileGroup:forColumn:row:")] + void SetTileGroup ([NullAllowed] SKTileGroup tileGroup, nuint column, nuint row); - [Export ("tileGroupAtColumn:row:")] - [return: NullAllowed] - SKTileGroup GetTileGroup (nuint column, nuint row); + [Export ("setTileGroup:andTileDefinition:forColumn:row:")] + void SetTileGroup (SKTileGroup tileGroup, SKTileDefinition tileDefinition, nuint column, nuint row); - [Export ("setTileGroup:forColumn:row:")] - void SetTileGroup ([NullAllowed] SKTileGroup tileGroup, nuint column, nuint row); + [Export ("tileColumnIndexFromPosition:")] + nuint GetTileColumnIndex (CGPoint position); - [Export ("setTileGroup:andTileDefinition:forColumn:row:")] - void SetTileGroup (SKTileGroup tileGroup, SKTileDefinition tileDefinition, nuint column, nuint row); + [Export ("tileRowIndexFromPosition:")] + nuint GetTileRowIndex (CGPoint position); - [Export ("tileColumnIndexFromPosition:")] - nuint GetTileColumnIndex (CGPoint position); + [Export ("centerOfTileAtColumn:row:")] + CGPoint GetCenterOfTile (nuint column, nuint row); - [Export ("tileRowIndexFromPosition:")] - nuint GetTileRowIndex (CGPoint position); + // Static Category from GameplayKit + [MacCatalyst (13, 1)] + [Static] + [Export ("tileMapNodesWithTileSet:columns:rows:tileSize:fromNoiseMap:tileTypeNoiseMapThresholds:")] + SKTileMapNode [] FromTileSet (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, GKNoiseMap noiseMap, NSNumber [] thresholds); - [Export ("centerOfTileAtColumn:row:")] - CGPoint GetCenterOfTile (nuint column, nuint row); + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - // Static Category from GameplayKit - [MacCatalyst (13, 1)] - [Static] - [Export ("tileMapNodesWithTileSet:columns:rows:tileSize:fromNoiseMap:tileTypeNoiseMapThresholds:")] - SKTileMapNode [] FromTileSet (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, GKNoiseMap noiseMap, NSNumber [] thresholds); + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); +} - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); +/// Represents the possible elements of a in the form of objects. +/// +/// An collects a set of related objects that may be placed on a . Additionally, it may define a default tile group and tile size. +/// +/// Apple documentation for SKTileSet +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKTileSet : NSCopying, NSSecureCoding { + [Static] + [Export ("tileSetWithTileGroups:")] + SKTileSet Create (SKTileGroup [] tileGroups); - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); - } + [Static] + [Export ("tileSetWithTileGroups:tileSetType:")] + SKTileSet Create (SKTileGroup [] tileGroups, SKTileSetType tileSetType); - /// Represents the possible elements of a in the form of objects. - /// - /// An collects a set of related objects that may be placed on a . Additionally, it may define a default tile group and tile size. - /// - /// Apple documentation for SKTileSet - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKTileSet : NSCopying, NSSecureCoding { - [Static] - [Export ("tileSetWithTileGroups:")] - SKTileSet Create (SKTileGroup [] tileGroups); + [Export ("initWithTileGroups:")] + NativeHandle Constructor (SKTileGroup [] tileGroups); - [Static] - [Export ("tileSetWithTileGroups:tileSetType:")] - SKTileSet Create (SKTileGroup [] tileGroups, SKTileSetType tileSetType); + [Export ("initWithTileGroups:tileSetType:")] + NativeHandle Constructor (SKTileGroup [] tileGroups, SKTileSetType tileSetType); - [Export ("initWithTileGroups:")] - NativeHandle Constructor (SKTileGroup [] tileGroups); + [Static] + [Export ("tileSetNamed:")] + [return: NullAllowed] + SKTileSet FromName (string name); - [Export ("initWithTileGroups:tileSetType:")] - NativeHandle Constructor (SKTileGroup [] tileGroups, SKTileSetType tileSetType); + [Static] + [Export ("tileSetFromURL:")] + [return: NullAllowed] + SKTileSet FromUrl (NSUrl url); - [Static] - [Export ("tileSetNamed:")] - [return: NullAllowed] - SKTileSet FromName (string name); + [Export ("tileGroups", ArgumentSemantic.Copy)] + SKTileGroup [] TileGroups { get; set; } - [Static] - [Export ("tileSetFromURL:")] - [return: NullAllowed] - SKTileSet FromUrl (NSUrl url); + [NullAllowed, Export ("name")] + string Name { get; set; } - [Export ("tileGroups", ArgumentSemantic.Copy)] - SKTileGroup [] TileGroups { get; set; } + [Export ("type", ArgumentSemantic.Assign)] + SKTileSetType Type { get; set; } - [NullAllowed, Export ("name")] - string Name { get; set; } + [NullAllowed, Export ("defaultTileGroup", ArgumentSemantic.Assign)] + SKTileGroup DefaultTileGroup { get; set; } - [Export ("type", ArgumentSemantic.Assign)] - SKTileSetType Type { get; set; } + [Export ("defaultTileSize", ArgumentSemantic.Assign)] + CGSize DefaultTileSize { get; set; } +} - [NullAllowed, Export ("defaultTileGroup", ArgumentSemantic.Assign)] - SKTileGroup DefaultTileGroup { get; set; } +/// +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKTileGroup : NSCopying, NSSecureCoding { + [Static] + [Export ("tileGroupWithTileDefinition:")] + SKTileGroup Create (SKTileDefinition tileDefinition); - [Export ("defaultTileSize", ArgumentSemantic.Assign)] - CGSize DefaultTileSize { get; set; } - } + [Static] + [Export ("tileGroupWithRules:")] + SKTileGroup Create (SKTileGroupRule [] rules); - /// - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKTileGroup : NSCopying, NSSecureCoding { - [Static] - [Export ("tileGroupWithTileDefinition:")] - SKTileGroup Create (SKTileDefinition tileDefinition); + [Static] + [Export ("emptyTileGroup")] + SKTileGroup CreateEmpty (); - [Static] - [Export ("tileGroupWithRules:")] - SKTileGroup Create (SKTileGroupRule [] rules); + [Export ("initWithTileDefinition:")] + NativeHandle Constructor (SKTileDefinition tileDefinition); - [Static] - [Export ("emptyTileGroup")] - SKTileGroup CreateEmpty (); + [Export ("initWithRules:")] + NativeHandle Constructor (SKTileGroupRule [] rules); - [Export ("initWithTileDefinition:")] - NativeHandle Constructor (SKTileDefinition tileDefinition); + [Export ("rules", ArgumentSemantic.Copy)] + SKTileGroupRule [] Rules { get; set; } - [Export ("initWithRules:")] - NativeHandle Constructor (SKTileGroupRule [] rules); + [NullAllowed, Export ("name")] + string Name { get; set; } +} - [Export ("rules", ArgumentSemantic.Copy)] - SKTileGroupRule [] Rules { get; set; } +/// Defines adjacency rules for tiles in an . +/// +/// Apple documentation for SKTileGroupRule +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKTileGroupRule : NSCopying, NSSecureCoding { + [Static] + [Export ("tileGroupRuleWithAdjacency:tileDefinitions:")] + SKTileGroupRule Create (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); - [NullAllowed, Export ("name")] - string Name { get; set; } - } + [Export ("initWithAdjacency:tileDefinitions:")] + NativeHandle Constructor (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); - /// Defines adjacency rules for tiles in an . - /// - /// Apple documentation for SKTileGroupRule - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKTileGroupRule : NSCopying, NSSecureCoding { - [Static] - [Export ("tileGroupRuleWithAdjacency:tileDefinitions:")] - SKTileGroupRule Create (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); + [Export ("adjacency", ArgumentSemantic.Assign)] + SKTileAdjacencyMask Adjacency { get; set; } - [Export ("initWithAdjacency:tileDefinitions:")] - NativeHandle Constructor (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); + [Export ("tileDefinitions", ArgumentSemantic.Copy)] + SKTileDefinition [] TileDefinitions { get; set; } - [Export ("adjacency", ArgumentSemantic.Assign)] - SKTileAdjacencyMask Adjacency { get; set; } + [NullAllowed, Export ("name")] + string Name { get; set; } +} - [Export ("tileDefinitions", ArgumentSemantic.Copy)] - SKTileDefinition [] TileDefinitions { get; set; } +/// Defines geometry deformation on objects. +/// +/// Apple documentation for SKWarpGeometry +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +interface SKWarpGeometry : NSCopying, NSSecureCoding { } + +/// Associates a and subdivision levels with an implementation. +[MacCatalyst (13, 1)] +[Protocol] +interface SKWarpable { + [Abstract] + [NullAllowed, Export ("warpGeometry", ArgumentSemantic.Assign)] + SKWarpGeometry WarpGeometry { get; set; } + + [Abstract] + [Export ("subdivisionLevels")] + nint SubdivisionLevels { get; set; } +} - [NullAllowed, Export ("name")] - string Name { get; set; } - } +/// A subclass that defines a warpable grid. +/// +/// Apple documentation for SKWarpGeometryGrid +[MacCatalyst (13, 1)] +[BaseType (typeof (SKWarpGeometry))] +[DisableDefaultCtor] +interface SKWarpGeometryGrid : NSSecureCoding { + [Static] + [Export ("grid")] + SKWarpGeometryGrid GetGrid (); - /// Defines geometry deformation on objects. - /// - /// Apple documentation for SKWarpGeometry - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - interface SKWarpGeometry : NSCopying, NSSecureCoding { } + [Static] + [Export ("gridWithColumns:rows:")] + SKWarpGeometryGrid Create (nint cols, nint rows); - /// Associates a and subdivision levels with an implementation. - [MacCatalyst (13, 1)] - [Protocol] - interface SKWarpable { - [Abstract] - [NullAllowed, Export ("warpGeometry", ArgumentSemantic.Assign)] - SKWarpGeometry WarpGeometry { get; set; } + [Internal] + [Static] + [Export ("gridWithColumns:rows:sourcePositions:destPositions:")] + SKWarpGeometryGrid GridWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - [Abstract] - [Export ("subdivisionLevels")] - nint SubdivisionLevels { get; set; } - } + [Internal] + [DesignatedInitializer] + [Export ("initWithColumns:rows:sourcePositions:destPositions:")] + IntPtr InitWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - /// A subclass that defines a warpable grid. - /// - /// Apple documentation for SKWarpGeometryGrid - [MacCatalyst (13, 1)] - [BaseType (typeof (SKWarpGeometry))] - [DisableDefaultCtor] - interface SKWarpGeometryGrid : NSSecureCoding { - [Static] - [Export ("grid")] - SKWarpGeometryGrid GetGrid (); + [Export ("numberOfColumns")] + nint NumberOfColumns { get; } - [Static] - [Export ("gridWithColumns:rows:")] - SKWarpGeometryGrid Create (nint cols, nint rows); + [Export ("numberOfRows")] + nint NumberOfRows { get; } - [Internal] - [Static] - [Export ("gridWithColumns:rows:sourcePositions:destPositions:")] - SKWarpGeometryGrid GridWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); + [Export ("vertexCount")] + nint VertexCount { get; } - [Internal] - [DesignatedInitializer] - [Export ("initWithColumns:rows:sourcePositions:destPositions:")] - IntPtr InitWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); + [Export ("sourcePositionAtIndex:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector2 GetSourcePosition (nint index); - [Export ("numberOfColumns")] - nint NumberOfColumns { get; } + [Export ("destPositionAtIndex:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector2 GetDestPosition (nint index); - [Export ("numberOfRows")] - nint NumberOfRows { get; } + [Internal] + [Export ("gridByReplacingSourcePositions:")] + SKWarpGeometryGrid _GridByReplacingSourcePositions (IntPtr sourcePositions); - [Export ("vertexCount")] - nint VertexCount { get; } + [Internal] + [Export ("gridByReplacingDestPositions:")] + SKWarpGeometryGrid _GridByReplacingDestPositions (IntPtr destPositions); +} - [Export ("sourcePositionAtIndex:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector2 GetSourcePosition (nint index); +// SKRenderer is not available for WatchKit apps and the iOS simulator +/// The class used to render SpriteKit. +[MacCatalyst (13, 1)] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface SKRenderer { + [Static] + [Export ("rendererWithDevice:")] + SKRenderer FromDevice (IMTLDevice device); - [Export ("destPositionAtIndex:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector2 GetDestPosition (nint index); + [Export ("renderWithViewport:commandBuffer:renderPassDescriptor:")] + void Render (CGRect viewport, IMTLCommandBuffer commandBuffer, MTLRenderPassDescriptor renderPassDescriptor); - [Internal] - [Export ("gridByReplacingSourcePositions:")] - SKWarpGeometryGrid _GridByReplacingSourcePositions (IntPtr sourcePositions); + [Export ("renderWithViewport:renderCommandEncoder:renderPassDescriptor:commandQueue:")] + void Render (CGRect viewport, IMTLRenderCommandEncoder renderCommandEncoder, MTLRenderPassDescriptor renderPassDescriptor, IMTLCommandQueue commandQueue); - [Internal] - [Export ("gridByReplacingDestPositions:")] - SKWarpGeometryGrid _GridByReplacingDestPositions (IntPtr destPositions); - } + [Export ("updateAtTime:")] + void Update (double currentTime); - // SKRenderer is not available for WatchKit apps and the iOS simulator - /// The class used to render SpriteKit. - [MacCatalyst (13, 1)] - [BaseType (typeof (NSObject))] - [DisableDefaultCtor] - interface SKRenderer { - [Static] - [Export ("rendererWithDevice:")] - SKRenderer FromDevice (IMTLDevice device); + [NullAllowed, Export ("scene", ArgumentSemantic.Assign)] + SKScene Scene { get; set; } - [Export ("renderWithViewport:commandBuffer:renderPassDescriptor:")] - void Render (CGRect viewport, IMTLCommandBuffer commandBuffer, MTLRenderPassDescriptor renderPassDescriptor); + [Export ("ignoresSiblingOrder")] + bool IgnoresSiblingOrder { get; set; } - [Export ("renderWithViewport:renderCommandEncoder:renderPassDescriptor:commandQueue:")] - void Render (CGRect viewport, IMTLRenderCommandEncoder renderCommandEncoder, MTLRenderPassDescriptor renderPassDescriptor, IMTLCommandQueue commandQueue); + [Export ("shouldCullNonVisibleNodes")] + bool ShouldCullNonVisibleNodes { get; set; } - [Export ("updateAtTime:")] - void Update (double currentTime); + [Export ("showsDrawCount")] + bool ShowsDrawCount { get; set; } - [NullAllowed, Export ("scene", ArgumentSemantic.Assign)] - SKScene Scene { get; set; } + [Export ("showsNodeCount")] + bool ShowsNodeCount { get; set; } - [Export ("ignoresSiblingOrder")] - bool IgnoresSiblingOrder { get; set; } + [Export ("showsQuadCount")] + bool ShowsQuadCount { get; set; } - [Export ("shouldCullNonVisibleNodes")] - bool ShouldCullNonVisibleNodes { get; set; } + [Export ("showsPhysics")] + bool ShowsPhysics { get; set; } - [Export ("showsDrawCount")] - bool ShowsDrawCount { get; set; } + [Export ("showsFields")] + bool ShowsFields { get; set; } +} - [Export ("showsNodeCount")] - bool ShowsNodeCount { get; set; } +/// A that holds a geometric transform. +[MacCatalyst (13, 1)] +[BaseType (typeof (SKNode))] +interface SKTransformNode { + [Export ("xRotation")] + nfloat XRotation { get; set; } - [Export ("showsQuadCount")] - bool ShowsQuadCount { get; set; } + [Export ("yRotation")] + nfloat YRotation { get; set; } - [Export ("showsPhysics")] - bool ShowsPhysics { get; set; } + [Export ("eulerAngles")] + VectorFloat3 EulerAngles { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } - [Export ("showsFields")] - bool ShowsFields { get; set; } + [Export ("rotationMatrix")] + MatrixFloat3x3 RotationMatrix { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; } - /// A that holds a geometric transform. - [MacCatalyst (13, 1)] - [BaseType (typeof (SKNode))] - interface SKTransformNode { - [Export ("xRotation")] - nfloat XRotation { get; set; } - - [Export ("yRotation")] - nfloat YRotation { get; set; } - - [Export ("eulerAngles")] - VectorFloat3 EulerAngles { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Export ("rotationMatrix")] - MatrixFloat3x3 RotationMatrix { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Export ("quaternion")] - Quaternion Quaternion { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [Export ("quaternion")] + Quaternion Quaternion { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; } } +} From d7e9108efa0e1e4b0bbd0f8046f19a3b4a23ac5d Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Mon, 10 Feb 2025 17:35:50 +0100 Subject: [PATCH 3/5] Back to main. --- .github/workflows/sdk-insertion-bump.yml | 30 - Directory.Build.props | 4 + dotnet/Workloads/SignList.xml | 5 +- eng/Version.Details.xml | 4 +- eng/Versions.props | 2 +- mk/xamarin.mk | 2 +- msbuild/Directory.Build.props | 2 +- msbuild/Makefile | 2 +- .../Xamarin.Messaging.Build.csproj | 4 + .../MSBStrings.resx | 5 + msbuild/Xamarin.MacDev.Tasks/Decompress.cs | 12 + .../Tasks/FilterStaticFrameworks.cs | 2 +- .../Tasks/PackLibraryResources.cs | 7 + .../Xamarin.MacDev.Tasks.csproj | 4 + .../Xamarin.iOS.Tasks.Windows.csproj | 3 +- scripts/rsp-to-csproj/rsp-to-csproj.cs | 4 + .../AVAssetDownloadStorageManagementPolicy.cs | 2 +- src/AVFoundation/AVCaptureMetadataOutput.cs | 4 +- .../AVMetadataMachineReadableCodeObject.cs | 4 +- src/AVFoundation/AVOutputSettingsAssistant.cs | 6 +- src/AVRouting/AVCustomDeviceRoute.cs | 2 +- src/Accessibility/AXSettings.cs | 2 +- src/AddressBook/ABAddressBook.cs | 2 +- src/AppKit/Enums.cs | 16 - src/AppKit/Functions.cs | 4 +- src/AppKit/NSGraphics.cs | 4 +- src/AppKit/NSPasteboardReading.cs | 2 +- src/AudioToolbox/AudioConverter.cs | 4 +- src/AudioToolbox/AudioFile.cs | 2 +- src/AudioToolbox/AudioFileStream.cs | 2 +- src/AudioToolbox/AudioQueue.cs | 10 +- src/AudioToolbox/MusicTrack.cs | 2 +- src/AudioToolbox/SystemSound.cs | 2 +- src/AudioUnit/AUEnums.cs | 60 +- src/AudioUnit/AUGraph.cs | 8 +- src/AudioUnit/AudioComponent.cs | 21 +- src/AudioUnit/AudioComponentDescription.cs | 38 +- src/AudioUnit/AudioUnit.cs | 9 +- src/AudioUnit/AudioUnitUtils.cs | 8 +- src/AudioUnit/ExtAudioFile.cs | 8 +- src/BrowserEngineKit/BEStructs.cs | 19 +- src/Compression/CompressionStreamStruct.cs | 8 +- src/Compression/TaskToApm.cs | 180 +- src/CoreAnimation/CATextLayer.cs | 2 +- src/CoreAnimation/CATransform3D.cs | 8 +- src/CoreBluetooth/CBPeer.cs | 2 +- src/CoreFoundation/CFMessagePort.cs | 12 +- src/CoreFoundation/CFProxySupport.cs | 4 +- src/CoreGraphics/CGAffineTransform.cs | 22 +- src/CoreGraphics/CGColorSpace.cs | 2 +- src/CoreGraphics/CGDisplay.cs | 45 +- src/CoreGraphics/CGEvent.cs | 58 +- src/CoreGraphics/CGEventSource.cs | 22 +- src/CoreGraphics/CGEventTypes.cs | 50 +- src/CoreGraphics/CGImage.cs | 22 +- src/CoreGraphics/CGPattern.cs | 3 +- src/CoreGraphics/CGVector.cs | 4 +- src/CoreImage/Enums.cs | 2 +- src/CoreLocation/CLLocationManager.cs | 2 +- src/CoreMedia/CMSampleBuffer.cs | 4 +- src/CoreMidi/MidiBluetoothDriver.cs | 8 +- src/CoreServices/FSEvents.cs | 34 +- src/CoreServices/LaunchServices.cs | 41 +- src/CoreSpotlight/CSSearchableIndex.cs | 2 +- .../CSSearchableItemAttributeSet.cs | 13 +- src/CoreText/CTFontCollection.cs | 2 +- src/CoreText/CTFontManager.cs | 8 +- src/CoreVideo/CVDisplayLink.cs | 56 +- src/CoreVideo/CVImageBuffer.cs | 2 +- src/CoreVideo/CVPixelFormatDescription.cs | 2 +- src/Darwin/KernelNotification.cs | 146 +- src/Darwin/SystemLog.cs | 60 +- src/FileProvider/Structs.cs | 5 +- src/Foundation/Compat.cs | 26 +- src/Foundation/DictionaryContainer.cs | 10 - src/Foundation/Enum.cs | 34 +- src/Foundation/LinkerSafeAttribute.cs | 2 - src/Foundation/ModelAttribute.cs | 3 - src/Foundation/MonoTouchException.cs | 72 - src/Foundation/NSAppleEventDescriptor.cs | 6 +- src/Foundation/NSArray.cs | 14 - src/Foundation/NSArray_1.cs | 20 - src/Foundation/NSAttributedString.cs | 10 +- src/Foundation/NSAttributedString.mac.cs | 10 +- src/Foundation/NSConnection.cs | 8 +- src/Foundation/NSHost.cs | 8 +- src/Foundation/NSIndexSet.cs | 38 +- src/Foundation/NSNumber.mac.cs | 28 +- src/Foundation/NSObject.mac.cs | 2 +- src/Foundation/NSObject2.cs | 144 +- src/Foundation/NSPropertyListSerialization.cs | 6 +- .../NSScriptCommandArgumentDescription.cs | 8 +- src/Foundation/NSScriptCommandDescription.cs | 16 +- .../NSScriptCommandDescriptionDictionary.cs | 20 +- src/Foundation/NSSecureCoding.cs | 3 +- src/Foundation/NSString.cs | 6 +- src/Foundation/NSThread.mac.cs | 13 +- src/Foundation/NSUrlDownload.cs | 2 +- src/Foundation/NSUrlSessionHandler.cs | 58 +- src/GameKit/GKCompat.cs | 5 +- src/ImageIO/CGImageAnimation.cs | 40 +- .../INSetClimateSettingsInCarIntent.cs | 2 +- src/Makefile | 2 +- src/MapKit/MapKit.cs | 2 +- src/MediaExtension/MEByteSource.cs | 8 +- .../MERawProcessingListParameter.cs | 2 +- src/MediaExtension/MESampleCursor.cs | 2 +- src/MediaToolbox/MTAudioProcessingTap.cs | 64 +- src/Metal/Defs.cs | 3 +- src/Metal/MTLArgumentEncoder.cs | 4 +- src/Metal/MTLArrays.cs | 3 +- src/Metal/MTLComputeCommandEncoder.cs | 4 +- .../MTLRasterizationRateLayerDescriptor.cs | 17 +- src/Metal/MTLResourceStateCommandEncoder.cs | 10 +- .../MPSGraphExecutable.cs | 8 +- src/MetricKit/MXMetaData.cs | 2 +- src/MetricKit/MXMetric.cs | 2 +- src/MetricKit/MXMetricPayload.cs | 2 +- ...IAlgorithmConvergenceStatusReasonValues.cs | 3 +- src/NearbyInteraction/NINearbyObject.cs | 15 +- src/Network/NWConnection.cs | 2 +- src/Network/NWConnectionGroup.cs | 2 +- src/Network/NWEndpoint.cs | 2 +- src/Network/NWEstablishmentReport.cs | 2 +- src/Network/NWEthernetChannel.cs | 22 +- src/Network/NWInterface.cs | 2 +- src/Network/NWParameters.cs | 4 +- src/Network/NWPath.cs | 2 +- src/Network/NWPrivacyContext.cs | 2 +- src/Network/NWProtocolDefinition.cs | 2 +- src/Network/NWProtocolFramerOptions.cs | 2 +- src/Network/NWProtocolMetadata.cs | 2 +- src/Network/NWProtocolOptions.cs | 2 +- src/Network/NWProtocolStack.cs | 2 +- src/Network/NWProxyConfig.cs | 2 +- src/Network/NWRelayHop.cs | 2 +- src/Network/NWResolverConfig.cs | 2 +- src/ObjCBindings/BindFromAttribute.cs | 35 + src/ObjCBindings/BindingTypeAttribute.cs | 45 + src/ObjCBindings/BindingTypeTag.cs | 27 + src/ObjCBindings/ExportAttribute.cs | 39 + src/ObjCBindings/ExportTag.cs | 96 + src/ObjCRuntime/BackingField.cs | 3 +- src/ObjCRuntime/BindAs.cs | 12 +- src/ObjCRuntime/Blocks.cs | 12 +- src/ObjCRuntime/Class.cs | 2 +- .../DelayedRegistrationAttribute.cs | 3 +- src/ObjCRuntime/Dlfcn.cs | 3 +- src/ObjCRuntime/INativeObject.cs | 2 +- src/ObjCRuntime/NativeHandle.cs | 4 +- src/ObjCRuntime/PlatformAvailability.cs | 2 +- src/ObjCRuntime/RegistrarHelper.cs | 24 +- src/ObjCRuntime/RequiredFrameworkAttribute.cs | 7 +- src/ObjCRuntime/Runtime.CoreCLR.cs | 52 +- src/ObjCRuntime/Runtime.cs | 31 +- src/ObjCRuntime/Runtime.mac.cs | 4 +- src/ObjCRuntime/Stret.cs | 11 +- src/PassKit/PKCompat.cs | 5 +- src/PdfKit/Enums.cs | 100 +- src/PhotosUI/PHEnums.cs | 4 +- src/QuickLook/Thumbnail.cs | 6 +- src/SceneKit/Defs.cs | 18 +- src/SceneKit/SCNMatrix4_dotnet.cs | 180 +- src/SceneKit/SCNQuaternion.cs | 18 +- src/SceneKit/SCNVector3.cs | 88 +- src/SceneKit/SCNVector4.cs | 50 +- src/Security/Authorization.cs | 80 +- src/Security/Enums.cs | 4 +- src/Security/Items.cs | 130 +- src/Security/SecCertificate2.cs | 2 +- src/Security/SecIdentity2.cs | 2 +- src/Security/SecSharedCredential.cs | 26 +- src/Security/SecTrust2.cs | 2 +- src/Simd/MathHelper.cs | 3 +- src/Simd/MatrixFloat3x3RM.cs | 32 +- src/Simd/MatrixFloat4x3.cs | 2 +- src/Simd/QuaternionDouble.cs | 13 +- src/Simd/VectorDouble2.cs | 8 +- src/Simd/VectorDouble4.cs | 11 +- src/Simd/VectorInt2.cs | 8 +- src/Simd/VectorInt3.cs | 8 +- src/Simd/VectorInt4.cs | 8 +- src/StoreKit/SKOverlayAppClipConfiguration.cs | 7 +- src/StoreKit/SKOverlayAppConfiguration.cs | 7 +- src/System.Net.Http/CFNetworkHandler.cs | 2 +- src/UIKit/NSLayoutManager.cs | 2 +- src/UIKit/UIActionSheet.cs | 10 +- src/UIKit/UIAppearance.cs | 4 +- src/UIKit/UIButton.cs | 2 +- src/UIKit/UIDevice.cs | 2 +- src/UIKit/UIDocumentBrowserViewController.cs | 6 +- src/UIKit/UIImage.cs | 6 +- src/UIKit/UINavigationBar.cs | 4 +- src/UIKit/UIPasteboard.cs | 14 +- src/UIKit/UIPickerView.cs | 2 +- src/UIKit/UIPopoverPresentationController.cs | 2 +- src/UIKit/UIStringDrawing.cs | 2 +- src/UIKit/UITextAttributes.cs | 18 +- src/UIKit/UIToolbar.cs | 8 +- src/UIKit/UIVideo.cs | 12 +- src/VideoToolbox/VTCompressionSession.cs | 2 +- src/VideoToolbox/VTDecompressionSession.cs | 6 +- src/VideoToolbox/VTRawProcessingSession.cs | 4 +- src/accessorysetupkit.cs | 54 +- src/appkit.cs | 4 +- src/authenticationservices.cs | 9 +- src/avfoundation.cs | 10 +- src/backgroundassets.cs | 3 +- src/browserenginekit.cs | 297 +- src/contactsui.cs | 9 +- src/coreanimation.cs | 5 +- src/coredata.cs | 14 +- src/corehaptics.cs | 2 +- src/coreimage.cs | 6 +- src/corelocation.cs | 4 +- src/corenfc.cs | 8 +- src/coretext.cs | 9 +- src/cryptotokenkit.cs | 249 +- src/eventkit.cs | 2 +- src/foundation.cs | 29 +- src/frameworks.sources | 2 +- src/gamekit.cs | 16 +- src/healthkit.cs | 2 +- src/mapkit.cs | 10 +- src/mediaextension.cs | 225 +- src/mediaplayer.cs | 6 +- src/metal.cs | 2 +- src/metrickit.cs | 2 +- src/networkextension.cs | 4 +- src/quicklook.cs | 6 +- src/rgen/.gitignore | 1 + .../Microsoft.Macios.Bindings.Analyzer.csproj | 29 +- .../Attributes/BindFromData.cs | 98 + .../Attributes/BindingTypeData.cs | 46 +- .../Attributes/ExportData.cs | 86 +- .../Attributes/FieldData.cs | 2 +- .../Attributes/MarshalDirective.cs | 37 + .../Attributes/SupportedOSPlatformData.cs | 6 + .../Attributes/UnsupportedOSPlatformData.cs | 6 + .../AttributesNames.cs | 4 + .../Availability/AvailabilityTrivia.cs | 59 + .../Availability/PlatformAvailability.cs | 18 +- .../Availability/SymbolAvailability.cs | 13 + .../Availability/SymbolAvailabilityBuilder.cs | 12 + .../BindingSourceGeneratorGenerator.cs | 51 +- .../Context/BindingContext.cs | 5 +- .../{RootBindingContext.cs => RootContext.cs} | 25 +- .../DataModel/Accessor.Generator.cs | 92 + .../DataModel/Accessor.cs | 44 +- .../DataModel/AttributeCodeChange.cs | 1 + .../{CodeChanges.cs => Binding.Generator.cs} | 202 +- .../DataModel/Binding.cs | 187 + ...Comparer.cs => BindingEqualityComparer.cs} | 6 +- .../DataModel/BindingInfo.cs | 15 + .../DataModel/BindingType.cs | 13 +- .../DataModel/Constructor.Generator.cs | 41 + .../DataModel/Constructor.cs | 35 +- .../DataModel/EnumMember.Generator.cs | 57 + .../DataModel/EnumMember.cs | 51 +- .../DataModel/Event.Generator.cs | 51 + .../DataModel/Event.cs | 43 +- .../DataModel/Method.Generator.cs | 104 + .../DataModel/Method.cs | 73 +- .../DataModel/Parameter.Generator.cs | 86 + .../DataModel/Parameter.cs | 79 +- .../DataModel/ParameterComparer.cs | 7 +- .../DataModel/Property.Generator.cs | 245 + .../DataModel/Property.cs | 159 +- .../DataModel/TypeInfo.Generator.cs | 71 + .../DataModel/TypeInfo.cs | 162 +- .../DataModel/TypeInfoComparer.cs | 2 +- .../Emitters/BindingSyntaxFactory.Dlfcn.cs | 516 +- .../BindingSyntaxFactory.ObjCRuntime.cs | 766 +++ .../Emitters/BindingSyntaxFactory.cs | 56 +- .../Emitters/CategoryEmitter.cs | 2 +- .../Emitters/ClassEmitter.cs | 130 +- .../Emitters/EmitterFactory.cs | 2 +- .../Emitters/EnumEmitter.cs | 100 +- .../Emitters/ICodeEmitter.cs | 2 +- .../Emitters/InterfaceEmitter.cs | 2 +- .../Emitters/LibraryEmitter.cs | 23 +- .../Emitters/TrampolineEmitter.cs | 2 +- .../Extensions/ApplePlatformExtensions.cs | 22 + .../Extensions/CompilationExtensions.cs | 60 +- .../Extensions/Delegates.cs | 19 + .../Extensions/EnumExtensions.cs | 29 + .../FieldSymbolExtensions.Generator.cs | 19 + .../Extensions/FieldSymbolExtensions.cs | 23 +- .../SemanticModelExtensions.Generator.cs | 38 + .../Extensions/SemanticModelExtensions.cs | 37 +- .../Extensions/SpecialTypeExtensions.cs | 44 + .../Extensions/TypeSymbolExtensions.Core.cs | 479 ++ .../TypeSymbolExtensions.Generator.cs | 234 + .../Extensions/TypeSymbolExtensions.cs | 363 -- .../Formatters/ParameterFormatter.cs | 12 +- .../Formatters/PropertyFormatter.cs | 20 +- .../Formatters/SmartEnumFormatter.cs | 4 +- .../Formatters/TypeInfoFormatter.cs | 2 +- .../IO/TabbedStringBuilder.Generator.cs | 22 + .../IO/TabbedStringBuilder.cs | 75 + .../IO/TabbedStringBuilderAvailability.cs | 57 + .../IO/TabbedStringBuilderExtensions.cs | 84 + .../IO/TabbedWriter.cs | 341 ++ .../Microsoft.Macios.Generator.csproj | 3 + .../TabbedStringBuilder.cs | 315 - .../AttributeType.cs | 10 + .../Attributes/BindingAttributeData.cs | 84 + .../Attributes/BindingFlagData.cs | 50 + ...rosoft.Macios.Transformer.Generator.csproj | 38 + .../Properties/launchSettings.json | 9 + .../XamarinBindingAPIGenerator.cs | 361 ++ .../Attributes/AsyncData.cs | 120 + .../Attributes/BackingFieldTypeData.cs | 54 + .../Attributes/BaseTypeData.cs | 142 + .../Attributes/BindAsData.cs | 66 + .../Attributes/BindData.cs | 59 + .../Attributes/CoreImageFilterData.cs | 59 + .../Attributes/CoreImageFilterPropertyData.cs | 53 + .../Attributes/ErrorDomainData.cs | 69 + .../Attributes/ExportData.cs | 84 + .../Attributes/FieldData.cs | 62 + .../Attributes/NativeData.cs | 59 + .../Attributes/NotificationData.cs | 97 + .../Attributes/SnippetData.cs | 67 + .../Attributes/StrongDictionaryData.cs | 63 + .../Attributes/ThreadSafeData.cs | 43 + .../Attributes/XamarinAvailabilityData.cs | 82 + .../AttributesNames.cs | 346 ++ .../CompilationResult.cs | 20 + .../DataModel/Accessor.Transformer.cs | 50 + .../DataModel/Binding.Transformer.cs | 90 + .../DataModel/BindingInfo.cs | 22 + .../DataModel/Constructor.Transformer.cs | 44 + .../DataModel/EnumMember.Transformer.cs | 40 + .../DataModel/FieldInfo.cs | 31 + .../DataModel/Method.Transformer.cs | 99 + .../DataModel/ModifiersFlags.cs | 109 + .../DataModel/Parameter.Transformer.cs | 43 + .../DataModel/Property.Transformer.cs | 157 + .../DataModel/TypeInfo.Transformer.cs | 47 + .../CSharpCommandLineArgumentsExtensions.cs | 38 + .../CSharpCommandLineParserExtensions.cs | 32 + .../FieldSymbolExtensions.Transformer.cs | 19 + .../TypeSymbolExtensions.Transformer.cs | 100 + .../IO/TabbedStreamWriter.cs | 70 + src/rgen/Microsoft.Macios.Transformer/Main.cs | 194 +- .../Microsoft.Macios.Transformer.csproj | 107 +- .../Microsoft.Macios.Transformer.sln | 24 + .../TransformCommand.cs | 40 - .../Transformer.cs | 281 + .../Microsoft.Macios.Transformer/Verbosity.cs | 13 + .../Workers/CategoryTransformer.cs | 40 + .../Workers/ClassTransformer.cs | 38 + .../Workers/CopyTransformer.cs | 39 + .../Workers/ErrorDomainTransformer.cs | 40 + .../Workers/ITransformer.cs | 12 + .../Workers/ProtocolTransformer.cs | 38 + .../Workers/SmartEnumTransformer.cs | 39 + .../Workers/StrongDictionaryTransformer.cs | 38 + src/rgen/rgen.sln | 9 +- src/scenekit.cs | 2 +- src/sharedwithyou.cs | 12 +- src/soundanalysis.cs | 2 +- src/spritekit.cs | 5240 ++++++++--------- src/storekit.cs | 18 +- src/tvmlkit.cs | 9 +- src/uikit.cs | 4 +- src/webkit.cs | 6 +- src/xkit.cs | 76 +- tests/BundledResources/ResourcesTest.cs | 13 +- .../Documentation.KnownFailures.txt | 1 - tests/common/Configuration.cs | 96 +- tests/common/MonoTouch.Dialog/Reflect.cs | 471 -- tests/dotnet/UnitTests/ProjectTest.cs | 21 +- .../Xamarin.MacDev.Tasks.Tests.csproj | 4 + .../Attributes/ExportDataTests.cs | 18 +- .../Attributes/FieldDataTests.cs | 4 +- .../Availability/AvailabilityTriviaTests.cs | 89 + .../BaseGeneratorTestClass.cs | 30 +- .../Classes/ClassGenerationTests.cs | 3 + .../Classes/Data/CIImage.cs | 39 + .../Classes/Data/ExpectedCIImage.cs | 131 + ...ingContextTests.cs => RootContextTests.cs} | 6 +- .../DataModel/AccessorTests.cs | 204 + ...mparerTests.cs => BindingComparerTests.cs} | 133 +- ...sts.cs => BindingEqualityComparerTests.cs} | 75 +- .../{CodeChangesTests.cs => BindingTests.cs} | 8 +- ...deChangesTests.cs => ClassBindingTests.cs} | 187 +- .../DataModel/ConstructorComparerTests.cs | 19 +- .../DataModel/ConstructorTests.cs | 83 +- .../ConstructorsEqualityComparerTests.cs | 27 +- .../DataModel/CoreImageFilterTests.cs | 8 + .../DataModel/DelegateInfoTests.cs | 36 +- .../EnumDeclarationCodeChangesTests.cs | 4 +- .../DataModel/EnumMemberCodeChangesTests.cs | 6 +- .../DataModel/EventTests.cs | 4 +- .../DataModel/InterfaceCodeChangesTests.cs | 158 +- .../DataModel/MethodComparerTests.cs | 19 +- .../DataModel/MethodEqualityComparerTests.cs | 67 +- .../DataModel/MethodTests.cs | 153 +- .../DataModel/ParameterTests.cs | 88 + .../DataModel/PropertyTests.cs | 352 +- .../DataModel/TypeInfoComparerTests.cs | 2 +- .../DataModel/TypeInfoTests.cs | 61 + .../DataModel/TypeInfoToMarshallTypeTests.cs | 212 + ...BindingSyntaxFactoryFieldAccessorsTests.cs | 1695 ++++++ ...SyntaxFactoryFieldBackingVariableTests.cs} | 416 +- .../BindingSyntaxFactoryObjCRuntimeTests.cs | 665 +++ .../Emitters/EmitterFactoryTests.cs | 4 +- .../GetObjCMessageSendMethodNameTests.cs | 380 ++ .../Extensions/CompilationExtensionsTest.cs | 76 + .../Extensions/EnumExtensionTests.cs | 27 + .../TypeSymbolExtensionsInheritanceTests.cs | 102 +- .../TypeSymbolExtensionsSizeTests.cs | 493 ++ .../Extensions/TypeSymbolExtensionsTests.cs | 183 +- .../Formatters/SmartEnumFormatterTests.cs | 2 +- .../{ => IO}/TabbedStringBuilderTests.cs | 186 +- .../Microsoft.Macios.Generator.Tests.csproj | 16 + .../TestDataFactory.cs | 273 +- .../Attributes/AsyncDataTests.cs | 149 + .../Attributes/AttributeParsingTestClass.cs | 47 + .../Attributes/AvailabilityTests.cs | 147 + .../Attributes/BackingFieldTypeDataTests.cs | 76 + .../Attributes/BaseTypeDataTests.cs | 175 + .../Attributes/BindAsDataTests.cs | 131 + .../Attributes/BindDataTests.cs | 72 + .../Attributes/CoreImageFilterDataTests.cs | 97 + .../CoreImageFilterPropertyTests.cs | 51 + .../Attributes/ErrorDomainDataTests.cs | 72 + .../Attributes/ExportDataTests.cs | 73 + .../Attributes/FieldDataTests.cs | 91 + .../Attributes/NativeDataTests.cs | 82 + .../Attributes/NotificationDataTests.cs | 112 + .../Attributes/SnippetDataTests.cs | 45 + .../Attributes/StrongDictionaryDataTests.cs | 48 + .../Attributes/ThreadSafeDataTests.cs | 75 + .../BaseTransformerTestClass.cs | 65 + .../DataModel/MethodTests.cs | 495 ++ .../DataModel/ParameterTests.cs | 339 ++ .../DataModel/PropertyTests.cs | 319 + .../DataModel/SmartEnumTests.cs | 163 + .../Extensions/TypeSymbolExtensionsTests.cs | 98 + .../IO/TabbedStreamWriterTests.cs | 121 + .../Microsoft.Macios.Transformer.Tests.csproj | 128 +- .../SyntaxTreeExtensions.cs | 12 + .../TransformerTests.cs | 266 + .../UnitTest1.cs | 11 - tests/xharness/Harness.cs | 8 +- tools/devops/automation/build-cronjob.yml | 6 - tools/devops/automation/build-lego.yml | 6 - tools/devops/automation/build-pipeline.yml | 13 +- .../devops/automation/build-pull-request.yml | 12 +- .../automation/publish-pr-html-results.yml | 6 - .../run-post-ci-build-vs-insertion.yml | 1 - tools/devops/automation/scripts/GitHub.psm1 | 6 + .../templates/pipelines/api-diff-pipeline.yml | 2 +- .../templates/pipelines/build-pipeline.yml | 8 +- .../pipelines/run-tests-pipeline.yml | 2 +- .../templates/release/vs-insertion-prep.yml | 1 + 459 files changed, 22914 insertions(+), 8023 deletions(-) delete mode 100644 .github/workflows/sdk-insertion-bump.yml delete mode 100644 src/Foundation/MonoTouchException.cs create mode 100644 src/ObjCBindings/BindFromAttribute.cs create mode 100644 src/rgen/.gitignore create mode 100644 src/rgen/Microsoft.Macios.Generator/Attributes/BindFromData.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Attributes/MarshalDirective.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Availability/AvailabilityTrivia.cs rename src/rgen/Microsoft.Macios.Generator/Context/{RootBindingContext.cs => RootContext.cs} (87%) create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.Generator.cs rename src/rgen/Microsoft.Macios.Generator/DataModel/{CodeChanges.cs => Binding.Generator.cs} (65%) create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs rename src/rgen/Microsoft.Macios.Generator/DataModel/{CodeChangesEqualityComparer.cs => BindingEqualityComparer.cs} (94%) create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/Event.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/ApplePlatformExtensions.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/Delegates.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/EnumExtensions.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/SpecialTypeExtensions.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Core.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Generator.cs delete mode 100644 src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.Generator.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderAvailability.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderExtensions.cs create mode 100644 src/rgen/Microsoft.Macios.Generator/IO/TabbedWriter.cs delete mode 100644 src/rgen/Microsoft.Macios.Generator/TabbedStringBuilder.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/AttributeType.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingAttributeData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingFlagData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj create mode 100644 src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Properties/launchSettings.json create mode 100644 src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/XamarinBindingAPIGenerator.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/AsyncData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/BackingFieldTypeData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/BaseTypeData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/BindAsData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/BindData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterPropertyData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/ErrorDomainData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/ExportData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/FieldData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/NativeData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/NotificationData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/SnippetData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/StrongDictionaryData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/ThreadSafeData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Attributes/XamarinAvailabilityData.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/CompilationResult.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/Accessor.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/BindingInfo.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/Constructor.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/EnumMember.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/FieldInfo.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/Parameter.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/TypeInfo.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineArgumentsExtensions.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineParserExtensions.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Extensions/FieldSymbolExtensions.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Extensions/TypeSymbolExtensions.Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/IO/TabbedStreamWriter.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.sln delete mode 100644 src/rgen/Microsoft.Macios.Transformer/TransformCommand.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Transformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Verbosity.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/CategoryTransformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/ClassTransformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/CopyTransformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/ErrorDomainTransformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/ITransformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/ProtocolTransformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/SmartEnumTransformer.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/Workers/StrongDictionaryTransformer.cs delete mode 100644 tests/common/MonoTouch.Dialog/Reflect.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Availability/AvailabilityTriviaTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/CIImage.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/ExpectedCIImage.cs rename tests/rgen/Microsoft.Macios.Generator.Tests/Context/{RootBindingContextTests.cs => RootContextTests.cs} (89%) rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{CodeChangesComparerTests.cs => BindingComparerTests.cs} (95%) rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{CodeChangesEqualityComparerTests.cs => BindingEqualityComparerTests.cs} (95%) rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{CodeChangesTests.cs => BindingTests.cs} (95%) rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{ClassCodeChangesTests.cs => ClassBindingTests.cs} (87%) create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CoreImageFilterTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ParameterTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoToMarshallTypeTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryFieldAccessorsTests.cs rename tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/{BindingSyntaxFactoryTests.cs => BindingSyntaxFactoryFieldBackingVariableTests.cs} (52%) create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/GetObjCMessageSendMethodNameTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/EnumExtensionTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsSizeTests.cs rename tests/rgen/Microsoft.Macios.Generator.Tests/{ => IO}/TabbedStringBuilderTests.cs (62%) create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AsyncDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AttributeParsingTestClass.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AvailabilityTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BackingFieldTypeDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BaseTypeDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindAsDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterPropertyTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ErrorDomainDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ExportDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/FieldDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NativeDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NotificationDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/SnippetDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/StrongDictionaryDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ThreadSafeDataTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/MethodTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/ParameterTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/PropertyTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/Extensions/TypeSymbolExtensionsTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/IO/TabbedStreamWriterTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/SyntaxTreeExtensions.cs create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/TransformerTests.cs delete mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/UnitTest1.cs diff --git a/.github/workflows/sdk-insertion-bump.yml b/.github/workflows/sdk-insertion-bump.yml deleted file mode 100644 index 3b1e7a4d50f6..000000000000 --- a/.github/workflows/sdk-insertion-bump.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Notify release branch change - -on: push - -jobs: - pingRemote: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - - name: Parse commit - shell: pwsh - id: commit_title - run: | - Write-Host "Commit message is $Env:COMMIT_MESSAGE" - $title = ($Env:COMMIT_MESSAGE -split '\n')[0] | ConvertTo-Json - "COMMIT_TITLE=$title" >> $env:GITHUB_OUTPUT - env: - COMMIT_MESSAGE: "${{ github.event.head_commit.message }}" - - - name: 'Update remote repository' - uses: peter-evans/repository-dispatch@v3 - with: - token: ${{ secrets.SERVICEACCOUNT_PAT }} - event-type: 'sdk_insertion' - repository: 'xamarin/sdk-insertions' - client-payload: '{"repository": "xamarin/xamarin-macios", "branch": "${{ github.ref_name }}", "commit": "${{ github.sha }}", "commit_message": ${{ steps.commit_title.outputs.COMMIT_TITLE }} }' - - diff --git a/Directory.Build.props b/Directory.Build.props index 345afdc19754..e735211586e1 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -9,6 +9,10 @@ $(MicrosoftBuildPackageVersion) $(MicrosoftBuildPackageVersion) 3.1.15 + + 4.7.2 + + 4.7.1 diff --git a/dotnet/Workloads/SignList.xml b/dotnet/Workloads/SignList.xml index 81d34b5fb630..211ecc98c11b 100644 --- a/dotnet/Workloads/SignList.xml +++ b/dotnet/Workloads/SignList.xml @@ -35,12 +35,13 @@ + + + - - diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index f0190241e7c3..73611fcc814f 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -95,9 +95,9 @@ https://github.com/dotnet/templating - + https://github.com/dotnet/xharness - 3119edb6d70fb252e6128b0c7e45d3fc2f49f249 + cf1b2925785f504d4d52773bcab470044e35ea15 https://github.com/dotnet/arcade diff --git a/eng/Versions.props b/eng/Versions.props index de3c31561594..9fb05e16f127 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -12,7 +12,7 @@ 9.0.0-rc.2.24462.10 7.0.100-alpha.1.21601.1 0.11.5-alpha.24515.1 - 10.0.0-prerelease.24610.1 + 10.0.0-prerelease.25103.1 9.0.0-beta.25058.5 $(MicrosoftNETWorkloadEmscriptenCurrentManifest80100Version) diff --git a/mk/xamarin.mk b/mk/xamarin.mk index ca9531828386..3fbe7bf1ca32 100644 --- a/mk/xamarin.mk +++ b/mk/xamarin.mk @@ -16,7 +16,7 @@ MACCORE_VERSION := $(shell cd $(MACCORE_PATH) 2> /dev/null && git rev-parse HE MACCORE_BRANCH := $(shell cd $(MACCORE_PATH) 2> /dev/null && git symbolic-ref --short HEAD 2> /dev/null) -NEEDED_ADR_VERSION := d466eac70a9b1bba94c18c63e34e590c66f6d044 +NEEDED_ADR_VERSION := adccd1c48a7c2540b0c37f2bf7add7d2c1398729 NEEDED_ADR_BRANCH := main ADR_DIRECTORY := macios-adr diff --git a/msbuild/Directory.Build.props b/msbuild/Directory.Build.props index 20876e7a029e..5c6a18b61a37 100644 --- a/msbuild/Directory.Build.props +++ b/msbuild/Directory.Build.props @@ -16,7 +16,7 @@ --> [3.0.13] - [1.1.7] + [17.14.133-g001ce2ac7a] diff --git a/msbuild/Makefile b/msbuild/Makefile index 8ce64128f360..1dbee190e1b0 100644 --- a/msbuild/Makefile +++ b/msbuild/Makefile @@ -53,7 +53,7 @@ IOS_WINDOWS_TARGETS = \ TASK_ASSEMBLIES = Xamarin.MacDev.Tasks $(LOCALIZATION_ASSEMBLIES) IOS_WINDOWS_TASK_ASSEMBLIES = Xamarin.iOS.Tasks.Windows -IOS_WINDOWS_DEPENDENCIES = Xamarin.iOS.Windows.Client iSign.Core ws2_32 System.Diagnostics.Tracer System.Formats.Asn1 System.Buffers System.Memory System.Numerics.Vectors System.Runtime.CompilerServices.Unsafe System.Security.Cryptography.ProtectedData System.Security.Cryptography.Pkcs Microsoft.Win32.Registry System.Security.AccessControl System.Security.Principal.Windows +IOS_WINDOWS_DEPENDENCIES = Xamarin.iOS.Windows.Client iSign.Core ws2_32 System.Diagnostics.Tracer System.Formats.Asn1 System.Buffers System.Memory System.Numerics.Vectors System.Runtime.CompilerServices.Unsafe System.Security.Cryptography.ProtectedData System.Security.Cryptography.Pkcs Microsoft.Win32.Registry IOS_WINDOWS_MOBILEDEVICE_TOOLS = iMobileDevice-net bz2 getopt ideviceactivation idevicebackup idevicebackup2 idevicecrashreport idevicedate idevicedebug idevicedebugserverproxy idevicediagnostics ideviceenterrecovery ideviceimagemounter ideviceinfo ideviceinstaller idevicename idevicenotificationproxy idevicepair ideviceprovision idevicerestore idevicescreenshot idevicesyslog idevice_id imobiledevice-net-lighthouse imobiledevice ios_webkit_debug_proxy iproxy irecovery irecovery libcharset libcurl LIBEAY32 libiconv libusb-1.0 libusb0 libxml2 lzma pcre pcreposix plist plistutil plist_cmp plist_test pthreadVC3 readline SSLEAY32 usbmuxd usbmuxd vcruntime140 zip zlib1 PROPS_AND_TARGETS = \ diff --git a/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj b/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj index d568407094be..664afef79aa1 100644 --- a/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj +++ b/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj @@ -32,6 +32,10 @@ + + + + Versions.g.cs diff --git a/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx b/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx index c5e2d698a91f..707652e32f62 100644 --- a/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx +++ b/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx @@ -1714,4 +1714,9 @@ {0}: the path to a file + + + Did not extract {0} because it would write outside the target directory. + + diff --git a/msbuild/Xamarin.MacDev.Tasks/Decompress.cs b/msbuild/Xamarin.MacDev.Tasks/Decompress.cs index 4f2f8d5c0636..5dc2734c6083 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Decompress.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Decompress.cs @@ -171,6 +171,7 @@ static bool TryDecompressUsingSystemIOCompression (TaskLoggingHelper log, string resource = resource.TrimEnd ('/', '\\'); resource = resource.Replace ('\\', zipDirectorySeparator); var resourceAsDir = resource + zipDirectorySeparator; + decompressionDir = Path.GetFullPath (decompressionDir); using var archive = ZipFile.OpenRead (zip); foreach (var entry in archive.Entries) { @@ -204,6 +205,17 @@ static bool TryDecompressUsingSystemIOCompression (TaskLoggingHelper log, string var isDir = entryPath [entryPath.Length - 1] == zipDirectorySeparator; var targetPath = Path.Combine (decompressionDir, entryPath.Replace (zipDirectorySeparator, Path.DirectorySeparatorChar)); + + // canonicalize the path + targetPath = Path.GetFullPath (targetPath); + + // validate that the unzipped file is inside the target directory + var decompressionDirectoryPath = decompressionDir.Trim (Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + if (!targetPath.StartsWith (decompressionDirectoryPath)) { + log.LogWarning (7144, null, MSBStrings.W7144 /* Did not extract {0} because it would write outside the target directory. */, entryPath); + continue; + } + if (isDir) { Directory.CreateDirectory (targetPath); } else { diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs index 701ba6df3475..e9f5c2903ee0 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs @@ -52,7 +52,7 @@ public override bool Execute () continue; } - Log.LogWarning (7091, frameworkExecutablePath, MSBStrings.W7091 /* "The framework {0} is a framework of static libraries, and will not be copied to the app." */, Path.GetDirectoryName (frameworkExecutablePath)); + Log.LogMessage (MessageImportance.Low, MSBStrings.W7091 /* "The framework {0} is a framework of static libraries, and will not be copied to the app." */, Path.GetDirectoryName (frameworkExecutablePath)); list.RemoveAt (i); } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/PackLibraryResources.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/PackLibraryResources.cs index 2c8cca4505ba..5b5d5046db36 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/PackLibraryResources.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/PackLibraryResources.cs @@ -49,7 +49,14 @@ public override bool Execute () { var results = new List (); + var hashOriginalResources = new HashSet (BundleOriginalResourcesWithLogicalNames.Select (v => v.ItemSpec)); + foreach (var item in BundleResourcesWithLogicalNames) { + if (hashOriginalResources.Contains (item.ItemSpec)) { + Log.LogMessage (MessageImportance.Low, $"Skipping BundleResourcesWithLogicalNames={item.ItemSpec}, because it's also specified in BundleOriginalResourcesWithLogicalNames"); + continue; + } + var logicalName = item.GetMetadata ("LogicalName"); if (string.IsNullOrEmpty (logicalName)) { diff --git a/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj b/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj index 24b51820d7e6..34bafd997107 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj +++ b/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj @@ -30,6 +30,10 @@ + + + + diff --git a/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj b/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj index 1173aaeb0905..7cbc1215d9bb 100644 --- a/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj +++ b/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj @@ -22,6 +22,7 @@ + @@ -38,7 +39,7 @@ PreserveNewest - + diff --git a/scripts/rsp-to-csproj/rsp-to-csproj.cs b/scripts/rsp-to-csproj/rsp-to-csproj.cs index 0e3ce7e2c7e0..d62e449a20c1 100644 --- a/scripts/rsp-to-csproj/rsp-to-csproj.cs +++ b/scripts/rsp-to-csproj/rsp-to-csproj.cs @@ -175,6 +175,10 @@ void ProcessFile (string file) break; case "noconfig": // this is already passed to csc by default break; + case "reportanalyzer": + if (!properties.Contains (("ReportAnalyzer", "true"))) + properties.Add (new ("ReportAnalyzer", "true")); + break; default: ReportError ($"Didn't understand argument '{a}'"); break; diff --git a/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs b/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs index b4bcb7ff7a81..02331fe8f91a 100644 --- a/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs +++ b/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs @@ -17,7 +17,7 @@ public virtual AVAssetDownloadedAssetEvictionPriority Priority { } public partial class AVMutableAssetDownloadStorageManagementPolicy { - + public override AVAssetDownloadedAssetEvictionPriority Priority { get { return AVAssetDownloadedAssetEvictionPriorityExtensions.GetValue (_Priority); } set { _Priority = value.GetConstant () ?? throw new ArgumentOutOfRangeException (nameof (Priority)); } diff --git a/src/AVFoundation/AVCaptureMetadataOutput.cs b/src/AVFoundation/AVCaptureMetadataOutput.cs index 48806d4fdf78..a4d7564bdeb2 100644 --- a/src/AVFoundation/AVCaptureMetadataOutput.cs +++ b/src/AVFoundation/AVCaptureMetadataOutput.cs @@ -36,12 +36,12 @@ namespace AVFoundation { public partial class AVCaptureMetadataOutput { - + public AVMetadataObjectType AvailableMetadataObjectTypes { get { return AVMetadataObjectTypeExtensions.ToFlags (WeakAvailableMetadataObjectTypes); } } - public AVMetadataObjectType MetadataObjectTypes { + public AVMetadataObjectType MetadataObjectTypes { get { return AVMetadataObjectTypeExtensions.ToFlags (WeakMetadataObjectTypes); } set { WeakMetadataObjectTypes = value.ToArray (); } } diff --git a/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs b/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs index efa68e1be136..0d40567dc4df 100644 --- a/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs +++ b/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs @@ -36,12 +36,12 @@ namespace AVFoundation { public partial class AVMetadataMachineReadableCodeObject { - public CGPoint []? Corners { + public CGPoint[]? Corners { get { var arr = WeakCorners; if (arr is null) return null; - var rv = new CGPoint [arr.Length]; + var rv = new CGPoint[arr.Length]; for (int i = 0; i < rv.Length; i++) { var dict = arr [i]; CGPoint pnt; diff --git a/src/AVFoundation/AVOutputSettingsAssistant.cs b/src/AVFoundation/AVOutputSettingsAssistant.cs index 246b8e373345..0b38d546a4a2 100644 --- a/src/AVFoundation/AVOutputSettingsAssistant.cs +++ b/src/AVFoundation/AVOutputSettingsAssistant.cs @@ -20,19 +20,19 @@ public AVOutputSettingsAssistant? Preset640x480 { return FromPreset (_Preset640x480); } } - + public AVOutputSettingsAssistant? Preset960x540 { get { return FromPreset (_Preset960x540); } } - + public AVOutputSettingsAssistant? Preset1280x720 { get { return FromPreset (_Preset1280x720); } } - + public AVOutputSettingsAssistant? Preset1920x1080 { get { return FromPreset (_Preset1920x1080); diff --git a/src/AVRouting/AVCustomDeviceRoute.cs b/src/AVRouting/AVCustomDeviceRoute.cs index 20a878143495..0e48913281e2 100644 --- a/src/AVRouting/AVCustomDeviceRoute.cs +++ b/src/AVRouting/AVCustomDeviceRoute.cs @@ -13,7 +13,7 @@ namespace AVRouting { partial class AVCustomDeviceRoute { - public NWEndpoint NetworkEndpoint => new NWEndpoint (_NetworkEndpoint, owns: false); + public NWEndpoint NetworkEndpoint => new NWEndpoint (_NetworkEndpoint, owns: false); } } diff --git a/src/Accessibility/AXSettings.cs b/src/Accessibility/AXSettings.cs index 760988c28a26..0d2cd574f394 100644 --- a/src/Accessibility/AXSettings.cs +++ b/src/Accessibility/AXSettings.cs @@ -51,7 +51,7 @@ public static bool IsAssistiveAccessEnabled { [SupportedOSPlatform ("macos15.0")] [SupportedOSPlatform ("tvos18.0")] [DllImport (Constants.AccessibilityLibrary)] - unsafe static extern void AXOpenSettingsFeature (nint /* AXSettingsFeature */ feature, BlockLiteral* block); + unsafe static extern void AXOpenSettingsFeature (nint /* AXSettingsFeature */ feature, BlockLiteral *block); /// Open the Settings app to the specified section. /// The section to open. diff --git a/src/AddressBook/ABAddressBook.cs b/src/AddressBook/ABAddressBook.cs index fbeeb3e682f1..cfcee0027fda 100644 --- a/src/AddressBook/ABAddressBook.cs +++ b/src/AddressBook/ABAddressBook.cs @@ -85,7 +85,7 @@ static InitConstants () { #if __MACCATALYST__ // avoid TypeLoadException if used before macOS 11.x - if (!SystemVersion.CheckiOS (14, 0)) + if (!SystemVersion.CheckiOS (14,0)) return; #endif // ensure we can init. This is needed before iOS6 (as per doc). diff --git a/src/AppKit/Enums.cs b/src/AppKit/Enums.cs index b178cae88586..9acf4b72db68 100644 --- a/src/AppKit/Enums.cs +++ b/src/AppKit/Enums.cs @@ -1439,22 +1439,6 @@ public enum NSPasteboardReadingOptions : ulong { AsKeyedArchive = 4, } -#if !NET && MONOMAC // Use the one in Foundation instead, only keep this in macOS until .NET. - [Native] - public enum NSUnderlineStyle : long { - None = 0x00, - Single = 0x01, - Thick = 0x02, - Double = 0x09, - PatternSolid = 0x0000, - PatternDot = 0x0100, - PatternDash = 0x0200, - PatternDashDot = 0x0300, - PatternDashDotDot = 0x0400, - ByWord = 0x8000, - } -#endif - // Convenience enum, untyped in ObjC [NoMacCatalyst] public enum NSUnderlinePattern : int { diff --git a/src/AppKit/Functions.cs b/src/AppKit/Functions.cs index 4a4299de2950..afe5a2e27b13 100644 --- a/src/AppKit/Functions.cs +++ b/src/AppKit/Functions.cs @@ -36,9 +36,9 @@ namespace AppKit { #if MONOMAC // Class to access C functions public partial class AppKitFramework { - + [DllImport (Constants.AppKitLibrary)] - public static extern void NSBeep (); + public static extern void NSBeep(); } #endif } diff --git a/src/AppKit/NSGraphics.cs b/src/AppKit/NSGraphics.cs index 617f034b17ef..4d8d857e889e 100644 --- a/src/AppKit/NSGraphics.cs +++ b/src/AppKit/NSGraphics.cs @@ -181,7 +181,7 @@ public static void FrameRect (CGRect rect, nfloat frameWidth, NSCompositingOpera #if NET [SupportedOSPlatform ("macos")] - [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead.")] + [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead." )] #else [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use 'NSCursor.DisappearingItemCursor' instead.")] #endif @@ -190,7 +190,7 @@ public static void FrameRect (CGRect rect, nfloat frameWidth, NSCompositingOpera #if NET [SupportedOSPlatform ("macos")] - [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead.")] + [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead." )] #else [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use 'NSCursor.DisappearingItemCursor' instead.")] #endif diff --git a/src/AppKit/NSPasteboardReading.cs b/src/AppKit/NSPasteboardReading.cs index a6587fa1a415..04e90627818c 100644 --- a/src/AppKit/NSPasteboardReading.cs +++ b/src/AppKit/NSPasteboardReading.cs @@ -11,7 +11,7 @@ namespace AppKit { public partial interface INSPasteboardReading { [BindingImpl (BindingImplOptions.Optimizable)] - public unsafe static T? CreateInstance (NSObject propertyList, NSPasteboardType type) where T : NSObject, INSPasteboardReading + public unsafe static T? CreateInstance (NSObject propertyList, NSPasteboardType type) where T: NSObject, INSPasteboardReading { return CreateInstance (propertyList, type.GetConstant ()!); } diff --git a/src/AudioToolbox/AudioConverter.cs b/src/AudioToolbox/AudioConverter.cs index b993c9f7208d..4a672adc6b86 100644 --- a/src/AudioToolbox/AudioConverter.cs +++ b/src/AudioToolbox/AudioConverter.cs @@ -583,13 +583,13 @@ AudioConverterError FillComplexBuffer (ref int outputDataPacketSize, var packetSize = outputDataPacketSize; int* packetSizePtr = &packetSize; if (packetDescription is null) { - var returnOne = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr) packetSizePtr, (IntPtr) outputData, IntPtr.Zero); + var returnOne = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr)packetSizePtr, (IntPtr) outputData, IntPtr.Zero); outputDataPacketSize = packetSize; return returnOne; } fixed (AudioStreamPacketDescription* pdesc = packetDescription) { - var returnTwo = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr) packetSizePtr, (IntPtr) outputData, (IntPtr) pdesc); + var returnTwo = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr)packetSizePtr, (IntPtr) outputData, (IntPtr) pdesc); outputDataPacketSize = packetSize; return returnTwo; } diff --git a/src/AudioToolbox/AudioFile.cs b/src/AudioToolbox/AudioFile.cs index 83c5ca7ac299..71130c797555 100644 --- a/src/AudioToolbox/AudioFile.cs +++ b/src/AudioToolbox/AudioFile.cs @@ -1444,7 +1444,7 @@ public IntPtr GetProperty (AudioFileProperty property, out int size) return IntPtr.Zero; } #if NET - unsafe T? GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileProperty property) where T : unmanaged + unsafe T? GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileProperty property) where T : unmanaged #else unsafe T? GetProperty (AudioFileProperty property) where T : unmanaged #endif diff --git a/src/AudioToolbox/AudioFileStream.cs b/src/AudioToolbox/AudioFileStream.cs index d227efe43049..5c6395deb45a 100644 --- a/src/AudioToolbox/AudioFileStream.cs +++ b/src/AudioToolbox/AudioFileStream.cs @@ -438,7 +438,7 @@ long GetLong (AudioFileStreamProperty property) } #if NET - unsafe T? GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileStreamProperty property) where T : unmanaged + unsafe T? GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileStreamProperty property) where T : unmanaged #else unsafe T? GetProperty (AudioFileStreamProperty property) where T : unmanaged #endif diff --git a/src/AudioToolbox/AudioQueue.cs b/src/AudioToolbox/AudioQueue.cs index 1e7bee989edb..3d2a248651d8 100644 --- a/src/AudioToolbox/AudioQueue.cs +++ b/src/AudioToolbox/AudioQueue.cs @@ -988,7 +988,7 @@ public IntPtr GetProperty (AudioQueueProperty property, out int size) // Should be private #if NET - public unsafe T GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioQueueProperty property) where T : struct + public unsafe T GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioQueueProperty property) where T : struct #else public unsafe T GetProperty (AudioQueueProperty property) where T : struct #endif @@ -1016,7 +1016,7 @@ public unsafe T GetProperty (AudioQueueProperty property) where T : struct } #if NET - unsafe T GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioConverterPropertyID property) where T : struct + unsafe T GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioConverterPropertyID property) where T : struct #else unsafe T GetProperty (AudioConverterPropertyID property) where T : struct #endif @@ -1189,7 +1189,7 @@ public AudioStreamBasicDescription AudioStreamDescription { #if !MONOMAC return GetProperty (AudioQueueProperty.StreamDescription); #else - return GetProperty (AudioConverterPropertyID.CurrentInputStreamDescription); + return GetProperty (AudioConverterPropertyID.CurrentInputStreamDescription); #endif } } @@ -1296,7 +1296,7 @@ extern static AudioQueueStatus AudioQueueProcessingTapNew (IntPtr inAQ, AudioQue #if NET unsafe { status = AudioQueueProcessingTapNew (handle, &AudioQueueProcessingTap.TapCallback, GCHandle.ToIntPtr (aqpt.Handle), flags, &maxFrames, - &processingFormat, &tapHandle); + &processingFormat, &tapHandle); } #else status = AudioQueueProcessingTapNew (handle, AudioQueueProcessingTap.CreateTapCallback, GCHandle.ToIntPtr (aqpt.Handle), flags, out maxFrames, @@ -1459,7 +1459,7 @@ public class OutputAudioQueue : AudioQueue { #if NET [DllImport (Constants.AudioToolboxLibrary)] extern unsafe static OSStatus AudioQueueNewOutput (AudioStreamBasicDescription* format, delegate* unmanaged callback, - IntPtr userData, IntPtr cfrunLoop_callbackRunloop, IntPtr cfstr_runMode, + IntPtr userData, IntPtr cfrunLoop_callbackRunloop, IntPtr cfstr_runMode, uint flags, IntPtr* audioQueue); #else static readonly AudioQueueOutputCallback dOutputCallback = output_callback; diff --git a/src/AudioToolbox/MusicTrack.cs b/src/AudioToolbox/MusicTrack.cs index 37866a3a50cc..53d36bafc3cf 100644 --- a/src/AudioToolbox/MusicTrack.cs +++ b/src/AudioToolbox/MusicTrack.cs @@ -309,7 +309,7 @@ public MusicPlayerStatus GetDestMidiEndpoint (out MidiEndpoint? outEndpoint) unsafe { result = MusicTrackGetDestMIDIEndpoint (Handle, &midiHandle); } - outEndpoint = (result == MusicPlayerStatus.Success) ? new MidiEndpoint (midiHandle) : null; + outEndpoint = (result == MusicPlayerStatus.Success)? new MidiEndpoint (midiHandle): null; return result; } #endif diff --git a/src/AudioToolbox/SystemSound.cs b/src/AudioToolbox/SystemSound.cs index 1e3d4be7f3fa..70295f4cb8c0 100644 --- a/src/AudioToolbox/SystemSound.cs +++ b/src/AudioToolbox/SystemSound.cs @@ -402,7 +402,7 @@ public AudioServicesError AddSystemSoundCompletion (Action routine, CFRunLoop? r runLoop.GetHandle (), IntPtr.Zero, // runLoopMode should be enum runLoopMode.GetHandle (), #if NET - &SoundCompletionShared, + &SoundCompletionShared, #else SoundCompletionCallback, #endif diff --git a/src/AudioUnit/AUEnums.cs b/src/AudioUnit/AUEnums.cs index 54a921159598..9eb7acba5f32 100644 --- a/src/AudioUnit/AUEnums.cs +++ b/src/AudioUnit/AUEnums.cs @@ -505,16 +505,16 @@ public enum AudioUnitParameterType // UInt32 in AudioUnitParameterInfo Mixer3DGain = 3, Mixer3DPlaybackRate = 4, #if MONOMAC - Mixer3DReverbBlend = 5, - Mixer3DGlobalReverbGain = 6, - Mixer3DOcclusionAttenuation = 7, - Mixer3DObstructionAttenuation = 8, - Mixer3DMinGain = 9, - Mixer3DMaxGain = 10, - Mixer3DPreAveragePower = 1000, - Mixer3DPrePeakHoldLevel = 2000, - Mixer3DPostAveragePower = 3000, - Mixer3DPostPeakHoldLevel = 4000, + Mixer3DReverbBlend = 5, + Mixer3DGlobalReverbGain = 6, + Mixer3DOcclusionAttenuation = 7, + Mixer3DObstructionAttenuation = 8, + Mixer3DMinGain = 9, + Mixer3DMaxGain = 10, + Mixer3DPreAveragePower = 1000, + Mixer3DPrePeakHoldLevel = 2000, + Mixer3DPostAveragePower = 3000, + Mixer3DPostPeakHoldLevel = 4000, #else Mixer3DEnable = 5, Mixer3DMinGain = 6, @@ -563,8 +563,8 @@ public enum AudioUnitParameterType // UInt32 in AudioUnitParameterInfo // AUTimePitch, AUTimePitch (offline), AUPitch units TimePitchRate = 0, #if MONOMAC - TimePitchPitch = 1, - TimePitchEffectBlend = 2, + TimePitchPitch = 1, + TimePitchEffectBlend = 2, #endif // AUNewTimePitch @@ -969,24 +969,24 @@ public enum AudioUnitSubType : uint { AudioFilePlayer = 0x6166706C, // 'afpl' #if MONOMAC - HALOutput = 0x6168616C, // 'ahal' - DefaultOutput = 0x64656620, // 'def ' - SystemOutput = 0x73797320, // 'sys ' - DLSSynth = 0x646C7320, // 'dls ' - TimePitch = 0x746D7074, // 'tmpt' - GraphicEQ = 0x67726571, // 'greq' - MultiBandCompressor = 0x6D636D70, // 'mcmp' - MatrixReverb = 0x6D726576, // 'mrev' - Pitch = 0x746D7074, // 'tmpt' - AUFilter = 0x66696C74, // 'filt - NetSend = 0x6E736E64, // 'nsnd' - RogerBeep = 0x726F6772, // 'rogr' - StereoMixer = 0x736D7872, // 'smxr' - SphericalHeadPanner = 0x73706872, // 'sphr' - VectorPanner = 0x76626173, // 'vbas' - SoundFieldPanner = 0x616D6269, // 'ambi' - HRTFPanner = 0x68727466, // 'hrtf' - NetReceive = 0x6E726376, // 'nrcv' + HALOutput = 0x6168616C, // 'ahal' + DefaultOutput = 0x64656620, // 'def ' + SystemOutput = 0x73797320, // 'sys ' + DLSSynth = 0x646C7320, // 'dls ' + TimePitch = 0x746D7074, // 'tmpt' + GraphicEQ = 0x67726571, // 'greq' + MultiBandCompressor = 0x6D636D70, // 'mcmp' + MatrixReverb = 0x6D726576, // 'mrev' + Pitch = 0x746D7074, // 'tmpt' + AUFilter = 0x66696C74, // 'filt + NetSend = 0x6E736E64, // 'nsnd' + RogerBeep = 0x726F6772, // 'rogr' + StereoMixer = 0x736D7872, // 'smxr' + SphericalHeadPanner = 0x73706872, // 'sphr' + VectorPanner = 0x76626173, // 'vbas' + SoundFieldPanner = 0x616D6269, // 'ambi' + HRTFPanner = 0x68727466, // 'hrtf' + NetReceive = 0x6E726376, // 'nrcv' #endif } diff --git a/src/AudioUnit/AUGraph.cs b/src/AudioUnit/AUGraph.cs index e0637a5c1a94..eaed2bec657b 100644 --- a/src/AudioUnit/AUGraph.cs +++ b/src/AudioUnit/AUGraph.cs @@ -175,7 +175,7 @@ public AudioUnitStatus RemoveRenderNotify (RenderDelegate callback) #if NET unsafe { if (graphUserCallbacks.Count == 0) - error = (AudioUnitStatus) AUGraphRemoveRenderNotify (Handle, &renderCallback, GCHandle.ToIntPtr (gcHandle)); + error = (AudioUnitStatus)AUGraphRemoveRenderNotify (Handle, &renderCallback, GCHandle.ToIntPtr (gcHandle)); } #else if (graphUserCallbacks.Count == 0) @@ -201,7 +201,7 @@ static CallbackShared static_CallbackShared { #if NET [UnmanagedCallersOnly] - static unsafe AudioUnitStatus renderCallback (IntPtr inRefCon, + static unsafe AudioUnitStatus renderCallback(IntPtr inRefCon, AudioUnitRenderActionFlags* _ioActionFlags, AudioTimeStamp* _inTimeStamp, uint _inBusNumber, @@ -530,14 +530,14 @@ protected override void Dispose (bool disposing) [DllImport (Constants.AudioToolboxLibrary)] #if NET - static unsafe extern int AUGraphAddRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon); + static unsafe extern int AUGraphAddRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon ); #else static extern int AUGraphAddRenderNotify (IntPtr inGraph, CallbackShared inCallback, IntPtr inRefCon); #endif #if NET [DllImport (Constants.AudioToolboxLibrary)] - static unsafe extern int AUGraphRemoveRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon); + static unsafe extern int AUGraphRemoveRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon ); #else [DllImport (Constants.AudioToolboxLibrary)] static extern int AUGraphRemoveRenderNotify (IntPtr inGraph, CallbackShared inCallback, IntPtr inRefCon); diff --git a/src/AudioUnit/AudioComponent.cs b/src/AudioUnit/AudioComponent.cs index 8cdc6261ab28..f5a073cc670c 100644 --- a/src/AudioUnit/AudioComponent.cs +++ b/src/AudioUnit/AudioComponent.cs @@ -43,7 +43,7 @@ #else using AppKit; #if !COREBUILD -using UIImage = AppKit.NSImage; +using UIImage=AppKit.NSImage; #endif #endif @@ -512,8 +512,7 @@ public double LastActiveTime { [Mac (13,0)] [iOS (16,0)] #endif - public NSDictionary? GetConfigurationInfo (out int resultCode) - { + public NSDictionary? GetConfigurationInfo (out int resultCode) { IntPtr dictPtr; unsafe { resultCode = AudioComponentCopyConfigurationInfo (GetCheckedHandle (), &dictPtr); @@ -562,8 +561,7 @@ unsafe static extern int AudioComponentValidate (IntPtr /* AudioComponent* */ in [iOS (16,0)] [MacCatalyst (16,0)] #endif - public AudioComponentValidationResult Validate (NSDictionary? validationParameters, out int resultCode) - { + public AudioComponentValidationResult Validate (NSDictionary? validationParameters, out int resultCode) { AudioComponentValidationResult result; unsafe { resultCode = AudioComponentValidate (GetCheckedHandle (), validationParameters.GetHandle (), &result); @@ -599,7 +597,7 @@ static void TrampolineAction (IntPtr blockPtr, AudioComponentValidationResult re { var del = BlockLiteral.GetTarget> (blockPtr); if (del is not null) - del (result, Runtime.GetNSObject (dictionary)); + del (result, Runtime.GetNSObject(dictionary)); } #if NET @@ -627,11 +625,10 @@ static void TrampolineAction (IntPtr blockPtr, AudioComponentValidationResult re #endif [BindingImpl (BindingImplOptions.Optimizable)] public void ValidateAsync (NSDictionary? validationParameters, - Action onCompletion, out int resultCode) - { + Action onCompletion, out int resultCode) { if (onCompletion is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (onCompletion)); - + unsafe { #if NET delegate* unmanaged trampoline = &TrampolineAction; @@ -699,7 +696,7 @@ public void ValidateAsync (NSDictionary? validationParameters, #else [NoTV] #endif - public AudioComponentInfo []? ComponentList { + public AudioComponentInfo[]? ComponentList { get { var nameHandle = CFString.CreateNative (Name); try { @@ -710,10 +707,10 @@ public AudioComponentInfo []? ComponentList { if (nsArray is null) return null; // make things easier for developers since we do not know how to have an implicit conversion from NSObject to AudioComponentInfo - var dics = NSArray.FromArray (nsArray); + var dics = NSArray.FromArray (nsArray); var result = new AudioComponentInfo [dics.Length]; for (var i = 0; i < result.Length; i++) { - result [i] = new AudioComponentInfo (dics [i]); + result [i] = new AudioComponentInfo (dics[i]); } return result; } diff --git a/src/AudioUnit/AudioComponentDescription.cs b/src/AudioUnit/AudioComponentDescription.cs index 019ee39f512f..48b801c68c16 100644 --- a/src/AudioUnit/AudioComponentDescription.cs +++ b/src/AudioUnit/AudioComponentDescription.cs @@ -97,9 +97,9 @@ public enum AudioComponentType : uint { // OSType in AudioComponentDescription public enum AudioTypeOutput { // OSType in AudioComponentDescription Generic = 0x67656e72, // 'genr' #if MONOMAC - HAL = 0x6168616c, // 'ahal' - Default = 0x64656620, // 'def' - System = 0x73797320, // 'sys' + HAL=0x6168616c, // 'ahal' + Default=0x64656620, // 'def' + System=0x73797320, // 'sys' #endif #if NET [SupportedOSPlatform ("macos")] @@ -113,7 +113,7 @@ public enum AudioTypeOutput { // OSType in AudioComponentDescription public enum AudioTypeMusicDevice { // OSType in AudioComponentDescription #if MONOMAC - DlsSynth = 0x646c7320, // 'dls ' + DlsSynth = 0x646c7320, // 'dls ' #endif Sampler = 0x73616d70, // 'samp' @@ -137,7 +137,7 @@ public enum AudioTypeConverter { // OSType in AudioComponentDescription RoundTripAAC = 0x72616163, // 'raac' MultiSplitter = 0x6d73706c, // 'mspl' #if MONOMAC - TimePitch = 0x746d7074, // 'tmpt' + TimePitch=0x746d7074, // 'tmpt' #else #if NET [SupportedOSPlatform ("ios")] @@ -188,13 +188,13 @@ public enum AudioTypeEffect { // OSType in AudioComponentDescription Distortion = 0x64697374, // 'dist' BandPassFilter = 0x62706173, // 'bpas' #if MONOMAC - GraphicEQ = 0x67726571, // 'greq' - MultiBandCompressor = 0x6d636d70, // 'mcmp' - MatrixReverb = 0x6d726576, // 'mrev' - Pitch = 0x70697463, // 'pitc' - AUFilter = 0x66696c74, // 'filt' - NetSend = 0x6e736e64, // 'nsnd' - RogerBeep = 0x726f6772, // 'rogr' + GraphicEQ=0x67726571, // 'greq' + MultiBandCompressor=0x6d636d70, // 'mcmp' + MatrixReverb=0x6d726576, // 'mrev' + Pitch=0x70697463, // 'pitc' + AUFilter=0x66696c74, // 'filt' + NetSend=0x6e736e64, // 'nsnd' + RogerBeep=0x726f6772, // 'rogr' #else #if NET [SupportedOSPlatform ("ios")] @@ -227,7 +227,7 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription Matrix = 0x6d786d78, // 'mxmx' Spacial = 0x3364656d, // Same as Embedded3D #if MONOMAC - Stereo = 0x736d7872, // 'smxr' + Stereo=0x736d7872, // 'smxr' #if NET [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("maccatalyst")] @@ -237,7 +237,7 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription #else [Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'Spacial' instead.")] #endif - ThreeD = 0x33646d78, // '3dmx' + ThreeD=0x33646d78, // '3dmx' #else #if NET [SupportedOSPlatform ("ios")] @@ -252,16 +252,16 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription public enum AudioTypePanner { // OSType in AudioComponentDescription #if MONOMAC - SphericalHead = 0x73706872, // 'sphr' - Vector = 0x76626173, // 'vbas' - SoundField = 0x616d6269, // 'ambi' - rHRTF = 0x68727466, // 'hrtf' + SphericalHead=0x73706872, // 'sphr' + Vector=0x76626173, // 'vbas' + SoundField=0x616d6269, // 'ambi' + rHRTF=0x68727466, // 'hrtf' #endif } public enum AudioTypeGenerator { // OSType in AudioComponentDescription #if MONOMAC - NetReceive = 0x6e726376, // 'nrcv' + NetReceive=0x6e726376, // 'nrcv' #endif ScheduledSoundPlayer = 0x7373706c, // 'sspl' AudioFilePlayer = 0x6166706c, // 'afpl' diff --git a/src/AudioUnit/AudioUnit.cs b/src/AudioUnit/AudioUnit.cs index ede6350113d9..332c6302aa1f 100644 --- a/src/AudioUnit/AudioUnit.cs +++ b/src/AudioUnit/AudioUnit.cs @@ -131,13 +131,14 @@ internal AudioUnitException (int k) : base (Lookup (k)) #if NET [StructLayout (LayoutKind.Sequential)] - unsafe struct AURenderCallbackStruct { + unsafe struct AURenderCallbackStruct + { #if COREBUILD public delegate* unmanaged Proc; #else public delegate* unmanaged Proc; #endif - public IntPtr ProcRefCon; + public IntPtr ProcRefCon; } #else [StructLayout (LayoutKind.Sequential)] @@ -700,7 +701,7 @@ public AudioUnitStatus SetRenderCallback (RenderDelegate renderDelegate, AudioUn #if NET [UnmanagedCallersOnly] - static unsafe AudioUnitStatus RenderCallbackImpl (IntPtr clientData, AudioUnitRenderActionFlags* actionFlags, AudioTimeStamp* timeStamp, uint busNumber, uint numberFrames, IntPtr data) + static unsafe AudioUnitStatus RenderCallbackImpl (IntPtr clientData, AudioUnitRenderActionFlags* actionFlags, AudioTimeStamp* timeStamp, uint busNumber, uint numberFrames, IntPtr data) #else [MonoPInvokeCallback (typeof (CallbackShared))] static AudioUnitStatus RenderCallbackImpl (IntPtr clientData, ref AudioUnitRenderActionFlags actionFlags, ref AudioTimeStamp timeStamp, uint busNumber, uint numberFrames, IntPtr data) @@ -1172,7 +1173,7 @@ public AudioObjectPropertyAddress (AudioObjectPropertySelector selector, AudioOb #endif public unsafe class AURenderEventEnumerator : INativeObject #if COREBUILD - { } + {} #else , IEnumerator { AURenderEvent* current; diff --git a/src/AudioUnit/AudioUnitUtils.cs b/src/AudioUnit/AudioUnitUtils.cs index 156b07afcda2..9303de1a98d0 100644 --- a/src/AudioUnit/AudioUnitUtils.cs +++ b/src/AudioUnit/AudioUnitUtils.cs @@ -40,10 +40,10 @@ namespace AudioUnit { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public static class AudioUnitUtils { public const int SampleFractionBits = 24; diff --git a/src/AudioUnit/ExtAudioFile.cs b/src/AudioUnit/ExtAudioFile.cs index 06d154f43695..83fab37e4822 100644 --- a/src/AudioUnit/ExtAudioFile.cs +++ b/src/AudioUnit/ExtAudioFile.cs @@ -70,10 +70,10 @@ public enum ExtAudioFileError // Implictly cast to OSType } #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public class ExtAudioFile : IDisposable { IntPtr _extAudioFile; diff --git a/src/BrowserEngineKit/BEStructs.cs b/src/BrowserEngineKit/BEStructs.cs index c6f6a5c1e1dc..b969768b35f7 100644 --- a/src/BrowserEngineKit/BEStructs.cs +++ b/src/BrowserEngineKit/BEStructs.cs @@ -6,15 +6,16 @@ namespace BrowserEngineKit { #if IOS || MACCATALYST || TVOS - [SupportedOSPlatform ("ios17.4")] - [SupportedOSPlatform ("maccatalyst17.4")] - [SupportedOSPlatform ("tvos17.4")] - [UnsupportedOSPlatform ("macos")] - [StructLayout (LayoutKind.Sequential)] - public struct BEDirectionalTextRange { - public nint Offset; - public nint Length; - } + [SupportedOSPlatform ("ios17.4")] + [SupportedOSPlatform ("maccatalyst17.4")] + [SupportedOSPlatform ("tvos17.4")] + [UnsupportedOSPlatform ("macos")] + [StructLayout (LayoutKind.Sequential)] + public struct BEDirectionalTextRange + { + public nint Offset; + public nint Length; + } #endif // __IOS__ || __MACCATALYST__ } #endif // NET diff --git a/src/Compression/CompressionStreamStruct.cs b/src/Compression/CompressionStreamStruct.cs index f50a88783d3d..1bc4c1199b06 100644 --- a/src/Compression/CompressionStreamStruct.cs +++ b/src/Compression/CompressionStreamStruct.cs @@ -8,10 +8,10 @@ namespace Compression { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("tvos")] #endif [StructLayout (LayoutKind.Sequential)] struct CompressionStreamStruct { diff --git a/src/Compression/TaskToApm.cs b/src/Compression/TaskToApm.cs index 643eefcf889b..4207ccc2c802 100644 --- a/src/Compression/TaskToApm.cs +++ b/src/Compression/TaskToApm.cs @@ -22,99 +22,107 @@ #nullable enable using System.Diagnostics; -namespace System.Threading.Tasks { - /// - /// Provides support for efficiently using Tasks to implement the APM (Begin/End) pattern. - /// - internal static class TaskToApm { - /// - /// Marshals the Task as an IAsyncResult, using the supplied callback and state - /// to implement the APM pattern. - /// - /// The Task to be marshaled. - /// The callback to be invoked upon completion. - /// The state to be stored in the IAsyncResult. - /// An IAsyncResult to represent the task's asynchronous operation. - public static IAsyncResult Begin (Task task, AsyncCallback? callback, object? state) => - new TaskAsyncResult (task, state, callback); +namespace System.Threading.Tasks +{ + /// + /// Provides support for efficiently using Tasks to implement the APM (Begin/End) pattern. + /// + internal static class TaskToApm + { + /// + /// Marshals the Task as an IAsyncResult, using the supplied callback and state + /// to implement the APM pattern. + /// + /// The Task to be marshaled. + /// The callback to be invoked upon completion. + /// The state to be stored in the IAsyncResult. + /// An IAsyncResult to represent the task's asynchronous operation. + public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state) => + new TaskAsyncResult(task, state, callback); - /// Processes an IAsyncResult returned by Begin. - /// The IAsyncResult to unwrap. - public static void End (IAsyncResult asyncResult) - { - if (asyncResult is TaskAsyncResult twar) { - twar._task.GetAwaiter ().GetResult (); - return; - } + /// Processes an IAsyncResult returned by Begin. + /// The IAsyncResult to unwrap. + public static void End(IAsyncResult asyncResult) + { + if (asyncResult is TaskAsyncResult twar) + { + twar._task.GetAwaiter().GetResult(); + return; + } - throw new ArgumentNullException (); - } + throw new ArgumentNullException(); + } - /// Processes an IAsyncResult returned by Begin. - /// The IAsyncResult to unwrap. - public static TResult End (IAsyncResult asyncResult) - { - if (asyncResult is TaskAsyncResult twar && twar._task is Task task) { - return task.GetAwaiter ().GetResult (); - } - throw new ArgumentNullException (); - } + /// Processes an IAsyncResult returned by Begin. + /// The IAsyncResult to unwrap. + public static TResult End(IAsyncResult asyncResult) + { + if (asyncResult is TaskAsyncResult twar && twar._task is Task task) + { + return task.GetAwaiter().GetResult(); + } + throw new ArgumentNullException(); + } - /// Provides a simple IAsyncResult that wraps a Task. - /// - /// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state, - /// but that's very rare, in particular in a situation where someone cares about allocation, and always - /// using TaskAsyncResult simplifies things and enables additional optimizations. - /// - internal sealed class TaskAsyncResult : IAsyncResult { - /// The wrapped Task. - internal readonly Task _task; - /// Callback to invoke when the wrapped task completes. - private readonly AsyncCallback? _callback; + /// Provides a simple IAsyncResult that wraps a Task. + /// + /// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state, + /// but that's very rare, in particular in a situation where someone cares about allocation, and always + /// using TaskAsyncResult simplifies things and enables additional optimizations. + /// + internal sealed class TaskAsyncResult : IAsyncResult + { + /// The wrapped Task. + internal readonly Task _task; + /// Callback to invoke when the wrapped task completes. + private readonly AsyncCallback? _callback; - /// Initializes the IAsyncResult with the Task to wrap and the associated object state. - /// The Task to wrap. - /// The new AsyncState value. - /// Callback to invoke when the wrapped task completes. - internal TaskAsyncResult (Task task, object? state, AsyncCallback? callback) - { - Debug.Assert (task is not null); - _task = task; - AsyncState = state; + /// Initializes the IAsyncResult with the Task to wrap and the associated object state. + /// The Task to wrap. + /// The new AsyncState value. + /// Callback to invoke when the wrapped task completes. + internal TaskAsyncResult(Task task, object? state, AsyncCallback? callback) + { + Debug.Assert(task is not null); + _task = task; + AsyncState = state; - if (task.IsCompleted) { - // Synchronous completion. Invoke the callback. No need to store it. - CompletedSynchronously = true; - callback?.Invoke (this); - } else if (callback is not null) { - // Asynchronous completion, and we have a callback; schedule it. We use OnCompleted rather than ContinueWith in - // order to avoid running synchronously if the task has already completed by the time we get here but still run - // synchronously as part of the task's completion if the task completes after (the more common case). - _callback = callback; - _task.ConfigureAwait (continueOnCapturedContext: false) - .GetAwaiter () - .OnCompleted (InvokeCallback); // allocates a delegate, but avoids a closure - } - } + if (task.IsCompleted) + { + // Synchronous completion. Invoke the callback. No need to store it. + CompletedSynchronously = true; + callback?.Invoke(this); + } + else if (callback is not null) + { + // Asynchronous completion, and we have a callback; schedule it. We use OnCompleted rather than ContinueWith in + // order to avoid running synchronously if the task has already completed by the time we get here but still run + // synchronously as part of the task's completion if the task completes after (the more common case). + _callback = callback; + _task.ConfigureAwait(continueOnCapturedContext: false) + .GetAwaiter() + .OnCompleted(InvokeCallback); // allocates a delegate, but avoids a closure + } + } - /// Invokes the callback. - private void InvokeCallback () - { - Debug.Assert (!CompletedSynchronously); - Debug.Assert (_callback is not null); - _callback.Invoke (this); - } + /// Invokes the callback. + private void InvokeCallback() + { + Debug.Assert(!CompletedSynchronously); + Debug.Assert(_callback is not null); + _callback.Invoke(this); + } - /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. - public object? AsyncState { get; } - /// Gets a value that indicates whether the asynchronous operation completed synchronously. - /// This is set lazily based on whether the has completed by the time this object is created. - public bool CompletedSynchronously { get; } - /// Gets a value that indicates whether the asynchronous operation has completed. - public bool IsCompleted => _task.IsCompleted; - /// Gets a that is used to wait for an asynchronous operation to complete. - public WaitHandle AsyncWaitHandle => ((IAsyncResult) _task).AsyncWaitHandle; - } - } + /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. + public object? AsyncState { get; } + /// Gets a value that indicates whether the asynchronous operation completed synchronously. + /// This is set lazily based on whether the has completed by the time this object is created. + public bool CompletedSynchronously { get; } + /// Gets a value that indicates whether the asynchronous operation has completed. + public bool IsCompleted => _task.IsCompleted; + /// Gets a that is used to wait for an asynchronous operation to complete. + public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle; + } + } } #endif diff --git a/src/CoreAnimation/CATextLayer.cs b/src/CoreAnimation/CATextLayer.cs index 40a377a5ef8f..135d5879a8cb 100644 --- a/src/CoreAnimation/CATextLayer.cs +++ b/src/CoreAnimation/CATextLayer.cs @@ -106,7 +106,7 @@ public object? WeakFont { set { #if MONOMAC var ns = value as NSFont; - if (ns is not null) { + if (ns is not null){ _Font = ns.Handle; return; } diff --git a/src/CoreAnimation/CATransform3D.cs b/src/CoreAnimation/CATransform3D.cs index a9608e3f0cfe..88845428cbc6 100644 --- a/src/CoreAnimation/CATransform3D.cs +++ b/src/CoreAnimation/CATransform3D.cs @@ -267,10 +267,10 @@ public override string ToString () { return String.Format ("[{0} {1} {2} {3}; {4} {5} {6} {7}; {8} {9} {10} {11}; {12} {13} {14} {15}]", #if NET - M11, M12, M13, M14, - M21, M22, M23, M24, - M31, M32, M33, M34, - M41, M42, M43, M44); + M11, M12, M13, M14, + M21, M22, M23, M24, + M31, M32, M33, M34, + M41, M42, M43, M44); #else m11, m12, m13, m14, m21, m22, m23, m24, diff --git a/src/CoreBluetooth/CBPeer.cs b/src/CoreBluetooth/CBPeer.cs index 418b3b009123..4d08fc531522 100644 --- a/src/CoreBluetooth/CBPeer.cs +++ b/src/CoreBluetooth/CBPeer.cs @@ -7,7 +7,7 @@ #nullable enable namespace CoreBluetooth { - public partial class CBPeer { + public partial class CBPeer { #if !NET [Deprecated (PlatformName.iOS, 7, 0)] [Obsoleted (PlatformName.iOS, 9, 0)] diff --git a/src/CoreFoundation/CFMessagePort.cs b/src/CoreFoundation/CFMessagePort.cs index 741bbbfabf46..7c71ba32ec86 100644 --- a/src/CoreFoundation/CFMessagePort.cs +++ b/src/CoreFoundation/CFMessagePort.cs @@ -264,12 +264,12 @@ protected override void Dispose (bool disposing) if (context is not null) { #if NET unsafe { - if (context.Retain is not null) - contextProxy.retain = &RetainProxy; - if (context.Release is not null) - contextProxy.release = &ReleaseProxy; - if (context.CopyDescription is not null) - contextProxy.copyDescription = &CopyDescriptionProxy; + if (context.Retain is not null) + contextProxy.retain = &RetainProxy; + if (context.Release is not null) + contextProxy.release = &ReleaseProxy; + if (context.CopyDescription is not null) + contextProxy.copyDescription = &CopyDescriptionProxy; } #else if (context.Retain is not null) diff --git a/src/CoreFoundation/CFProxySupport.cs b/src/CoreFoundation/CFProxySupport.cs index 01feaaf66745..24cdf7178f35 100644 --- a/src/CoreFoundation/CFProxySupport.cs +++ b/src/CoreFoundation/CFProxySupport.cs @@ -719,7 +719,7 @@ await Task.Run (() => { #if NET unsafe { - using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) + using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) #else using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) #endif @@ -783,7 +783,7 @@ await Task.Run (() => { #if NET unsafe { - using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) + using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) #else using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) #endif diff --git a/src/CoreGraphics/CGAffineTransform.cs b/src/CoreGraphics/CGAffineTransform.cs index fe3f74d41eac..620b85fdd7d7 100644 --- a/src/CoreGraphics/CGAffineTransform.cs +++ b/src/CoreGraphics/CGAffineTransform.cs @@ -162,11 +162,11 @@ public static CGAffineTransform Multiply (CGAffineTransform a, CGAffineTransform { #if NET return new CGAffineTransform (a.A * b.A + a.B * b.C, - a.A * b.B + a.B * b.D, - a.C * b.A + a.D * b.C, - a.C * b.B + a.D * b.D, - a.Tx * b.A + a.Ty * b.C + b.Tx, - a.Tx * b.B + a.Ty * b.D + b.Ty); + a.A * b.B + a.B * b.D, + a.C * b.A + a.D * b.C, + a.C * b.B + a.D * b.D, + a.Tx * b.A + a.Ty * b.C + b.Tx, + a.Tx * b.B + a.Ty * b.D + b.Ty); #else #pragma warning disable CS0618 // Type or member is obsolete return new CGAffineTransform (a.xx * b.xx + a.yx * b.xy, @@ -388,11 +388,11 @@ public bool IsIdentity { { #if NET return new CGAffineTransform (a.A * b.A + a.B * b.C, - a.A * b.B + a.B * b.D, - a.C * b.A + a.D * b.C, - a.C * b.B + a.D * b.D, - a.Tx * b.A + a.Ty * b.C + b.Tx, - a.Tx * b.B + a.Ty * b.D + b.Ty); + a.A * b.B + a.B * b.D, + a.C * b.A + a.D * b.C, + a.C * b.B + a.D * b.D, + a.Tx * b.A + a.Ty * b.C + b.Tx, + a.Tx * b.B + a.Ty * b.D + b.Ty); #else return new CGAffineTransform (a.xx * b.xx + a.yx * b.xy, a.xx * b.yx + a.yx * b.yy, @@ -426,7 +426,7 @@ public CGPoint TransformPoint (CGPoint point) { #if NET return new CGPoint (A * point.X + C * point.Y + Tx, - B * point.X + D * point.Y + Ty); + B * point.X + D * point.Y + Ty); #else return new CGPoint (xx * point.X + xy * point.Y + x0, yx * point.X + yy * point.Y + y0); diff --git a/src/CoreGraphics/CGColorSpace.cs b/src/CoreGraphics/CGColorSpace.cs index 54163367aa75..c0eb87cfa104 100644 --- a/src/CoreGraphics/CGColorSpace.cs +++ b/src/CoreGraphics/CGColorSpace.cs @@ -512,7 +512,7 @@ public byte [] GetColorTable () /* CGColorSpaceRef __nullable */ IntPtr alternate); #if NET - public static CGColorSpace? CreateIccProfile (nfloat []? range, CGDataProvider profile, CGColorSpace alternate) + public static CGColorSpace? CreateIccProfile (nfloat[]? range, CGDataProvider profile, CGColorSpace alternate) #else public static CGColorSpace? CreateICCProfile (nfloat []? range, CGDataProvider profile, CGColorSpace alternate) #endif diff --git a/src/CoreGraphics/CGDisplay.cs b/src/CoreGraphics/CGDisplay.cs index d9afcb3d6ae3..e526968846e1 100644 --- a/src/CoreGraphics/CGDisplay.cs +++ b/src/CoreGraphics/CGDisplay.cs @@ -6,7 +6,8 @@ using ObjCRuntime; using Foundation; -namespace CoreGraphics { +namespace CoreGraphics +{ #if NET [SupportedOSPlatform ("maccatalyst")] @@ -14,7 +15,8 @@ namespace CoreGraphics { #else [MacCatalyst (13,1)] #endif - public enum CGCaptureOptions : uint { + public enum CGCaptureOptions : uint + { None = 0, NoFill = 1 << 0 } @@ -25,18 +27,19 @@ public enum CGCaptureOptions : uint { #else [MacCatalyst (13,1)] #endif - public static class CGDisplay { + public static class CGDisplay + { #if !COREBUILD [DllImport (Constants.CoreGraphicsLibrary)] static extern uint CGMainDisplayID (); public static int MainDisplayID { get { - return (int) CGMainDisplayID (); + return (int)CGMainDisplayID (); } } - [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGDisplayModeGetTypeID")] + [DllImport (Constants.CoreGraphicsLibrary, EntryPoint="CGDisplayModeGetTypeID")] public static extern nint GetTypeID (); [DllImport (Constants.CoreGraphicsLibrary)] @@ -44,7 +47,7 @@ public static int MainDisplayID { public static CGRect GetBounds (int display) { - return CGDisplayBounds ((uint) display); + return CGDisplayBounds ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -52,7 +55,7 @@ public static CGRect GetBounds (int display) public static nint GetWidth (int display) { - return (nint) CGDisplayPixelsWide ((uint) display); + return (nint)CGDisplayPixelsWide ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -60,7 +63,7 @@ public static nint GetWidth (int display) public static nint GetHeight (int display) { - return (nint) CGDisplayPixelsHigh ((uint) display); + return (nint)CGDisplayPixelsHigh ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -68,7 +71,7 @@ public static nint GetHeight (int display) public static int SetDisplayTransfer (int display, float redMin, float redMax, float redGamma, float greenMin, float greenMax, float greenGamma, float blueMin, float blueMax, float blueGamma) { - return CGSetDisplayTransferByFormula ((uint) display, redMin, redMax, redGamma, greenMin, greenMax, greenGamma, blueMin, blueMax, blueGamma); + return CGSetDisplayTransferByFormula ((uint)display, redMin, redMax, redGamma, greenMin, greenMax, greenGamma, blueMin, blueMax, blueGamma); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -76,7 +79,7 @@ public static int SetDisplayTransfer (int display, float redMin, float redMax, f public static int GetGammaTableCapacity (int display) { - return (int) CGDisplayGammaTableCapacity ((uint) display); + return (int)CGDisplayGammaTableCapacity ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGDisplayRestoreColorSyncSettings")] @@ -95,7 +98,7 @@ public static int GetGammaTableCapacity (int display) public static bool IsCaptured (int display) { - return CGDisplayIsCaptured ((uint) display) != 0; + return CGDisplayIsCaptured ((uint)display) != 0; } [DllImport (Constants.CoreGraphicsLibrary)] @@ -103,7 +106,7 @@ public static bool IsCaptured (int display) public static int Capture (int display) { - return CGDisplayCapture ((uint) display); + return CGDisplayCapture ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -111,7 +114,7 @@ public static int Capture (int display) public static int Capture (int display, CGCaptureOptions options) { - return CGDisplayCaptureWithOptions ((uint) display, options); + return CGDisplayCaptureWithOptions ((uint)display, options); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -119,13 +122,13 @@ public static int Capture (int display, CGCaptureOptions options) public static int Release (int display) { - return CGDisplayRelease ((uint) display); + return CGDisplayRelease ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGCaptureAllDisplays")] public static extern int CaptureAllDisplays (); - [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGCaptureAllDisplaysWithOptions")] + [DllImport (Constants.CoreGraphicsLibrary, EntryPoint="CGCaptureAllDisplaysWithOptions")] static extern int CaptureAllDisplays (CGCaptureOptions options); @@ -137,7 +140,7 @@ public static int Release (int display) public static int HideCursor (int display) { - return CGDisplayHideCursor ((uint) display); + return CGDisplayHideCursor ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -145,7 +148,7 @@ public static int HideCursor (int display) public static int ShowCursor (int display) { - return CGDisplayShowCursor ((uint) display); + return CGDisplayShowCursor ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -153,7 +156,7 @@ public static int ShowCursor (int display) public static int MoveCursor (int display, CGPoint point) { - return CGDisplayMoveCursorToPoint ((uint) display, point); + return CGDisplayMoveCursorToPoint ((uint)display, point); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -161,7 +164,7 @@ public static int MoveCursor (int display, CGPoint point) public static int GetOpenGLDisplayMask (int display) { - return (int) CGDisplayIDToOpenGLDisplayMask ((uint) display); + return (int)CGDisplayIDToOpenGLDisplayMask ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -169,7 +172,7 @@ public static int GetOpenGLDisplayMask (int display) public static int GetDisplayID (int displayMask) { - return (int) CGOpenGLDisplayMaskToDisplayID ((uint) displayMask); + return (int)CGOpenGLDisplayMaskToDisplayID ((uint)displayMask); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -177,7 +180,7 @@ public static int GetDisplayID (int displayMask) public static int GetShieldingWindowID (int display) { - return (int) CGShieldingWindowID ((uint) display); + return (int)CGShieldingWindowID ((uint)display); } [DllImport (Constants.CoreGraphicsLibrary)] diff --git a/src/CoreGraphics/CGEvent.cs b/src/CoreGraphics/CGEvent.cs index e13ead361bdc..bdec2da8e97f 100644 --- a/src/CoreGraphics/CGEvent.cs +++ b/src/CoreGraphics/CGEvent.cs @@ -70,10 +70,10 @@ public void Dispose () static IntPtr TapCallback (IntPtr tapProxyEvent, CGEventType eventType, IntPtr eventRef, IntPtr userInfo) { var gch = GCHandle.FromIntPtr (userInfo); - var tapData = (TapData) gch.Target!; + var tapData = (TapData)gch.Target!; return tapData.Callback (tapProxyEvent, eventType, eventRef, tapData.UserInfo); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static unsafe IntPtr CGEventTapCreate (CGEventTapLocation location, CGEventTapPlacement place, CGEventTapOptions options, CGEventMask mask, delegate* unmanaged cback, IntPtr data); #else @@ -126,7 +126,7 @@ static IntPtr TapCallback (IntPtr tapProxyEvent, CGEventType eventType, IntPtr e [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventTapCreateForPSN (IntPtr processSerialNumer, CGEventTapPlacement place, CGEventTapOptions options, CGEventMask mask, CGEventTapCallback cback, IntPtr data); #endif - + #if !XAMCORE_5_0 [Obsolete ("The location parameter is not used. Consider using the overload without the location parameter.", false)] [System.ComponentModel.EditorBrowsable (System.ComponentModel.EditorBrowsableState.Never)] @@ -193,14 +193,14 @@ static IntPtr Create (NSData source) return CGEventCreateFromData (IntPtr.Zero, source.Handle); } - public CGEvent (NSData source) + public CGEvent (NSData source) : base (Create (source), true) { } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventCreate (IntPtr eventSourceHandle); - + public CGEvent (CGEventSource? eventSource) : base (CGEventCreate (eventSource.GetHandle ()), true) { @@ -220,8 +220,8 @@ internal CGEvent (NativeHandle handle, bool owns) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - extern static IntPtr CGEventCreateMouseEvent (IntPtr source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton); - + extern static IntPtr CGEventCreateMouseEvent(IntPtr source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton); + public CGEvent (CGEventSource? source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton) : base (CGEventCreateMouseEvent (source.GetHandle (), mouseType, mouseCursorPosition, mouseButton), true) { @@ -297,8 +297,8 @@ public CGEvent Copy () return null; return new CGEventSource (esh, true); } - - + + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGPoint CGEventGetLocation (IntPtr handle); @@ -325,7 +325,7 @@ public CGPoint UnflippedLocation { // Keep this public, as we want to avoid creating instances of the object // just to peek at the flags - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetFlags")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetFlags")] public extern static CGEventFlags GetFlags (IntPtr eventHandle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] @@ -340,16 +340,16 @@ public CGEventFlags Flags { } } - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetIntegerValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetIntegerValueField")] extern static long GetLong (IntPtr eventHandle, CGEventField eventField); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSetIntegerValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSetIntegerValueField")] extern static void SetLong (IntPtr eventHandle, CGEventField eventField, long value); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetDoubleValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetDoubleValueField")] extern static double GetDouble (IntPtr eventHandle, CGEventField eventField); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSetDoubleValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSetDoubleValueField")] extern static void SetDouble (IntPtr eventHandle, CGEventField eventField, double value); /// Get the 64-bit integer value of the specified event field. @@ -468,7 +468,7 @@ public long MouseEventSubtype { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventSetSource (IntPtr handle, IntPtr source); - + public void SetEventSource (CGEventSource eventSource) { if (eventSource is null) @@ -477,11 +477,11 @@ public void SetEventSource (CGEventSource eventSource) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - extern static CGEventType CGEventGetType (IntPtr handle); + extern static CGEventType CGEventGetType (IntPtr handle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSetType (IntPtr handle, CGEventType evtType); - + public CGEventType EventType { get { return CGEventGetType (Handle); @@ -497,7 +497,7 @@ public CGEventType EventType { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSetTimestamp (IntPtr handle, ulong timeStampp); - + #if !NET [Obsolete ("Use 'Timestamp' instead.")] public ulong Timestampe { @@ -547,15 +547,15 @@ public static bool IsTapEnabled (CFMachPort machPort) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - unsafe extern static void CGEventKeyboardGetUnicodeString (IntPtr handle, nuint maxLen, nuint* actualLen, ushort* buffer); + unsafe extern static void CGEventKeyboardGetUnicodeString (IntPtr handle, nuint maxLen, nuint* actualLen, ushort *buffer); public unsafe string GetUnicodeString () { const int bufferLength = 40; - ushort* buffer = stackalloc ushort [bufferLength]; + ushort *buffer = stackalloc ushort [bufferLength]; nuint actual = 0; CGEventKeyboardGetUnicodeString (Handle, bufferLength, &actual, buffer); - return new String ((char*) buffer, 0, (int) actual); + return new String ((char *) buffer, 0, (int) actual); } #if NET @@ -585,10 +585,10 @@ public static void TapPostEven (IntPtr tapProxyEvent, CGEvent evt) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventTapPostEvent (tapProxyEvent, evt.Handle); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventPost (CGEventTapLocation location, IntPtr handle); @@ -596,7 +596,7 @@ public static void Post (CGEvent evt, CGEventTapLocation location) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventPost (location, evt.Handle); } @@ -609,7 +609,7 @@ public static void PostToPSN (CGEvent evt, IntPtr processSerialNumber) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventPostToPSN (processSerialNumber, evt.Handle); } @@ -637,11 +637,11 @@ public void PostToPid (int pid) { PostToPid (this, pid); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] unsafe extern static int /* CGError = int32_t */ CGGetEventTapList ( uint /* uint32_t */ maxNumberOfTaps, - CGEventTapInformation* tapList, + CGEventTapInformation *tapList, uint* /* uint32_t* */ eventTapCount); public unsafe CGEventTapInformation []? GetEventTapList () @@ -650,7 +650,7 @@ public void PostToPid (int pid) if (CGGetEventTapList (0, null, &count) != 0) return null; var result = new CGEventTapInformation [count]; - fixed (CGEventTapInformation* p = result) { + fixed (CGEventTapInformation *p = result){ if (CGGetEventTapList (count, p, &count) != 0) return null; } @@ -674,7 +674,7 @@ public void PostToPid (int pid) [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] #endif - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGRequestListenEventAccess")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGRequestListenEventAccess")] static extern byte CGRequestListenEventAccess (); #if NET diff --git a/src/CoreGraphics/CGEventSource.cs b/src/CoreGraphics/CGEventSource.cs index e0e6f0e35fcf..44e47bbcb81f 100644 --- a/src/CoreGraphics/CGEventSource.cs +++ b/src/CoreGraphics/CGEventSource.cs @@ -50,7 +50,7 @@ public CGEventSource (NativeHandle handle, bool owns) [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventSourceCreate (CGEventSourceStateID stateID); - + public CGEventSource (CGEventSourceStateID stateID) : base (CGEventSourceCreate (stateID), true) { @@ -62,7 +62,7 @@ public CGEventSource (CGEventSourceStateID stateID) [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetKeyboardType (IntPtr handle, int /* CGEventSourceKeyboardType = uint32_t */ keyboardType); - public int KeyboardType { + public int KeyboardType { get { return CGEventSourceGetKeyboardType (Handle); } @@ -73,7 +73,7 @@ public int KeyboardType { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventSourceStateID CGEventSourceGetSourceStateID (IntPtr handle); - + public CGEventSourceStateID StateID { get { return CGEventSourceGetSourceStateID (Handle); @@ -86,7 +86,7 @@ public CGEventSourceStateID StateID { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetPixelsPerLine (IntPtr handle, double value); - + public double PixelsPerLine { get { return CGEventSourceGetPixelsPerLine (Handle); @@ -108,13 +108,13 @@ public static bool GetButtonState (CGEventSourceStateID stateID, CGMouseButton b public static bool GetKeyState (CGEventSourceStateID stateID, ushort keycode) => CGEventSourceKeyState (stateID, keycode) != 0; - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceFlagsState")] - public extern static CGEventFlags GetFlagsState (CGEventSourceStateID stateID); + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceFlagsState")] + public extern static CGEventFlags GetFlagsState (CGEventSourceStateID stateID); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceSecondsSinceLastEventType")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceSecondsSinceLastEventType")] public extern static double GetSecondsSinceLastEventType (CGEventSourceStateID stateID, CGEventType eventType); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceCounterForEventType")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceCounterForEventType")] public extern static uint /* uint32_t */ GetCounterForEventType (CGEventSourceStateID stateID, CGEventType eventType); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] @@ -140,7 +140,7 @@ public void SetLocalEventsFilterDuringSupressionState (CGEventFilterMask filter, { CGEventSourceSetLocalEventsFilterDuringSuppressionState (Handle, filter, state); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventFilterMask CGEventSourceGetLocalEventsFilterDuringSuppressionState (IntPtr handle, CGEventSuppressionState state); @@ -148,7 +148,7 @@ public CGEventFilterMask GetLocalEventsFilterDuringSupressionState (CGEventSuppr { return CGEventSourceGetLocalEventsFilterDuringSuppressionState (Handle, state); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetLocalEventsSuppressionInterval (IntPtr handle, double seconds); @@ -163,7 +163,7 @@ public double LocalEventsSupressionInterval { CGEventSourceSetLocalEventsSuppressionInterval (Handle, value); } } - + } } diff --git a/src/CoreGraphics/CGEventTypes.cs b/src/CoreGraphics/CGEventTypes.cs index 2ccc52411296..0dfe9dccc45e 100644 --- a/src/CoreGraphics/CGEventTypes.cs +++ b/src/CoreGraphics/CGEventTypes.cs @@ -56,7 +56,7 @@ public enum CGEventTapPlacement : uint { [MacCatalyst (13,1)] #endif public enum CGEventTapOptions : uint { - Default, + Default, ListenOnly, } @@ -94,22 +94,22 @@ public enum CGScrollEventUnit : uint { #endif [Flags] public enum CGEventMask : ulong { - Null = 0x00000001, - LeftMouseDown = 0x00000002, - LeftMouseUp = 0x00000004, - RightMouseDown = 0x00000008, - RightMouseUp = 0x00000010, - MouseMoved = 0x00000020, - LeftMouseDragged = 0x00000040, + Null = 0x00000001, + LeftMouseDown = 0x00000002, + LeftMouseUp = 0x00000004, + RightMouseDown = 0x00000008, + RightMouseUp = 0x00000010, + MouseMoved = 0x00000020, + LeftMouseDragged = 0x00000040, RightMouseDragged = 0x00000080, - KeyDown = 0x00000400, - KeyUp = 0x00000800, - FlagsChanged = 0x00001000, - ScrollWheel = 0x00400000, - TabletPointer = 0x00800000, - TabletProximity = 0x01000000, - OtherMouseDown = 0x02000000, - OtherMouseUp = 0x04000000, + KeyDown = 0x00000400, + KeyUp = 0x00000800, + FlagsChanged = 0x00001000, + ScrollWheel = 0x00400000, + TabletPointer = 0x00800000, + TabletProximity = 0x01000000, + OtherMouseDown = 0x02000000, + OtherMouseUp = 0x04000000, OtherMouseDragged = 0x08000000, } @@ -123,14 +123,14 @@ public enum CGEventMask : ulong { [Flags] public enum CGEventFlags : ulong { NonCoalesced = 0x00000100, - AlphaShift = 0x00010000, - Shift = 0x00020000, - Control = 0x00040000, - Alternate = 0x00080000, - Command = 0x00100000, - NumericPad = 0x00200000, - Help = 0x00400000, - SecondaryFn = 0x00800000, + AlphaShift = 0x00010000, + Shift = 0x00020000, + Control = 0x00040000, + Alternate = 0x00080000, + Command = 0x00100000, + NumericPad = 0x00200000, + Help = 0x00400000, + SecondaryFn = 0x00800000, } // CGEventTypes.h:typedef uint32_t CGEventField; @@ -482,7 +482,7 @@ public enum CGEventSuppressionState : int { RemoteMouseDrag, NumberOfEventSuppressionStates, } - + } #endif // MONOMAC diff --git a/src/CoreGraphics/CGImage.cs b/src/CoreGraphics/CGImage.cs index 9453ae774b20..bb0ce4fde487 100644 --- a/src/CoreGraphics/CGImage.cs +++ b/src/CoreGraphics/CGImage.cs @@ -51,12 +51,12 @@ namespace CoreGraphics { #endif [Flags] public enum CGWindowImageOption : uint { - Default = 0, + Default = 0, BoundsIgnoreFraming = (1 << 0), - ShouldBeOpaque = (1 << 1), - OnlyShadows = (1 << 2), - BestResolution = (1 << 3), - NominalResolution = (1 << 4), + ShouldBeOpaque = (1 << 1), + OnlyShadows = (1 << 2), + BestResolution = (1 << 3), + NominalResolution = (1 << 4), } // uint32_t -> CGWindow.h (OSX SDK only) @@ -68,12 +68,12 @@ public enum CGWindowImageOption : uint { #endif [Flags] public enum CGWindowListOption : uint { - All = 0, - OnScreenOnly = (1 << 0), + All = 0, + OnScreenOnly = (1 << 0), OnScreenAboveWindow = (1 << 1), OnScreenBelowWindow = (1 << 2), - IncludingWindow = (1 << 3), - ExcludeDesktopElements = (1 << 4) + IncludingWindow = (1 << 3), + ExcludeDesktopElements = (1 << 4) } #endif @@ -264,8 +264,8 @@ public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, i [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use ScreenCaptureKit instead.")] #endif [DllImport (Constants.CoreGraphicsLibrary)] - static extern IntPtr CGWindowListCreateImage (CGRect screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption); - + static extern IntPtr CGWindowListCreateImage(CGRect screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption); + #if NET [SupportedOSPlatform ("maccatalyst")] [ObsoletedOSPlatform ("maccatalyst18.0", "Use ScreenCaptureKit instead.")] diff --git a/src/CoreGraphics/CGPattern.cs b/src/CoreGraphics/CGPattern.cs index 07a187fd53f3..791131f63a40 100644 --- a/src/CoreGraphics/CGPattern.cs +++ b/src/CoreGraphics/CGPattern.cs @@ -102,8 +102,7 @@ unsafe extern static IntPtr CGPatternCreate (/* void* */ IntPtr info, CGRect bou #if NET static CGPatternCallbacks callbacks; - static CGPattern () - { + static CGPattern () { unsafe { callbacks = new CGPatternCallbacks () { version = 0, diff --git a/src/CoreGraphics/CGVector.cs b/src/CoreGraphics/CGVector.cs index 45ec779f1ca1..4972a0fcee7b 100644 --- a/src/CoreGraphics/CGVector.cs +++ b/src/CoreGraphics/CGVector.cs @@ -93,7 +93,7 @@ public override bool Equals (object? other) #endif [DllImport (Constants.UIKitLibrary)] extern static IntPtr NSStringFromCGVector (CGVector vector); - + #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -113,7 +113,7 @@ public override bool Equals (object? other) #endif [DllImport (Constants.UIKitLibrary)] extern static CGVector CGVectorFromString (IntPtr str); - + #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] diff --git a/src/CoreImage/Enums.cs b/src/CoreImage/Enums.cs index 4b5ab1a56943..60941bb22369 100644 --- a/src/CoreImage/Enums.cs +++ b/src/CoreImage/Enums.cs @@ -53,7 +53,7 @@ public enum CIFormat { #if MONOMAC RGBA16 = 2, [Obsolete ("This value can not be shared across Mac/iOS binaries, future proof with kRGBAf instead.")] - RGBAf = 3, + RGBAf = 3, // Please, do not add values into MonoMac/iOS without adding an explicit value #endif diff --git a/src/CoreLocation/CLLocationManager.cs b/src/CoreLocation/CLLocationManager.cs index 930268432daa..e3e39e3ff36a 100644 --- a/src/CoreLocation/CLLocationManager.cs +++ b/src/CoreLocation/CLLocationManager.cs @@ -45,7 +45,7 @@ public partial class CLLocationManager : NSObject { #if IOS public static bool IsMonitoringAvailable (Type t) { - if (SystemVersion.CheckiOS (7, 0)) + if (SystemVersion.CheckiOS (7,0)) return IsMonitoringAvailable (new Class (t)); return false; } diff --git a/src/CoreMedia/CMSampleBuffer.cs b/src/CoreMedia/CMSampleBuffer.cs index 5ff8c4fab453..dd2cd47b4d63 100644 --- a/src/CoreMedia/CMSampleBuffer.cs +++ b/src/CoreMedia/CMSampleBuffer.cs @@ -168,7 +168,7 @@ unsafe static extern OSStatus CMSampleBufferCreateCopyWithNewTiming ( unsafe static extern CMSampleBufferError CMSampleBufferCallForEachSample ( /* CMSampleBufferRef */ IntPtr sbuf, #if NET - delegate* unmanaged callback, + delegate* unmanaged callback, #else CMSampleBufferCallForEachSampleCallback callback, #endif @@ -678,7 +678,7 @@ public CMSampleBufferError SetInvalidateCallback (Action invalid invalidate = GCHandle.Alloc (Tuple.Create (invalidateHandler, this)); #if NET unsafe { - return CMSampleBufferSetInvalidateCallback (Handle, &InvalidateHandler, (ulong) (IntPtr) invalidate); + return CMSampleBufferSetInvalidateCallback (Handle, &InvalidateHandler, (ulong)(IntPtr)invalidate); } #else return CMSampleBufferSetInvalidateCallback (Handle, invalidate_handler, (ulong) (IntPtr) invalidate); diff --git a/src/CoreMidi/MidiBluetoothDriver.cs b/src/CoreMidi/MidiBluetoothDriver.cs index 3bc6de0f656d..f74cc15aa2b7 100644 --- a/src/CoreMidi/MidiBluetoothDriver.cs +++ b/src/CoreMidi/MidiBluetoothDriver.cs @@ -23,10 +23,10 @@ namespace CoreMidi { #if NET - [SupportedOSPlatform ("ios16.0")] - [SupportedOSPlatform ("maccatalyst16.0")] - [SupportedOSPlatform ("tvos16.0")] - [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("tvos16.0")] + [SupportedOSPlatform ("macos13.0")] #else [iOS (16, 0), Mac (13, 0), TV (16, 0), MacCatalyst (16, 0)] #endif // NET diff --git a/src/CoreServices/FSEvents.cs b/src/CoreServices/FSEvents.cs index e0a55724352d..aed8dc85b289 100644 --- a/src/CoreServices/FSEvents.cs +++ b/src/CoreServices/FSEvents.cs @@ -18,11 +18,12 @@ using CoreFoundation; using Foundation; -namespace CoreServices { +namespace CoreServices +{ // FSEvents.h: typedef UInt32 FSEventStreamCreateFlags; [Flags] public enum FSEventStreamCreateFlags : uint { - None = 0x00000000, + None = 0x00000000, /*UseCFTypes = 0x00000001,*/ NoDefer = 0x00000002, WatchRoot = 0x00000004, @@ -65,7 +66,7 @@ public enum FSEventStreamEventFlags : uint { ItemIsFile = 0x00010000, ItemIsDir = 0x00020000, ItemIsSymlink = 0x00040000, - OwnEvent = 0x00080000, + OwnEvent = 0x00080000, ItemIsHardlink = 0x00100000, ItemIsLastHardlink = 0x00200000, #if NET @@ -77,7 +78,8 @@ public enum FSEventStreamEventFlags : uint { #if NET [SupportedOSPlatform ("macos")] #endif - public struct FSEvent { + public struct FSEvent + { public ulong Id { get; internal set; } public string? Path { get; internal set; } public FSEventStreamEventFlags Flags { get; internal set; } @@ -149,7 +151,8 @@ struct FSEventStreamContext { #if NET [SupportedOSPlatform ("macos")] #endif - public sealed class FSEventStreamEventsArgs : EventArgs { + public sealed class FSEventStreamEventsArgs : EventArgs + { public FSEvent [] Events { get; private set; } internal FSEventStreamEventsArgs (FSEvent [] events) @@ -164,7 +167,8 @@ internal FSEventStreamEventsArgs (FSEvent [] events) #if NET [SupportedOSPlatform ("macos")] #endif - public sealed class FSEventStreamCreateOptions { + public sealed class FSEventStreamCreateOptions + { /// /// The allocator to use to allocate memory for the stream. If null, the default /// allocator will be used. @@ -239,7 +243,8 @@ public FSEventStreamCreateOptions (FSEventStreamCreateFlags flags, TimeSpan late #if NET [SupportedOSPlatform ("macos")] #endif - public class FSEventStream : NativeObject { + public class FSEventStream : NativeObject + { [DllImport (Constants.CoreServicesLibrary)] static extern void FSEventStreamRetain (IntPtr handle); @@ -312,7 +317,7 @@ public FSEventStream (FSEventStreamCreateOptions options) var allocator = options.Allocator.GetHandle (); var sinceWhenId = options.SinceWhenId ?? FSEvent.SinceNowId; var latency = options.Latency.TotalSeconds; - var flags = options.Flags |= (FSEventStreamCreateFlags) 0x1 /* UseCFTypes */; + var flags = options.Flags |= (FSEventStreamCreateFlags)0x1 /* UseCFTypes */; IntPtr handle; unsafe { @@ -398,7 +403,7 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, return; } - var events = new FSEvent [numEvents]; + var events = new FSEvent[numEvents]; for (int i = 0; i < events.Length; i++) { string? path = null; @@ -410,7 +415,7 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, if (eventDataType == CFStringTypeID) { path = CFString.FromHandle (eventDataHandle); } else if (eventDataType == CFDictionaryTypeID) { - path = CFString.FromHandle (CFDictionary.GetValue ( + path = CFString.FromHandle (CFDictionary.GetValue ( eventDataHandle, kFSEventStreamEventExtendedDataPathKey.Handle)); @@ -424,11 +429,12 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, } } - events [i] = new FSEvent { - Id = (ulong) Marshal.ReadInt64 (eventIds, i * 8), + events[i] = new FSEvent + { + Id = (ulong)Marshal.ReadInt64 (eventIds, i * 8), Path = path, - Flags = (FSEventStreamEventFlags) (uint) Marshal.ReadInt32 (eventFlags, i * 4), - FileId = (ulong) fileId, + Flags = (FSEventStreamEventFlags)(uint)Marshal.ReadInt32 (eventFlags, i * 4), + FileId = (ulong)fileId, }; } diff --git a/src/CoreServices/LaunchServices.cs b/src/CoreServices/LaunchServices.cs index d19a890f7423..8bc434315164 100644 --- a/src/CoreServices/LaunchServices.cs +++ b/src/CoreServices/LaunchServices.cs @@ -30,7 +30,8 @@ using Foundation; using ObjCRuntime; -namespace CoreServices { +namespace CoreServices +{ [Flags] public enum LSRoles/*Mask*/ : uint /* always 32-bit uint */ { @@ -48,7 +49,8 @@ public enum LSAcceptanceFlags : uint /* always 32-bit uint */ AllowLoginUI = 2 } - public enum LSResult { + public enum LSResult + { Success = 0, #if NET [SupportedOSPlatform ("macos13.0")] @@ -87,8 +89,9 @@ public enum LSResult { #if NET [SupportedOSPlatform ("macos")] #endif - public static class LaunchServices { - #region Locating an Application + public static class LaunchServices + { +#region Locating an Application #if NET [SupportedOSPlatform ("macos")] @@ -218,19 +221,19 @@ public static NSUrl [] GetApplicationUrlsForBundleIdentifier (string bundleIdent ); } - #endregion +#endregion - #region Opening Items +#region Opening Items [DllImport (Constants.CoreServicesLibrary)] - unsafe static extern LSResult LSOpenCFURLRef (IntPtr inUrl, void** outLaunchedUrl); + unsafe static extern LSResult LSOpenCFURLRef (IntPtr inUrl, void **outLaunchedUrl); public unsafe static LSResult Open (NSUrl url) { if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - return LSOpenCFURLRef (url.Handle, (void**) 0); + return LSOpenCFURLRef (url.Handle, (void **)0); } public unsafe static LSResult Open (NSUrl url, out NSUrl? launchedUrl) @@ -238,15 +241,15 @@ public unsafe static LSResult Open (NSUrl url, out NSUrl? launchedUrl) if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - void* launchedUrlHandle; + void *launchedUrlHandle; var result = LSOpenCFURLRef (url.Handle, &launchedUrlHandle); launchedUrl = Runtime.GetNSObject (new IntPtr (launchedUrlHandle)); return result; } - #endregion +#endregion - #region Registering an Application +#region Registering an Application [DllImport (Constants.CoreServicesLibrary)] static extern LSResult LSRegisterURL (IntPtr inUrl, byte inUpdate); @@ -256,12 +259,12 @@ public static LSResult Register (NSUrl url, bool update) if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - return LSRegisterURL (url.Handle, (byte) (update ? 1 : 0)); + return LSRegisterURL (url.Handle, (byte)(update ? 1 : 0)); } - #endregion +#endregion - #region Working with Role Handlers +#region Working with Role Handlers #if NET [SupportedOSPlatform ("macos")] @@ -278,7 +281,7 @@ public static LSResult Register (NSUrl url, bool update) #else [Deprecated (PlatformName.MacOSX, 14, 0)] #endif - public static string? []? GetAllRoleHandlersForContentType (string contentType, LSRoles roles = LSRoles.All) + public static string?[]? GetAllRoleHandlersForContentType (string contentType, LSRoles roles = LSRoles.All) { if (contentType is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (contentType)); @@ -308,7 +311,7 @@ public static string GetDefaultRoleHandlerForContentType (string contentType, LS if (contentType is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (contentType)); - return (string) Runtime.GetNSObject ( + return (string)Runtime.GetNSObject ( LSCopyDefaultRoleHandlerForContentType (new NSString (contentType).Handle, roles) ); } @@ -360,7 +363,7 @@ public static LSResult SetDefaultRoleHandlerForContentType (string contentType, #else [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'GetApplicationUrlsForUrl' instead.")] #endif - public static string? []? GetAllHandlersForUrlScheme (string urlScheme) + public static string?[]? GetAllHandlersForUrlScheme (string urlScheme) { if (urlScheme is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (urlScheme)); @@ -390,7 +393,7 @@ public static string GetDefaultHandlerForUrlScheme (string urlScheme) if (urlScheme is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (urlScheme)); - return (string) Runtime.GetNSObject ( + return (string)Runtime.GetNSObject ( LSCopyDefaultHandlerForURLScheme (new NSString (urlScheme).Handle) ); } @@ -423,7 +426,7 @@ public static LSResult SetDefaultHandlerForUrlScheme (string urlScheme, string h ); } - #endregion +#endregion } } diff --git a/src/CoreSpotlight/CSSearchableIndex.cs b/src/CoreSpotlight/CSSearchableIndex.cs index 0b0a04696d38..3886817384de 100644 --- a/src/CoreSpotlight/CSSearchableIndex.cs +++ b/src/CoreSpotlight/CSSearchableIndex.cs @@ -21,7 +21,7 @@ public partial class CSSearchableIndex { // Strongly typed version of initWithName:protectionClass: public CSSearchableIndex (string name, CSFileProtection protectionOption = CSFileProtection.None) : this (name, Translate (protectionOption)) - { } + {} static NSString? Translate (CSFileProtection protectionOption) { diff --git a/src/CoreSpotlight/CSSearchableItemAttributeSet.cs b/src/CoreSpotlight/CSSearchableItemAttributeSet.cs index 5efd455a0e95..44fc02577858 100644 --- a/src/CoreSpotlight/CSSearchableItemAttributeSet.cs +++ b/src/CoreSpotlight/CSSearchableItemAttributeSet.cs @@ -28,11 +28,10 @@ public INSSecureCoding? this [CSCustomAttributeKey key] { [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] #endif - public bool? IsUserCreated { + public bool? IsUserCreated { get { return _IsUserCreated?.BoolValue; - } - set { + } set { _IsUserCreated = value.HasValue ? new NSNumber (value.Value) : null; } } @@ -46,8 +45,7 @@ public bool? IsUserCreated { public bool? IsUserOwned { get { return _IsUserOwned?.BoolValue; - } - set { + } set { _IsUserOwned = value.HasValue ? new NSNumber (value.Value) : null; } } @@ -58,11 +56,10 @@ public bool? IsUserOwned { [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] #endif - public bool? IsUserCurated { + public bool? IsUserCurated { get { return _IsUserCurated?.BoolValue; - } - set { + } set { _IsUserCurated = value.HasValue ? new NSNumber (value.Value) : null; } } diff --git a/src/CoreText/CTFontCollection.cs b/src/CoreText/CTFontCollection.cs index c3e5dfec1c72..89154017f8f4 100644 --- a/src/CoreText/CTFontCollection.cs +++ b/src/CoreText/CTFontCollection.cs @@ -191,7 +191,7 @@ public CTFontDescriptor [] GetMatchingFontDescriptors (CTFontCollectionOptions? #if NET [DllImport (Constants.CoreTextLibrary)] static unsafe extern IntPtr CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback ( - IntPtr collection, delegate* unmanaged sortCallback, + IntPtr collection, delegate* unmanaged sortCallback, IntPtr refCon); #else [DllImport (Constants.CoreTextLibrary)] diff --git a/src/CoreText/CTFontManager.cs b/src/CoreText/CTFontManager.cs index 7fc1b47f49db..e9150b2970d3 100644 --- a/src/CoreText/CTFontManager.cs +++ b/src/CoreText/CTFontManager.cs @@ -666,7 +666,7 @@ public unsafe static void UnregisterFontDescriptors (CTFontDescriptor [] fontDes [NoTV] [NoMac] #endif - public static CTFontDescriptor []? GetRegisteredFontDescriptors (CTFontManagerScope scope, bool enabled) + public static CTFontDescriptor[]? GetRegisteredFontDescriptors (CTFontManagerScope scope, bool enabled) { var p = CTFontManagerCopyRegisteredFontDescriptors (scope, enabled.AsByte ()); // Copy/Create rule - we must release the CFArrayRef @@ -746,7 +746,7 @@ public unsafe static void UnregisterFontDescriptors (CTFontDescriptor [] fontDes [iOS (13,0)] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public unsafe static void RegisterFonts (string [] assetNames, CFBundle bundle, CTFontManagerScope scope, bool enabled, CTFontRegistrationHandler registrationHandler) + public unsafe static void RegisterFonts (string[] assetNames, CFBundle bundle, CTFontManagerScope scope, bool enabled, CTFontRegistrationHandler registrationHandler) { using (var arr = EnsureNonNullArray (assetNames, nameof (assetNames))) { if (registrationHandler is null) { @@ -774,7 +774,7 @@ public unsafe static void RegisterFonts (string [] assetNames, CFBundle bundle, [NoMac] [iOS (13,0)] #endif - public delegate void CTFontManagerRequestFontsHandler (CTFontDescriptor [] unresolvedFontDescriptors); + public delegate void CTFontManagerRequestFontsHandler (CTFontDescriptor[] unresolvedFontDescriptors); #if NET [SupportedOSPlatform ("ios13.0")] @@ -817,7 +817,7 @@ static unsafe void TrampolineRequestFonts (IntPtr block, /* CFArray */ IntPtr fo [iOS (13,0)] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public static void RequestFonts (CTFontDescriptor [] fontDescriptors, CTFontManagerRequestFontsHandler completionHandler) + public static void RequestFonts (CTFontDescriptor[] fontDescriptors, CTFontManagerRequestFontsHandler completionHandler) { if (completionHandler is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (completionHandler)); diff --git a/src/CoreVideo/CVDisplayLink.cs b/src/CoreVideo/CVDisplayLink.cs index a0572e325594..b8059e928234 100644 --- a/src/CoreVideo/CVDisplayLink.cs +++ b/src/CoreVideo/CVDisplayLink.cs @@ -47,7 +47,7 @@ namespace CoreVideo { #endif public class CVDisplayLink : NativeObject { GCHandle callbackHandle; - + #if !NET public CVDisplayLink (NativeHandle handle) : base (handle, false, true) @@ -55,7 +55,7 @@ public CVDisplayLink (NativeHandle handle) } #endif - [Preserve (Conditional = true)] + [Preserve (Conditional=true)] internal CVDisplayLink (NativeHandle handle, bool owns) : base (handle, owns) { @@ -140,7 +140,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) [NoTV] [NoMacCatalyst] #endif - public static CVDisplayLink? CreateFromDisplayIds (uint [] displayIds, out CVReturn error) + public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds, out CVReturn error) { if (displayIds is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (displayIds)); @@ -168,7 +168,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) [NoTV] [NoMacCatalyst] #endif - public static CVDisplayLink? CreateFromDisplayIds (uint [] displayIds) + public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds) => CreateFromDisplayIds (displayIds, out var _); #if NET @@ -230,7 +230,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) #endif [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRetain (IntPtr handle); - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -239,7 +239,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) #endif [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRelease (IntPtr handle); - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -265,7 +265,7 @@ protected internal override void Release () protected override void Dispose (bool disposing) { if (callbackHandle.IsAllocated) { - callbackHandle.Free (); + callbackHandle.Free(); } base.Dispose (disposing); @@ -310,7 +310,7 @@ static IntPtr Create () public CVDisplayLink () : base (Create (), true) { - } + } #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] @@ -330,8 +330,8 @@ public CVDisplayLink () public CVReturn SetCurrentDisplay (int displayId) { return CVDisplayLinkSetCurrentCGDisplay (Handle, displayId); - } - + } + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -350,7 +350,7 @@ public CVReturn SetCurrentDisplay (int displayId) public CVReturn SetCurrentDisplay (CGLContext cglContext, CGLPixelFormat cglPixelFormat) { return CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext (Handle, cglContext.Handle, cglPixelFormat.Handle); - } + } #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] @@ -371,7 +371,7 @@ public int GetCurrentDisplay () { return CVDisplayLinkGetCurrentCGDisplay (Handle); } - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -390,8 +390,8 @@ public int GetCurrentDisplay () public CVReturn Start () { return CVDisplayLinkStart (Handle); - } - + } + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -410,8 +410,8 @@ public CVReturn Start () public CVReturn Stop () { return CVDisplayLinkStop (Handle); - } - + } + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -474,7 +474,7 @@ public double ActualOutputVideoRefreshPeriod { return CVDisplayLinkGetActualOutputVideoRefreshPeriod (Handle); } } - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -495,7 +495,7 @@ public bool IsRunning { return CVDisplayLinkIsRunning (Handle) != 0; } } - + #if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -516,15 +516,15 @@ public CVReturn GetCurrentTime (out CVTimeStamp outTime) CVReturn ret; outTime = default; unsafe { - ret = CVDisplayLinkGetCurrentTime (this.Handle, (CVTimeStamp*) Unsafe.AsPointer (ref outTime)); + ret = CVDisplayLinkGetCurrentTime (this.Handle, (CVTimeStamp *) Unsafe.AsPointer (ref outTime)); } - + return ret; } - - public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut); - delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext); - + + public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut); + delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext); + #if NET [UnmanagedCallersOnly] static unsafe CVReturn OutputCallback (IntPtr displayLink, CVTimeStamp* inNow, CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, IntPtr displayLinkContext) @@ -538,7 +538,7 @@ static CVReturn OutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref C { GCHandle callbackHandle = GCHandle.FromIntPtr (displayLinkContext); DisplayLinkOutputCallback func = (DisplayLinkOutputCallback) callbackHandle.Target!; - CVDisplayLink delegateDisplayLink = new CVDisplayLink (displayLink, false); + CVDisplayLink delegateDisplayLink = new CVDisplayLink(displayLink, false); #if NET return func (delegateDisplayLink, ref System.Runtime.CompilerServices.Unsafe.AsRef (inNow), @@ -553,7 +553,7 @@ ref System.Runtime.CompilerServices.Unsafe.AsRef (inOutputTime), [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] - extern static unsafe CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, delegate* unmanaged function, IntPtr userInfo); + extern static unsafe CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, delegate* unmanaged function, IntPtr userInfo); #else [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [DllImport (Constants.CoreVideoLibrary)] @@ -578,7 +578,7 @@ public CVReturn SetOutputCallback (DisplayLinkOutputCallback callback) CVReturn ret = CVDisplayLinkSetOutputCallback (this.Handle, static_OutputCallback, GCHandle.ToIntPtr (callbackHandle)); return ret; #endif - + } #if NET @@ -641,7 +641,7 @@ public static nuint GetTypeId () public bool TryTranslateTime (CVTimeStamp inTime, ref CVTimeStamp outTime) { unsafe { - return CVDisplayLinkTranslateTime (this.Handle, inTime, (CVTimeStamp*) Unsafe.AsPointer (ref outTime)) == 0; + return CVDisplayLinkTranslateTime (this.Handle, inTime, (CVTimeStamp *) Unsafe.AsPointer (ref outTime)) == 0; } } } diff --git a/src/CoreVideo/CVImageBuffer.cs b/src/CoreVideo/CVImageBuffer.cs index 1506ee1b39b8..063924e77237 100644 --- a/src/CoreVideo/CVImageBuffer.cs +++ b/src/CoreVideo/CVImageBuffer.cs @@ -95,7 +95,7 @@ public bool IsFlipped { #if MONOMAC [DllImport (Constants.CoreVideoLibrary)] extern static /* CGColorSpaceRef */ IntPtr CVImageBufferGetColorSpace (/* CVImageBufferRef */ IntPtr imageBuffer); - + #if NET [UnsupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] diff --git a/src/CoreVideo/CVPixelFormatDescription.cs b/src/CoreVideo/CVPixelFormatDescription.cs index 3c5b07b6a863..2011de0dd91c 100644 --- a/src/CoreVideo/CVPixelFormatDescription.cs +++ b/src/CoreVideo/CVPixelFormatDescription.cs @@ -329,7 +329,7 @@ public CVFillExtendedPixelsCallBackDataStruct? FillExtendedPixelsCallbackStruct unsafe { if (bytes.Length < sizeof (CVFillExtendedPixelsCallBackDataStruct)) throw new InvalidOperationException ($"The size of the callback data structure is smaller than expected (got {bytes.Length} bytes, expected at least {sizeof (CVFillExtendedPixelsCallBackDataStruct)} bytes)"); - fixed (byte* ptr = bytes) + fixed (byte *ptr = bytes) return Marshal.PtrToStructure ((IntPtr) ptr); } } diff --git a/src/Darwin/KernelNotification.cs b/src/Darwin/KernelNotification.cs index 96ebcc87bc17..74234fedb2c9 100644 --- a/src/Darwin/KernelNotification.cs +++ b/src/Darwin/KernelNotification.cs @@ -57,24 +57,24 @@ public struct KernelEvent { [Flags] public enum EventFlags : ushort { - Add = 0x0001, - Delete = 0x0002, - Enable = 0x0004, - Disable = 0x0008, - OneShot = 0x0010, - Clear = 0x0020, - Receipt = 0x0040, - Dispatch = 0x0080, - - Flag0 = 0x1000, - Flag1 = 0x2000, - SystemFlags = unchecked(0xf000), - + Add = 0x0001, + Delete = 0x0002, + Enable = 0x0004, + Disable = 0x0008, + OneShot = 0x0010, + Clear = 0x0020, + Receipt = 0x0040, + Dispatch = 0x0080, + + Flag0 = 0x1000, + Flag1 = 0x2000, + SystemFlags = unchecked (0xf000), + // Return values. - EOF = 0x8000, - Error = 0x4000, + EOF = 0x8000, + Error = 0x4000, } - + public enum EventFilter : short { Read = -1, Write = -2, @@ -88,60 +88,60 @@ public enum EventFilter : short { User = -10, VM = -11 } - + [Flags] public enum FilterFlags : uint { - ReadPoll = EventFlags.Flag0, - ReadOutOfBand = EventFlags.Flag1, - ReadLowWaterMark = 0x00000001, + ReadPoll = EventFlags.Flag0, + ReadOutOfBand = EventFlags.Flag1, + ReadLowWaterMark = 0x00000001, WriteLowWaterMark = ReadLowWaterMark, - NoteTrigger = 0x01000000, - NoteFFNop = 0x00000000, - NoteFFAnd = 0x40000000, - NoteFFOr = 0x80000000, - NoteFFCopy = 0xc0000000, - NoteFFCtrlMask = 0xc0000000, - NoteFFlagsMask = 0x00ffffff, - - VNodeDelete = 0x00000001, - VNodeWrite = 0x00000002, - VNodeExtend = 0x00000004, - VNodeAttrib = 0x00000008, - VNodeLink = 0x00000010, - VNodeRename = 0x00000020, - VNodeRevoke = 0x00000040, - VNodeNone = 0x00000080, - - ProcExit = 0x80000000, - ProcFork = 0x40000000, - ProcExec = 0x20000000, - ProcReap = 0x10000000, - ProcSignal = 0x08000000, - ProcExitStatus = 0x04000000, - ProcResourceEnd = 0x02000000, + NoteTrigger = 0x01000000, + NoteFFNop = 0x00000000, + NoteFFAnd = 0x40000000, + NoteFFOr = 0x80000000, + NoteFFCopy = 0xc0000000, + NoteFFCtrlMask = 0xc0000000, + NoteFFlagsMask = 0x00ffffff, + + VNodeDelete = 0x00000001, + VNodeWrite = 0x00000002, + VNodeExtend = 0x00000004, + VNodeAttrib = 0x00000008, + VNodeLink = 0x00000010, + VNodeRename = 0x00000020, + VNodeRevoke = 0x00000040, + VNodeNone = 0x00000080, + + ProcExit = 0x80000000, + ProcFork = 0x40000000, + ProcExec = 0x20000000, + ProcReap = 0x10000000, + ProcSignal = 0x08000000, + ProcExitStatus = 0x04000000, + ProcResourceEnd = 0x02000000, // iOS only - ProcAppactive = 0x00800000, + ProcAppactive = 0x00800000, ProcAppBackground = 0x00400000, - ProcAppNonUI = 0x00200000, - ProcAppInactive = 0x00100000, - ProcAppAllStates = 0x00f00000, + ProcAppNonUI = 0x00200000, + ProcAppInactive = 0x00100000, + ProcAppAllStates = 0x00f00000, // Masks - ProcPDataMask = 0x000fffff, - ProcControlMask = 0xfff00000, + ProcPDataMask = 0x000fffff, + ProcControlMask = 0xfff00000, - VMPressure = 0x80000000, + VMPressure = 0x80000000, VMPressureTerminate = 0x40000000, VMPressureSuddenTerminate = 0x20000000, - VMError = 0x10000000, + VMError = 0x10000000, - TimerSeconds = 0x00000001, - TimerMicroSeconds = 0x00000002, - TimerNanoSeconds = 0x00000004, - TimerAbsolute = 0x00000008, + TimerSeconds = 0x00000001, + TimerMicroSeconds = 0x00000002, + TimerNanoSeconds = 0x00000004, + TimerAbsolute = 0x00000008, } public class KernelQueue : IDisposable, INativeObject { @@ -167,19 +167,19 @@ public void Dispose () { Dispose (false); } - + protected virtual void Dispose (bool disposing) { - if (handle != -1) { + if (handle != -1){ DispatchSource.VnodeMonitor.close (handle); handle = -1; } } [DllImport (Constants.SystemLibrary)] - unsafe extern static int /* int */ kevent (int kq, KernelEvent* changeList, int /* int */ nChanges, KernelEvent* eventList, int /* int */ nEvents, TimeSpec* timeout); + unsafe extern static int /* int */ kevent (int kq, KernelEvent *changeList, int /* int */ nChanges, KernelEvent *eventList, int /* int */ nEvents, TimeSpec* timeout); - public int KEvent (KernelEvent [] changeList, KernelEvent [] eventList, TimeSpan? timeout = null) + public int KEvent (KernelEvent[] changeList, KernelEvent[] eventList, TimeSpan? timeout = null) { if (changeList is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (changeList)); @@ -196,7 +196,7 @@ public int KEvent (KernelEvent [] changeList, KernelEvent [] eventList, TimeSpan return KEvent (changeList, changeList.Length, eventList, eventList.Length, ToTimespec (timeout)); } - public unsafe int KEvent (KernelEvent [] changeList, int nChanges, KernelEvent [] eventList, int nEvents, TimeSpec? timeout = null) + public unsafe int KEvent (KernelEvent[] changeList, int nChanges, KernelEvent[] eventList, int nEvents, TimeSpec? timeout = null) { if (changeList is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (changeList)); @@ -217,15 +217,15 @@ public unsafe int KEvent (KernelEvent [] changeList, int nChanges, KernelEvent [ throw new ArgumentOutOfRangeException ("nEvents is larger than the number of elements in eventList", nameof (nEvents)); unsafe { - fixed (KernelEvent* cp = changeList) - fixed (KernelEvent* ep = eventList) { - if (timeout is null) { - return kevent (handle, cp, nChanges, ep, nEvents, null); - } else { - TimeSpec ts = timeout.Value; - return kevent (handle, cp, nChanges, ep, nEvents, &ts); + fixed (KernelEvent *cp = changeList) + fixed (KernelEvent *ep = eventList) { + if (timeout is null) { + return kevent (handle, cp, nChanges, ep, nEvents, null); + } else { + TimeSpec ts = timeout.Value; + return kevent (handle, cp, nChanges, ep, nEvents, &ts); + } } - } } } @@ -240,7 +240,7 @@ public unsafe int KEvent (KernelEvent [] changeList, int nChanges, KernelEvent [ return rv; } - // Don't worry about nullability for !NET +// Don't worry about nullability for !NET #nullable disable #if !NET [Obsolete ("Use any of the overloads that return an int to get how many events were returned from kevent.")] @@ -295,10 +295,10 @@ public bool KEvent (KernelEvent [] changeList, KernelEvent [] eventList) #endif { unsafe { - fixed (KernelEvent* cp = changeList) - fixed (KernelEvent* ep = eventList) + fixed (KernelEvent *cp = changeList) + fixed (KernelEvent *ep = eventList) #if NET - return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null); + return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null); #else return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null) != -1; #endif diff --git a/src/Darwin/SystemLog.cs b/src/Darwin/SystemLog.cs index b470534c75d7..02dcc77443e1 100644 --- a/src/Darwin/SystemLog.cs +++ b/src/Darwin/SystemLog.cs @@ -43,7 +43,7 @@ namespace Darwin { public class SystemLog : DisposableObject { static SystemLog? _default; - + public static SystemLog Default { get { if (_default is null) @@ -51,7 +51,7 @@ public static SystemLog Default { return _default!; } } - + [Flags] public enum Option { Stderr, @@ -65,10 +65,10 @@ protected override void Dispose (bool disposing) asl_close (Handle); base.Dispose (disposing); } - + [DllImport (Constants.SystemLibrary)] extern static void asl_close (IntPtr handle); - + [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_open (IntPtr ident, IntPtr facility, Option /* uint32_t */ options); @@ -89,7 +89,7 @@ static IntPtr asl_open (string ident, string facility, Option options) : base (handle, owns) { } - + public SystemLog (string ident, string facility, Option options = 0) : base ( asl_open ( @@ -110,7 +110,7 @@ static IntPtr asl_open_from_file (int /* int */ fd, string ident, string facilit using var facilityStr = new TransientString (facility); return asl_open_from_file (fd, identStr, facilityStr); } - + public SystemLog (int fileDescriptor, string ident, string facility) : base ( asl_open_from_file ( @@ -127,7 +127,7 @@ public SystemLog (int fileDescriptor, string ident, string facility) [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_remove_log_file (IntPtr handle, int /* int */ fd); - + public void AddLogFile (int descriptor) { asl_add_log_file (Handle, descriptor); @@ -159,24 +159,24 @@ public int Log (string text) { if (text is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (text)); - + return asl_log (Handle, IntPtr.Zero, text); } - + [DllImport (Constants.SystemLibrary)] extern static int asl_send (IntPtr handle, IntPtr msgHandle); - + public int Log (Message msg) { if (msg is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (msg)); - + return asl_send (Handle, msg.Handle); } [DllImport (Constants.SystemLibrary)] extern static int asl_set_filter (IntPtr handle, int /* int */ f); - + public int SetFilter (int level) { return asl_set_filter (Handle, level); @@ -187,17 +187,17 @@ public int SetFilter (int level) [DllImport (Constants.SystemLibrary)] extern static IntPtr aslresponse_next (IntPtr handle); - + [DllImport (Constants.SystemLibrary)] extern static void aslresponse_free (IntPtr handle); - + public IEnumerable Search (Message msg) { if (msg is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (msg)); var search = asl_search (Handle, msg.Handle); IntPtr mh; - + while ((mh = aslresponse_next (search)) != IntPtr.Zero) yield return new Message (mh, true); @@ -218,7 +218,7 @@ public enum Op { Suffix = 0x40, Substring = 0x60, Numeric = 0x80, - Regex = 0x100, + Regex = 0x100, Equal = 1, Greater = 2, GreaterEqual = 3, @@ -233,7 +233,7 @@ internal Message (NativeHandle handle, bool owns) : base (handle, owns) { } - + public Message (Kind kind) : base (asl_new (kind), true) { @@ -254,7 +254,7 @@ protected override void Dispose (bool disposing) [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_get (IntPtr handle, IntPtr key); - + [DllImport (Constants.SystemLibrary)] extern static int asl_set (IntPtr handle, IntPtr key, IntPtr value); @@ -276,7 +276,7 @@ public string this [string key] { [DllImport (Constants.SystemLibrary)] extern static int asl_unset (IntPtr handle, IntPtr key); - + public void Remove (string key) { if (key is null) @@ -284,7 +284,7 @@ public void Remove (string key) using var keyStr = new TransientString (key); asl_unset (Handle, keyStr); } - + #if NET [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_key (IntPtr handle, int /* uint32_t */ key); @@ -292,8 +292,8 @@ public void Remove (string key) [DllImport (Constants.SystemLibrary)] extern static string asl_key (IntPtr handle, int /* uint32_t */ key); #endif - - public string this [int key] { + + public string this [int key]{ get { #if NET return Marshal.PtrToStringAuto (asl_key (Handle, key))!; @@ -312,37 +312,37 @@ public string Host { get { return this ["Host"]; } set { this ["Host"] = value; } } - + public string Sender { get { return this ["Sender"]; } set { this ["Sender"] = value; } } - + public string Facility { get { return this ["Facility"]; } set { this ["Facility"] = value; } } - + public string PID { get { return this ["PID"]; } set { this ["PID"] = value; } } - + public string UID { get { return this ["UID"]; } set { this ["UID"] = value; } } - + public string GID { get { return this ["GID"]; } set { this ["GID"] = value; } } - + public string Level { get { return this ["Level"]; } set { this ["Level"] = value; } } - + public string Msg { get { return this ["Message"]; } set { this ["Message"] = value; } @@ -350,7 +350,7 @@ public string Msg { [DllImport (Constants.SystemLibrary)] extern static int asl_set_query (IntPtr handle, IntPtr key, IntPtr value, int /* uint32_t */ op); - + public bool SetQuery (string key, Op op, string value) { using var keyStr = new TransientString (key); diff --git a/src/FileProvider/Structs.cs b/src/FileProvider/Structs.cs index 4a4440fe3f72..8fd2a4fa59f2 100644 --- a/src/FileProvider/Structs.cs +++ b/src/FileProvider/Structs.cs @@ -23,7 +23,8 @@ namespace FileProvider { [NoMacCatalyst] #endif [StructLayout (LayoutKind.Sequential)] - public struct NSFileProviderTypeAndCreator { + public struct NSFileProviderTypeAndCreator + { public uint Type; public uint Creator; @@ -31,7 +32,7 @@ public struct NSFileProviderTypeAndCreator { public string GetTypeAsFourCC () => Runtime.ToFourCCString (Type); - public string GetCreatorAsFourCC () + public string GetCreatorAsFourCC() => Runtime.ToFourCCString (Creator); #endif } diff --git a/src/Foundation/Compat.cs b/src/Foundation/Compat.cs index d71b94b5c7d0..4173975d8cb4 100644 --- a/src/Foundation/Compat.cs +++ b/src/Foundation/Compat.cs @@ -1,5 +1,5 @@ // -// Compat.cs: Stuff we won't provide in Xamarin.iOS.dll or newer XAMCORE_* profiles +// Compat.cs: Stuff we won't provide in newer XAMCORE_* profiles // // Authors: // Sebastien Pouliot @@ -12,30 +12,6 @@ using ObjCRuntime; namespace Foundation { - -#if !NET -#if MONOMAC - public partial class NSError { - - // removed in Xcode 11 GM - [Obsolete ("This API has been removed.")] - public static NSError GetFileProviderErrorForOutOfDateItem (FileProvider.INSFileProviderItem updatedVersion) - { - return null; - } - } -#endif - - public partial class NSUserActivity { - - [Obsolete ("Use the constructor that allows you to set an activity type.")] - public NSUserActivity () - : this (String.Empty) - { - } - } -#endif // !NET - #if !XAMCORE_5_0 #if __IOS__ && !__MACCATALYST__ public partial class NSUrlConnection { diff --git a/src/Foundation/DictionaryContainer.cs b/src/Foundation/DictionaryContainer.cs index 363501052412..257afc5d5ac7 100644 --- a/src/Foundation/DictionaryContainer.cs +++ b/src/Foundation/DictionaryContainer.cs @@ -43,20 +43,14 @@ using UIKit; #endif -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace Foundation { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public abstract class DictionaryContainer { #if !COREBUILD protected DictionaryContainer () @@ -247,11 +241,7 @@ protected DictionaryContainer (NSDictionary? dictionary) return value as NSDictionary; } -#if NET protected T? GetStrongDictionary<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (NSString key) -#else - protected T? GetStrongDictionary (NSString key) -#endif where T : DictionaryContainer { return GetStrongDictionary (key, dict => diff --git a/src/Foundation/Enum.cs b/src/Foundation/Enum.cs index 90f7c2fa9c80..1132c4afd283 100644 --- a/src/Foundation/Enum.cs +++ b/src/Foundation/Enum.cs @@ -77,16 +77,9 @@ public enum NSUrlCredentialPersistence : ulong { #if MONOMAC -#if !NET - [Native] - public enum NSBundleExecutableArchitecture : long { -#else /// The bundle's architecture. - [NoiOS] - [NoTV] - [NoMacCatalyst] + [NoiOS][NoTV][NoMacCatalyst] public enum NSBundleExecutableArchitecture { -#endif I386 = 0x00000007, PPC = 0x00000012, X86_64 = 0x01000007, @@ -254,10 +247,6 @@ public enum NSCalendarUnit : ulong { public enum NSDataReadingOptions : ulong { Mapped = 1 << 0, Uncached = 1 << 1, -#if !NET - [Obsolete ("This option is unavailable.")] - Coordinated = 1 << 2, -#endif MappedAlways = 1 << 3, } @@ -594,10 +583,6 @@ public enum NSVolumeEnumerationOptions : ulong { [Flags] [Native] public enum NSDirectoryEnumerationOptions : ulong { -#if !NET - [Obsolete ("Use 'None' instead.")] - SkipsNone = 0, -#endif None = 0, SkipsSubdirectoryDescendants = 1 << 0, SkipsPackageDescendants = 1 << 1, @@ -810,10 +795,6 @@ public enum NSJsonReadingOptions : ulong { Json5Allowed = 8, [iOS (15, 0), TV (15, 0), MacCatalyst (15, 0)] TopLevelDictionaryAssumed = 16, -#if !NET - [Obsolete ("Use 'FragmentsAllowed. instead.")] - AllowFragments = FragmentsAllowed, -#endif } [Flags] @@ -891,7 +872,6 @@ public enum NSAttributedStringEnumeration : ulong { LongestEffectiveRangeNotRequired = 1 << 20, } -#if NET || !MONOMAC // macOS has defined this in AppKit as well, but starting with .NET we're going // to use this one only. [Native] @@ -907,7 +887,6 @@ public enum NSUnderlineStyle : long { PatternDashDotDot = 0x0400, ByWord = 0x8000, } -#endif // There's an AppKit.NSWritingDirection, which is deprecated. // There's also an UIKit.UITextWritingDirection, which is deprecated too. @@ -979,17 +958,6 @@ public enum NSLigatureType : long { All, } -#if !NET - [Flags] - [Native] - public enum NSDateComponentsWrappingBehavior : ulong { - None = 0, - WrapCalendarComponents = 1 << 0, - - // Did not add the new enums here, we moved them elsewhere, and provided overloads. - } -#endif - [Flags] [Native] public enum NSCalendarOptions : ulong { diff --git a/src/Foundation/LinkerSafeAttribute.cs b/src/Foundation/LinkerSafeAttribute.cs index f2260de1d86c..41e3b493a8d5 100644 --- a/src/Foundation/LinkerSafeAttribute.cs +++ b/src/Foundation/LinkerSafeAttribute.cs @@ -29,10 +29,8 @@ namespace Foundation { -#if NET [Obsolete ("Replace with '[assembly: System.Reflection.AssemblyMetadata (\"IsTrimmable\", \"True\")]'.")] [EditorBrowsable (EditorBrowsableState.Never)] -#endif [AttributeUsage (AttributeTargets.Assembly)] public sealed class LinkerSafeAttribute : Attribute { diff --git a/src/Foundation/ModelAttribute.cs b/src/Foundation/ModelAttribute.cs index a00b71e67142..a7b0572cad53 100644 --- a/src/Foundation/ModelAttribute.cs +++ b/src/Foundation/ModelAttribute.cs @@ -32,8 +32,5 @@ public sealed class ModelAttribute : Attribute { public ModelAttribute () { } public string? Name { get; set; } -#if !NET - public bool AutoGeneratedName { get; set; } -#endif } } diff --git a/src/Foundation/MonoTouchException.cs b/src/Foundation/MonoTouchException.cs deleted file mode 100644 index 2d07d1ee6af7..000000000000 --- a/src/Foundation/MonoTouchException.cs +++ /dev/null @@ -1,72 +0,0 @@ -#if !MONOMAC && !NET - -using System; -using System.Text; - -#nullable enable - -namespace Foundation { - public class MonoTouchException : Exception { - NSException? native_exc; - - public MonoTouchException () : base () - { - native_exc = new NSException ("default", String.Empty, null); - } - - public MonoTouchException (NSException exc) : base () - { - native_exc = exc; - } - - public NSException? NSException { - get { - return native_exc; - } - } - - public string? Reason { - get { - return native_exc?.Reason; - } - } - - public string? Name { - get { - return native_exc?.Name; - } - } - - public override string Message { - get { - var sb = new StringBuilder ("Objective-C exception thrown. Name: ").Append (Name); - sb.Append (" Reason: ").AppendLine (Reason); - sb.AppendLine ("Native stack trace:"); - AppendNativeStackTrace (sb); - return sb.ToString (); - } - } - - void AppendNativeStackTrace (StringBuilder sb) - { - var callStackSymbols = native_exc?.CallStackSymbols; - if (callStackSymbols is not null) { - foreach (var symbol in callStackSymbols) - sb.Append ('\t').AppendLine (symbol); - } - } - - public override string ToString () - { - var msg = base.ToString (); - if (native_exc is null) - return msg; - - var sb = new StringBuilder (msg); - AppendNativeStackTrace (sb); - return sb.ToString (); - } - } -} - -#endif // !MONOMAC && !NET diff --git a/src/Foundation/NSAppleEventDescriptor.cs b/src/Foundation/NSAppleEventDescriptor.cs index 1943142b53b7..a4d5a8777b23 100644 --- a/src/Foundation/NSAppleEventDescriptor.cs +++ b/src/Foundation/NSAppleEventDescriptor.cs @@ -9,13 +9,15 @@ using AppKit; -namespace Foundation { +namespace Foundation +{ public enum NSAppleEventDescriptorType { Record, List, } - public partial class NSAppleEventDescriptor { + public partial class NSAppleEventDescriptor + { public NSAppleEventDescriptor (NSAppleEventDescriptorType type) { switch (type) { diff --git a/src/Foundation/NSArray.cs b/src/Foundation/NSArray.cs index b276ebb5e63d..fe122cd31608 100644 --- a/src/Foundation/NSArray.cs +++ b/src/Foundation/NSArray.cs @@ -32,10 +32,6 @@ using CoreFoundation; using ObjCRuntime; -#if !NET -using NativeHandle = System.IntPtr; -#endif - // Disable until we get around to enable + fix any issues. #nullable disable @@ -232,7 +228,6 @@ static public NSArray FromStrings (IReadOnlyList items) } } -#if NET /// Create an from the specified pointers. /// Array of pointers (to instances). /// If the array is null, an is thrown. @@ -246,7 +241,6 @@ static internal NSArray FromIntPtrs (IntPtr [] items) return Runtime.GetNSObject (NSArray.FromObjects ((IntPtr) valuesPtr, items.Length))!; } } -#endif static public NSArray FromIntPtrs (NativeHandle [] vals) { @@ -274,15 +268,7 @@ internal static nuint GetCount (IntPtr handle) internal static NativeHandle GetAtIndex (NativeHandle handle, nuint i) { -#if NET return Messaging.NativeHandle_objc_msgSend_UIntPtr (handle, Selector.GetHandle ("objectAtIndex:"), (UIntPtr) i); -#else -#if MONOMAC - return Messaging.IntPtr_objc_msgSend_UIntPtr (handle, selObjectAtIndex_XHandle, (UIntPtr) i); -#else - return Messaging.IntPtr_objc_msgSend_UIntPtr (handle, Selector.GetHandle ("objectAtIndex:"), (UIntPtr) i); -#endif -#endif } [Obsolete ("Use of 'CFArray.StringArrayFromHandle' offers better performance.")] diff --git a/src/Foundation/NSArray_1.cs b/src/Foundation/NSArray_1.cs index 4754337a7e7e..6d093768552b 100644 --- a/src/Foundation/NSArray_1.cs +++ b/src/Foundation/NSArray_1.cs @@ -17,10 +17,6 @@ using ObjCRuntime; -#if !NET -using NativeHandle = System.IntPtr; -#endif - namespace Foundation { #if false // https://github.com/xamarin/xamarin-macios/issues/15577 public delegate bool NSOrderedCollectionDifferenceEquivalenceTest (TValue? first, TValue? second); @@ -105,27 +101,15 @@ public TKey this [nint idx] { #if false // https://github.com/xamarin/xamarin-macios/issues/15577 -#if !NET - [TV (13,0), iOS (13,0)] -#else [SupportedOSPlatform ("ios13.0"), SupportedOSPlatform ("tvos13.0"), SupportedOSPlatform ("macos")] -#endif public NSOrderedCollectionDifference? GetDifference (TKey[] other, NSOrderedCollectionDifferenceCalculationOptions options) => Runtime.GetNSObject > (_GetDifference (NSArray.FromNSObjects (other), options)); -#if !NET - [TV (13,0), iOS (13,0)] -#else [SupportedOSPlatform ("ios13.0"), SupportedOSPlatform ("tvos13.0"), SupportedOSPlatform ("macos")] -#endif public NSOrderedCollectionDifference? GetDifference (TKey[] other) => Runtime.GetNSObject > (_GetDifference (NSArray.FromNSObjects (other))); -#if !NET - [TV (13,0), iOS (13,0)] -#else [SupportedOSPlatform ("ios13.0"), SupportedOSPlatform ("tvos13.0"), SupportedOSPlatform ("macos")] -#endif public TKey[]? GetArrayByApplyingDifference (NSOrderedCollectionDifference difference) => NSArray.ArrayFromHandle (_GetArrayByApplyingDifference (difference)); static readonly NSOrderedCollectionDifferenceEquivalenceTestProxy static_DiffEqualityGeneric = DiffEqualityHandlerGeneric; @@ -142,11 +126,7 @@ static bool DiffEqualityHandlerGeneric (IntPtr block, IntPtr first, IntPtr secon return false; } -#if !NET - [TV (13,0), iOS (13,0)] -#else [SupportedOSPlatform ("ios13.0"), SupportedOSPlatform ("tvos13.0"), SupportedOSPlatform ("macos")] -#endif public NSOrderedCollectionDifference? GetDifferenceFromArray (NSArray other, NSOrderedCollectionDifferenceCalculationOptions options, NSOrderedCollectionDifferenceEquivalenceTest equivalenceTest) { if (equivalenceTest is null) diff --git a/src/Foundation/NSAttributedString.cs b/src/Foundation/NSAttributedString.cs index 63c936ae8ad0..f6a40823c386 100644 --- a/src/Foundation/NSAttributedString.cs +++ b/src/Foundation/NSAttributedString.cs @@ -181,22 +181,22 @@ public partial class NSAttributedString { [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSUrl url, NSAttributedStringDocumentAttributes documentAttributes, out NSError error) - : this (url, documentAttributes, out var _, out error) { } + : this (url, documentAttributes, out var _, out error) {} [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSData data, NSAttributedStringDocumentAttributes documentAttributes, out NSError error) - : this (data, documentAttributes, out var _, out error) { } + : this (data, documentAttributes, out var _, out error) {} [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSUrl url, out NSError error) - : this (url, new NSDictionary (), out var _, out error) { } + : this (url, new NSDictionary (), out var _, out error) {} [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSData data, out NSError error) - : this (data, new NSDictionary (), out var _, out error) { } + : this (data, new NSDictionary (), out var _, out error) {} #else [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] @@ -237,7 +237,6 @@ public string? Value { return Runtime.GetNSObject (LowLevelGetAttributes (location, out effectiveRange)); } -#if NET public IntPtr LowLevelGetAttributes (nint location, out NSRange effectiveRange) { unsafe { @@ -246,7 +245,6 @@ public IntPtr LowLevelGetAttributes (nint location, out NSRange effectiveRange) } } } -#endif public NSAttributedString (string str, CTStringAttributes? attributes) : this (str, attributes?.Dictionary) diff --git a/src/Foundation/NSAttributedString.mac.cs b/src/Foundation/NSAttributedString.mac.cs index 74abe3b76959..078f350d5ca5 100644 --- a/src/Foundation/NSAttributedString.mac.cs +++ b/src/Foundation/NSAttributedString.mac.cs @@ -16,8 +16,10 @@ using WebKit; //using CoreText; -namespace Foundation { - public partial class NSAttributedString { +namespace Foundation +{ + public partial class NSAttributedString + { public NSAttributedString (string str, NSFont? font = null, NSColor? foregroundColor = null, @@ -95,11 +97,11 @@ internal NSAttributedString (NSData data, NSAttributedStringDataType type, out N Handle = InitWithRtfd (data, out resultDocumentAttributes); break; default: - throw new ArgumentException ("Error creating NSAttributedString."); + throw new ArgumentException("Error creating NSAttributedString."); } if (Handle == IntPtr.Zero) - throw new ArgumentException ("Error creating NSAttributedString."); + throw new ArgumentException("Error creating NSAttributedString."); } public static NSAttributedString CreateWithRTF (NSData rtfData, out NSDictionary resultDocumentAttributes) diff --git a/src/Foundation/NSConnection.cs b/src/Foundation/NSConnection.cs index e8cc3a5cc2fc..6b2c233a2606 100644 --- a/src/Foundation/NSConnection.cs +++ b/src/Foundation/NSConnection.cs @@ -36,8 +36,10 @@ // Disable until we get around to enable + fix any issues. #nullable disable -namespace Foundation { - public partial class NSConnection { +namespace Foundation +{ + public partial class NSConnection + { public TProxy GetRootProxy () where TProxy : NSObject { @@ -63,7 +65,7 @@ static TProxy GetRootProxy (IntPtr handle) where TProxy : NSObject var result = Runtime.TryGetNSObject (handle) as TProxy; if (result is null) - result = (TProxy) Activator.CreateInstance (typeof (TProxy), new object [] { handle }); + result = (TProxy)Activator.CreateInstance (typeof (TProxy), new object[] { handle }); return result; } diff --git a/src/Foundation/NSHost.cs b/src/Foundation/NSHost.cs index 879e2fbf496b..b410c6000d9b 100644 --- a/src/Foundation/NSHost.cs +++ b/src/Foundation/NSHost.cs @@ -17,8 +17,10 @@ using System.Collections; using System.Collections.Generic; -namespace Foundation { - public partial class NSHost : IEquatable, IEnumerable { +namespace Foundation +{ + public partial class NSHost : IEquatable, IEnumerable + { static NSHost? CheckNull (NSHost? host) { if (host is null) @@ -141,7 +143,7 @@ public IPAddress [] Addresses { public override int GetHashCode () { - return (int) _Hash; + return (int)_Hash; } public override bool Equals (object? obj) diff --git a/src/Foundation/NSIndexSet.cs b/src/Foundation/NSIndexSet.cs index 27f82b5484d5..b50df0a7b8e5 100644 --- a/src/Foundation/NSIndexSet.cs +++ b/src/Foundation/NSIndexSet.cs @@ -33,7 +33,7 @@ using ObjCRuntime; namespace Foundation { - + public partial class NSIndexSet : IEnumerable, IEnumerable { IEnumerator IEnumerable.GetEnumerator () @@ -59,8 +59,8 @@ public IEnumerator GetEnumerator () i = this.IndexGreaterThan (i); } } - - public nuint [] ToArray () + + public nuint[] ToArray () { nuint [] indexes = new nuint [Count]; @@ -75,54 +75,54 @@ public nuint [] ToArray () return indexes; } - public static NSIndexSet FromArray (nuint [] items) + public static NSIndexSet FromArray (nuint[] items) { if (items is null) return new NSIndexSet (); - - var indexSet = new NSMutableIndexSet (); - foreach (var index in items) - indexSet.Add (index); + + var indexSet = new NSMutableIndexSet(); + foreach (var index in items) + indexSet.Add (index); return indexSet; } - public static NSIndexSet FromArray (uint [] items) + public static NSIndexSet FromArray (uint[] items) { if (items is null) return new NSIndexSet (); - var indexSet = new NSMutableIndexSet (); + var indexSet = new NSMutableIndexSet(); foreach (var index in items) - indexSet.Add ((nuint) index); + indexSet.Add ((nuint)index); return indexSet; } - public static NSIndexSet FromArray (int [] items) + public static NSIndexSet FromArray (int[] items) { if (items is null) return new NSIndexSet (); - - var indexSet = new NSMutableIndexSet (); - foreach (var index in items) { + + var indexSet = new NSMutableIndexSet(); + foreach (var index in items){ if (index < 0) throw new ArgumentException ("One of the items values is negative"); - indexSet.Add ((nuint) (uint) index); + indexSet.Add ((nuint)(uint) index); } return indexSet; } - public NSIndexSet (uint value) : this ((nuint) value) + public NSIndexSet (uint value) : this ((nuint)value) { } - public NSIndexSet (nint value) : this ((nuint) value) + public NSIndexSet (nint value) : this ((nuint)value) { if (value < 0) throw new ArgumentException ("value must be positive"); // init done by the base ctor } - public NSIndexSet (int value) : this ((nuint) (uint) value) + public NSIndexSet (int value) : this ((nuint)(uint)value) { if (value < 0) throw new ArgumentException ("value must be positive"); diff --git a/src/Foundation/NSNumber.mac.cs b/src/Foundation/NSNumber.mac.cs index 4f22543ec637..1e5f80b1e701 100644 --- a/src/Foundation/NSNumber.mac.cs +++ b/src/Foundation/NSNumber.mac.cs @@ -14,33 +14,35 @@ // Disable until we get around to enable + fix any issues. #nullable disable -namespace Foundation { - public partial class NSNumber { +namespace Foundation +{ + public partial class NSNumber + { #if !COREBUILD public static NSNumber FromObject (object value) { if (value is float) { - return FromFloat ((float) value); + return FromFloat ((float)value); } else if (value is double) { - return FromDouble ((double) value); + return FromDouble ((double)value); } else if (value is sbyte) { - return FromSByte ((sbyte) value); + return FromSByte ((sbyte)value); } else if (value is byte) { - return FromByte ((byte) value); + return FromByte ((byte)value); } else if (value is short) { - return FromInt16 ((short) value); + return FromInt16 ((short)value); } else if (value is ushort) { - return FromUInt16 ((ushort) value); + return FromUInt16 ((ushort)value); } else if (value is int) { - return FromInt32 ((int) value); + return FromInt32 ((int)value); } else if (value is uint) { - return FromUInt32 ((uint) value); + return FromUInt32 ((uint)value); } else if (value is long) { - return FromInt64 ((long) value); + return FromInt64 ((long)value); } else if (value is ulong) { - return FromUInt64 ((ulong) value); + return FromUInt64 ((ulong)value); } else if (value is bool) { - return FromBoolean ((bool) value); + return FromBoolean ((bool)value); } else if (value is nint) { return FromNInt ((nint) value); } else if (value is nuint) { diff --git a/src/Foundation/NSObject.mac.cs b/src/Foundation/NSObject.mac.cs index 0b1fb0266514..0f92d00a4f34 100644 --- a/src/Foundation/NSObject.mac.cs +++ b/src/Foundation/NSObject.mac.cs @@ -100,7 +100,7 @@ public partial class NSObject { static IntPtr nl = Dlfcn.dlopen (Constants.NaturalLanguageLibrary, 1); static IntPtr vs = Dlfcn.dlopen (Constants.VideoSubscriberAccountLibrary, 1); static IntPtr un = Dlfcn.dlopen (Constants.UserNotificationsLibrary, 1); - static IntPtr il = Dlfcn.dlopen (Constants.iTunesLibraryLibrary, 1); + static IntPtr il = Dlfcn.dlopen (Constants.iTunesLibraryLibrary, 1); static IntPtr exl = Dlfcn.dlopen (Constants.ExtensionKitLibrary, 1); static IntPtr sw = Dlfcn.dlopen (Constants.SharedWithYouLibrary, 1); static IntPtr swc = Dlfcn.dlopen (Constants.SharedWithYouCoreLibrary, 1); diff --git a/src/Foundation/NSObject2.cs b/src/Foundation/NSObject2.cs index 2d7cb199aa8d..848b69e377c0 100644 --- a/src/Foundation/NSObject2.cs +++ b/src/Foundation/NSObject2.cs @@ -33,9 +33,7 @@ using System.Runtime.Versioning; using System.Diagnostics; -#if NET using System.Runtime.InteropServices.ObjectiveC; -#endif using ObjCRuntime; #if !COREBUILD @@ -47,16 +45,11 @@ using CoreGraphics; #endif -#if !NET -using NativeHandle = System.IntPtr; -#endif - // Disable until we get around to enable + fix any issues. #nullable disable namespace Foundation { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -64,15 +57,7 @@ namespace Foundation { public enum NSObjectFlag { Empty, } -#else - public class NSObjectFlag { - public static readonly NSObjectFlag Empty; - - NSObjectFlag () { } - } -#endif -#if NET // This interface will be made public when the managed static registrar is used. internal interface INSObjectFactory { // The method will be implemented via custom linker step if the managed static registrar is used @@ -80,9 +65,8 @@ internal interface INSObjectFactory { [MethodImpl (MethodImplOptions.NoInlining)] virtual static NSObject _Xamarin_ConstructNSObject (NativeHandle handle) => null; } -#endif -#if NET && !COREBUILD +#if !COREBUILD [ObjectiveCTrackedType] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -95,10 +79,7 @@ public partial class NSObject : INativeObject , IEquatable , IDisposable #endif -#if NET - , INSObjectFactory -#endif - { + , INSObjectFactory { #if !COREBUILD const string selConformsToProtocol = "conformsToProtocol:"; const string selEncodeWithCoder = "encodeWithCoder:"; @@ -114,9 +95,6 @@ public partial class NSObject : INativeObject NativeHandle handle; IntPtr super; /* objc_super* */ -#if !NET - Flags flags; -#else // See "Toggle-ref support for CoreCLR" in coreclr-bridge.m for more information. Flags actual_flags; internal unsafe Runtime.TrackedObjectInfo* tracked_object_info; @@ -137,7 +115,6 @@ unsafe Flags flags { tracked_object_info->Flags = value; } } -#endif // NET // This enum has a native counterpart in runtime.h [Flags] @@ -220,21 +197,13 @@ public NSObject (NSObjectFlag x) } [EditorBrowsable (EditorBrowsableState.Never)] -#if NET protected internal NSObject (NativeHandle handle) -#else - public NSObject (NativeHandle handle) -#endif : this (handle, false) { } [EditorBrowsable (EditorBrowsableState.Never)] -#if NET protected NSObject (NativeHandle handle, bool alloced) -#else - public NSObject (NativeHandle handle, bool alloced) -#endif { this.handle = handle; InitializeObject (alloced); @@ -251,21 +220,17 @@ public void Dispose () GC.SuppressFinalize (this); } -#if NET // This method should never be called when using the managed static registrar, so assert that never happens by throwing an exception in that case. // This method doesn't necessarily work with NativeAOT, but this is covered by the exception, because the managed static registrar is required for NativeAOT. // // IL2072: 'type' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors', 'DynamicallyAccessedMemberTypes.NonPublicConstructors' in call to 'System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(Type)'. The return value of method 'ObjCRuntime.Runtime.GetGCHandleTarget(IntPtr)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. [UnconditionalSuppressMessage ("", "IL2072", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] -#endif internal static IntPtr CreateNSObject (IntPtr type_gchandle, IntPtr handle, Flags flags) { -#if NET // Note that the code in this method doesn't necessarily work with NativeAOT, so assert that never happens by throwing an exception if using the managed static registrar (which is required for NativeAOT) if (Runtime.IsManagedStaticRegistrar) { throw new System.Diagnostics.UnreachableException (); } -#endif // This function is called from native code before any constructors have executed. var type = (Type) Runtime.GetGCHandleTarget (type_gchandle); @@ -312,33 +277,29 @@ internal static NativeHandle Initialize () return class_ptr; } -#if NET internal Flags FlagsInternal { get { return flags; } set { flags = value; } } -#endif -#if !NET || !__MACOS__ +#if !__MACOS__ [MethodImplAttribute (MethodImplOptions.InternalCall)] extern static void RegisterToggleRef (NSObject obj, IntPtr handle, bool isCustomType); -#endif // !NET || !__MACOS__ +#endif // !__MACOS__ [DllImport ("__Internal")] static extern void xamarin_release_managed_ref (IntPtr handle, byte user_type); static void RegisterToggleReference (NSObject obj, IntPtr handle, bool isCustomType) { -#if NET && __MACOS__ +#if __MACOS__ Runtime.RegisterToggleReferenceCoreCLR (obj, handle, isCustomType); -#elif NET +#else if (Runtime.IsCoreCLR) { Runtime.RegisterToggleReferenceCoreCLR (obj, handle, isCustomType); } else { RegisterToggleRef (obj, handle, isCustomType); } -#else - RegisterToggleRef (obj, handle, isCustomType); #endif } @@ -510,41 +471,24 @@ public virtual bool ConformsToProtocol (NativeHandle protocol) // the linker/trimmer will remove the following code if the dynamic registrar is removed from the app var classHandle = ClassHandle; lock (Runtime.protocol_cache) { -#if NET ref var map = ref CollectionsMarshal.GetValueRefOrAddDefault (Runtime.protocol_cache, classHandle, out var exists); if (!exists) map = new (); ref var result = ref CollectionsMarshal.GetValueRefOrAddDefault (map, protocol, out exists); if (!exists) result = DynamicConformsToProtocol (protocol); -#else - bool new_map = false; - if (!Runtime.protocol_cache.TryGetValue (classHandle, out var map)) { - map = new (); - new_map = true; - Runtime.protocol_cache.Add (classHandle, map); - } - if (new_map || !map.TryGetValue (protocol, out var result)) { - result = DynamicConformsToProtocol (protocol); - map.Add (protocol, result); - } -#endif return result; } } -#if NET // Note that this method does not work with NativeAOT, so throw an exception in that case. // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.Interfaces' in call to 'System.Type.GetInterfaces()'. The return value of method 'System.Object.GetType()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. [UnconditionalSuppressMessage ("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] -#endif bool DynamicConformsToProtocol (NativeHandle protocol) { -#if NET // Note that this method does not work with NativeAOT, so throw an exception in that case. if (Runtime.IsNativeAOT) throw Runtime.CreateNativeAOTNotSupportedException (); -#endif object [] adoptedProtocols = GetType ().GetCustomAttributes (typeof (AdoptsAttribute), true); foreach (AdoptsAttribute adopts in adoptedProtocols) { @@ -656,12 +600,10 @@ public NativeHandle Handle { handle = value; -#if NET unsafe { if (tracked_object_info is not null) tracked_object_info->Handle = value; } -#endif if (handle != IntPtr.Zero) Runtime.RegisterNSObject (this, handle); @@ -712,15 +654,7 @@ private bool AllocIfNeeded () private void InvokeOnMainThread (Selector sel, NSObject obj, bool wait) { -#if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (this.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), sel.Handle, obj.GetHandle (), wait ? (byte) 1 : (byte) 0); -#else -#if MONOMAC - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (this.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, sel.Handle, obj.GetHandle (), wait ? (byte) 1 : (byte) 0); -#else - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (this.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), sel.Handle, obj.GetHandle (), wait ? (byte) 1 : (byte) 0); -#endif -#endif } public void BeginInvokeOnMainThread (Selector sel, NSObject obj) @@ -736,70 +670,30 @@ public void InvokeOnMainThread (Selector sel, NSObject obj) public void BeginInvokeOnMainThread (Action action) { var d = new NSAsyncActionDispatcher (action); -#if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), NSDispatcher.Selector.Handle, d.Handle, 0); -#else -#if MONOMAC - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, - NSDispatcher.Selector.Handle, d.Handle, 0); -#else - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 0); -#endif -#endif } internal void BeginInvokeOnMainThread (System.Threading.SendOrPostCallback cb, object state) { var d = new NSAsyncSynchronizationContextDispatcher (cb, state); -#if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 0); -#else -#if MONOMAC - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, - NSDispatcher.Selector.Handle, d.Handle, 0); -#else - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 0); -#endif -#endif } public void InvokeOnMainThread (Action action) { using (var d = new NSActionDispatcher (action)) { -#if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); -#else -#if MONOMAC - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, - NSDispatcher.Selector.Handle, d.Handle, 1); -#else - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); -#endif -#endif } } internal void InvokeOnMainThread (System.Threading.SendOrPostCallback cb, object state) { using (var d = new NSSynchronizationContextDispatcher (cb, state)) { -#if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); -#else -#if MONOMAC - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, - NSDispatcher.Selector.Handle, d.Handle, 1); -#else - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), - Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, 1); -#endif -#endif } } @@ -883,27 +777,11 @@ public void SetValueForKeyPath (NativeHandle handle, NSString keyPath) { if (keyPath is null) throw new ArgumentNullException ("keyPath"); -#if NET if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle (this.Handle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); } else { ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_NativeHandle (this.SuperHandle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); } -#else -#if MONOMAC - if (IsDirectBinding) { - ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetValue_ForKeyPath_XHandle, handle, keyPath.Handle); - } else { - ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr (this.SuperHandle, selSetValue_ForKeyPath_XHandle, handle, keyPath.Handle); - } -#else - if (IsDirectBinding) { - ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); - } else { - ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr (this.SuperHandle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); - } -#endif -#endif } // if IsDirectBinding is false then we _likely_ have managed state and it's up to the subclass to provide @@ -1017,15 +895,7 @@ static internal void Add (NSObject handle) static void ScheduleDrain () { -#if NET Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool (class_ptr, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle ("drain:"), NativeHandle.Zero, 0); -#else -#if MONOMAC - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (class_ptr, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, drainHandle, IntPtr.Zero, 0); -#else - Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (class_ptr, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle ("drain:"), IntPtr.Zero, 0); -#endif -#endif } static bool draining; @@ -1150,12 +1020,10 @@ public static void InvokeInBackground (Action action) } #if !COREBUILD -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class NSObservedChange { NSDictionary dict; public NSObservedChange (NSDictionary source) diff --git a/src/Foundation/NSPropertyListSerialization.cs b/src/Foundation/NSPropertyListSerialization.cs index aeb80700fdc3..6b56f3612348 100644 --- a/src/Foundation/NSPropertyListSerialization.cs +++ b/src/Foundation/NSPropertyListSerialization.cs @@ -30,8 +30,10 @@ using System; -namespace Foundation { - public partial class NSPropertyListSerialization { +namespace Foundation +{ + public partial class NSPropertyListSerialization + { public static NSData DataWithPropertyList (NSObject plist, NSPropertyListFormat format, out NSError error) { return DataWithPropertyList (plist, format, NSPropertyListWriteOptions.Immutable, out error); diff --git a/src/Foundation/NSScriptCommandArgumentDescription.cs b/src/Foundation/NSScriptCommandArgumentDescription.cs index 4524945bae73..e60a43b7231d 100644 --- a/src/Foundation/NSScriptCommandArgumentDescription.cs +++ b/src/Foundation/NSScriptCommandArgumentDescription.cs @@ -30,16 +30,16 @@ public static NSString OptionalKey { public partial class NSScriptCommandArgumentDescription { public string Name { get; set; } - public bool IsOptional { + public bool IsOptional { get { return Optional is not null && Optional == "Yes"; } - set { + set { Optional = (value) ? "Yes" : "No"; } } - public NSScriptCommandArgumentDescription (string name, string eventCode, string type, bool isOptional = false) + public NSScriptCommandArgumentDescription (string name, string eventCode, string type, bool isOptional=false) { if (String.IsNullOrEmpty (name)) throw new ArgumentException ("name cannot be null or empty."); @@ -58,7 +58,7 @@ public NSScriptCommandArgumentDescription (string name, string eventCode, string } } - + #endif } diff --git a/src/Foundation/NSScriptCommandDescription.cs b/src/Foundation/NSScriptCommandDescription.cs index afa41557f905..04aaf384c62b 100644 --- a/src/Foundation/NSScriptCommandDescription.cs +++ b/src/Foundation/NSScriptCommandDescription.cs @@ -14,11 +14,11 @@ namespace Foundation { // The kyes are not found in any of the public headers from apple. That is the reason // to use this technique. static class NSScriptCommonKeys { - private static NSString appEventCode = new NSString ("AppleEventCode"); + private static NSString appEventCode = new NSString ("AppleEventCode"); public static NSString AppleEventCodeKey { get { return appEventCode; } } - + private static NSString typeKey = new NSString ("Type"); public static NSString TypeKey { get { return typeKey; } @@ -36,7 +36,7 @@ static int ToIntValue (string fourCC) int ret = 0; for (int i = 0; i < 4; i++) { ret <<= 8; - ret |= fourCC [i]; + ret |= fourCC[i]; } return ret; } @@ -63,7 +63,7 @@ public static NSScriptCommandDescription Create (string suiteName, string comman throw new ArgumentException ("eventClass must be a four characters string."); if (commandDeclaration.ResultAppleEventCode is not null && commandDeclaration.ResultAppleEventCode.Length != 4) throw new ArgumentException ("resultAppleEvent must be a four characters string."); - + using (var nsSuitName = new NSString (suiteName)) using (var nsCommandName = new NSString (commandName)) { try { @@ -96,8 +96,8 @@ public string GetTypeForArgument (string name) { if (name is null) throw new ArgumentNullException ("name"); - - using (var nsName = new NSString (name)) + + using (var nsName = new NSString(name)) using (var nsType = GetNSTypeForArgument (nsName)) { return nsType?.ToString (); } @@ -112,8 +112,8 @@ public string GetAppleEventCodeForArgument (string name) return Runtime.ToFourCCString (FCCAppleEventCodeForArgument (nsName)); } } - - public bool IsOptionalArgument (string name) + + public bool IsOptionalArgument (string name) { using (var nsName = new NSString (name)) { return NSIsOptionalArgument (nsName); diff --git a/src/Foundation/NSScriptCommandDescriptionDictionary.cs b/src/Foundation/NSScriptCommandDescriptionDictionary.cs index 55c42fd4abfc..4f140e4d110c 100644 --- a/src/Foundation/NSScriptCommandDescriptionDictionary.cs +++ b/src/Foundation/NSScriptCommandDescriptionDictionary.cs @@ -9,28 +9,28 @@ namespace Foundation { public static class NSScriptCommandDescriptionDictionaryKeys { private static NSString cmdClass = new NSString ("CommandClass"); - public static NSString CommandClassKey { + public static NSString CommandClassKey { get { return cmdClass; } } - - public static NSString AppleEventCodeKey { + + public static NSString AppleEventCodeKey { get { return NSScriptCommonKeys.AppleEventCodeKey; } } - + private static NSString codeClass = new NSString ("AppleEventClassCode"); - public static NSString AppleEventClassCodeKey { + public static NSString AppleEventClassCodeKey { get { return codeClass; } } - + public static NSString TypeKey { get { return NSScriptCommonKeys.TypeKey; } } - + private static NSString resultAppEventCode = new NSString ("ResultAppleEventCode"); - public static NSString ResultAppleEventCodeKey { + public static NSString ResultAppleEventCodeKey { get { return resultAppEventCode; } } - + private static NSString args = new NSString ("Arguments"); public static NSString ArgumentsKey { get { return args; } @@ -44,7 +44,7 @@ public void Add (NSScriptCommandArgumentDescription arg) if (arg is null) throw new ArgumentNullException ("arg"); if (Arguments is null) - Arguments = new NSMutableDictionary (); + Arguments = new NSMutableDictionary (); using (var nsName = new NSString (arg.Name)) { Arguments.Add (nsName, arg.Dictionary); } diff --git a/src/Foundation/NSSecureCoding.cs b/src/Foundation/NSSecureCoding.cs index 4d616daff386..30c523180085 100644 --- a/src/Foundation/NSSecureCoding.cs +++ b/src/Foundation/NSSecureCoding.cs @@ -28,7 +28,8 @@ public static bool SupportsSecureCoding (Type type) #if MONOMAC try { return SupportsSecureCoding (new Class (type)); - } catch (ArgumentException) { + } + catch (ArgumentException) { // unlike XI the current registration will throw for protocols // until that's fixed we'll only report correctly properly bound protocol types // the workaround is important since this method is used to validate our bindings diff --git a/src/Foundation/NSString.cs b/src/Foundation/NSString.cs index 115081a7e8ae..adde5d390fbf 100644 --- a/src/Foundation/NSString.cs +++ b/src/Foundation/NSString.cs @@ -44,11 +44,11 @@ namespace Foundation { #if COREBUILD [Protocol] - public interface INSCopying { } + public interface INSCopying {} [Protocol] - public interface INSCoding { } + public interface INSCoding {} [Protocol] - public interface INSSecureCoding { } + public interface INSSecureCoding {} #endif public partial class NSString : NSObject diff --git a/src/Foundation/NSThread.mac.cs b/src/Foundation/NSThread.mac.cs index f8b681ccf731..5bf36a09f0d1 100644 --- a/src/Foundation/NSThread.mac.cs +++ b/src/Foundation/NSThread.mac.cs @@ -10,16 +10,19 @@ using System; -namespace Foundation { - public partial class NSThread { - class ActionThread : NSThread { +namespace Foundation +{ + public partial class NSThread + { + class ActionThread : NSThread + { Action action; - + public ActionThread (Action action) { this.action = action; } - + public override void Main () { action (); diff --git a/src/Foundation/NSUrlDownload.cs b/src/Foundation/NSUrlDownload.cs index e71e7ebdfcd7..2161b97aa83f 100644 --- a/src/Foundation/NSUrlDownload.cs +++ b/src/Foundation/NSUrlDownload.cs @@ -2,7 +2,7 @@ namespace Foundation { public partial class NSUrlDownload { - + public override string ToString () { return GetType ().ToString (); diff --git a/src/Foundation/NSUrlSessionHandler.cs b/src/Foundation/NSUrlSessionHandler.cs index 126bc3b249d4..817116cb8863 100644 --- a/src/Foundation/NSUrlSessionHandler.cs +++ b/src/Foundation/NSUrlSessionHandler.cs @@ -58,9 +58,6 @@ namespace System.Net.Http { namespace Foundation { #endif -#if !NET - public delegate bool NSUrlSessionHandlerTrustOverrideCallback (NSUrlSessionHandler sender, SecTrust trust); -#endif public delegate bool NSUrlSessionHandlerTrustOverrideForUrlCallback (NSUrlSessionHandler sender, string url, SecTrust trust); // useful extensions for the class in order to set it in a header @@ -305,21 +302,6 @@ public ICredentials? Credentials { } } -#if !NET - NSUrlSessionHandlerTrustOverrideCallback? trustOverride; - - [Obsolete ("Use the 'TrustOverrideForUrl' property instead.")] - public NSUrlSessionHandlerTrustOverrideCallback? TrustOverride { - get { - return trustOverride; - } - set { - EnsureModifiability (); - trustOverride = value; - } - } -#endif - NSUrlSessionHandlerTrustOverrideForUrlCallback? trustOverrideForUrl; public NSUrlSessionHandlerTrustOverrideForUrlCallback? TrustOverrideForUrl { @@ -502,9 +484,6 @@ async Task CreateRequest (HttpRequestMessage request) return nsrequest; } -#if (SYSTEM_NET_HTTP || MONOMAC) && !NET - internal -#endif protected override async Task SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) { Volatile.Write (ref sentRequest, true); @@ -545,7 +524,6 @@ protected override async Task SendAsync (HttpRequestMessage return await inflightData.CompletionSource.Task.ConfigureAwait (false); } -#if NET // Properties that will be called by the default HttpClientHandler // NSUrlSession handler automatically handles decompression, and there doesn't seem to be a way to turn it off. @@ -804,7 +782,6 @@ public bool UseProxy { ObjCRuntime.ThrowHelper.ThrowArgumentOutOfRangeException (nameof (value), value, "It's not possible to disable the use of system proxies."); ; } } -#endif // NET partial class NSUrlSessionHandlerDelegate : NSUrlSessionDataDelegate { readonly NSUrlSessionHandler sessionHandler; @@ -1052,17 +1029,6 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl var trustCallbackForUrl = sessionHandler.TrustOverrideForUrl; var trustSec = false; var usedCallback = false; -#if !NET - var trustCallback = sessionHandler.TrustOverride; - var hasCallBack = trustCallback is not null || trustCallbackForUrl is not null; - if (hasCallBack && challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust) { - // if one of the delegates allows to ignore the cert, do it. We check first the one that takes the url because is more precisse, later the - // more general one. Since we are using nullables, if the delegate is not present, by default is false - trustSec = (trustCallbackForUrl?.Invoke (sessionHandler, inflight.RequestUrl, challenge.ProtectionSpace.ServerSecTrust) ?? false) || - (trustCallback?.Invoke (sessionHandler, challenge.ProtectionSpace.ServerSecTrust) ?? false); - usedCallback = true; - } -#else if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust) { // if the trust delegate allows to ignore the cert, do it. Since we are using nullables, if the delegate is not present, by default is false if (trustCallbackForUrl is not null) { @@ -1072,7 +1038,6 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl usedCallback = true; } } -#endif if (usedCallback) { if (trustSec) { @@ -1088,7 +1053,7 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl } return; } -#if NET + if (sessionHandler.ClientCertificateOptions == ClientCertificateOption.Manual && challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate) { var certificate = CertificateHelper.GetEligibleClientCertificate (sessionHandler.ClientCertificates); if (certificate is not null) { @@ -1099,7 +1064,6 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl return; } } -#endif // case for the basic auth failing up front. As per apple documentation: // The URL Loading System is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers using @@ -1306,9 +1270,6 @@ protected override Task SerializeToStreamAsync (Stream stream, TransportContext? return content.CopyToAsync (stream, bufferSize, cancellationToken); } -#if !NET - internal -#endif protected override bool TryComputeLength (out long length) { if (!content.CanSeek) { @@ -1564,16 +1525,9 @@ protected override bool SetCFClientFlags (CFStreamEventType inFlags, IntPtr inCa } [Preserve (Conditional = true)] -#if NET public override void Schedule (NSRunLoop aRunLoop, NSString nsMode) -#else - public override void Schedule (NSRunLoop aRunLoop, string mode) -#endif { var cfRunLoop = aRunLoop.GetCFRunLoop (); -#if !NET - var nsMode = new NSString (mode); -#endif cfRunLoop.AddSource (source, nsMode); @@ -1586,17 +1540,9 @@ public override void Schedule (NSRunLoop aRunLoop, string mode) } [Preserve (Conditional = true)] -#if NET public override void Unschedule (NSRunLoop aRunLoop, NSString nsMode) -#else - public override void Unschedule (NSRunLoop aRunLoop, string mode) -#endif { var cfRunLoop = aRunLoop.GetCFRunLoop (); -#if !NET - var nsMode = new NSString (mode); -#endif - cfRunLoop.RemoveSource (source, nsMode); } @@ -1606,7 +1552,6 @@ protected override void Dispose (bool disposing) } } -#if NET static class CertificateHelper { // Based on https://github.com/dotnet/runtime/blob/c2848c582f5d6ae42c89f5bfe0818687ab3345f0/src/libraries/Common/src/System/Net/Security/CertificateHelper.cs // with the NetEventSource code removed and namespace changed. @@ -1672,6 +1617,5 @@ static bool IsValidForDigitalSignatureUsage (X509KeyUsageExtension ku) return (ku.KeyUsages & RequiredUsages) == RequiredUsages; } } -#endif } } diff --git a/src/GameKit/GKCompat.cs b/src/GameKit/GKCompat.cs index 1a70c5f50231..0f2cadd8d4be 100644 --- a/src/GameKit/GKCompat.cs +++ b/src/GameKit/GKCompat.cs @@ -48,7 +48,8 @@ public static void DidSaveData (GKGameSession session, GKCloudPlayer player, Fou [Unavailable (PlatformName.MacOSX)] [Unavailable (PlatformName.TvOS)] #endif - public interface IGKPeerPickerControllerDelegate : INativeObject, IDisposable { + public interface IGKPeerPickerControllerDelegate : INativeObject, IDisposable + { } [EditorBrowsable (EditorBrowsableState.Never)] @@ -206,7 +207,7 @@ public virtual NSObject? WeakDelegate { protected override void Dispose (bool disposing) { - throw new PlatformNotSupportedException (Constants.TypeUnavailable); + throw new PlatformNotSupportedException (Constants.TypeUnavailable); } } /* class GKPeerPickerController */ #endif // __IOS__ || __MACCATALYST__ diff --git a/src/ImageIO/CGImageAnimation.cs b/src/ImageIO/CGImageAnimation.cs index df3743762c81..954888f9622c 100644 --- a/src/ImageIO/CGImageAnimation.cs +++ b/src/ImageIO/CGImageAnimation.cs @@ -19,20 +19,20 @@ namespace ImageIO { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public static class CGImageAnimation { public delegate void CGImageSourceAnimationHandler (nint index, CGImage image, out bool stop); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -41,10 +41,10 @@ public static class CGImageAnimation { unsafe static extern /* OSStatus */ CGImageAnimationStatus CGAnimateImageAtURLWithBlock ( /* CFURLRef */ IntPtr url, /* CFDictionaryRef _iio_Nullable */ IntPtr options, /* CGImageSourceAnimationHandler */ BlockLiteral* block); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -53,10 +53,10 @@ public static class CGImageAnimation { unsafe static extern /* OSStatus */ CGImageAnimationStatus CGAnimateImageDataWithBlock ( /* CFDataRef _Nonnull */ IntPtr data, /* CFDictionaryRef _Nullable */ IntPtr options, /* CGImageSourceAnimationHandler _Nonnull */ BlockLiteral* block); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -82,10 +82,10 @@ public static CGImageAnimationStatus AnimateImage (NSUrl url, CGImageAnimationOp } #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] diff --git a/src/Intents/INSetClimateSettingsInCarIntent.cs b/src/Intents/INSetClimateSettingsInCarIntent.cs index 69b72f2f8d6f..dc2f218e2f01 100644 --- a/src/Intents/INSetClimateSettingsInCarIntent.cs +++ b/src/Intents/INSetClimateSettingsInCarIntent.cs @@ -18,7 +18,7 @@ public partial class INSetClimateSettingsInCarIntent { [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] #endif public INSetClimateSettingsInCarIntent (bool? enableFan, bool? enableAirConditioner, bool? enableClimateControl, bool? enableAutoMode, INCarAirCirculationMode airCirculationMode, NSNumber fanSpeedIndex, NSNumber fanSpeedPercentage, INRelativeSetting relativeFanSpeedSetting, NSMeasurement temperature, INRelativeSetting relativeTemperatureSetting, INCarSeat climateZone) : - this (enableFan.HasValue ? new NSNumber (enableFan.Value) : null, enableAirConditioner.HasValue ? new NSNumber (enableAirConditioner.Value) : null, + this (enableFan.HasValue ? new NSNumber (enableFan.Value) : null, enableAirConditioner.HasValue ? new NSNumber (enableAirConditioner.Value) : null, enableClimateControl.HasValue ? new NSNumber (enableClimateControl.Value) : null, enableAutoMode.HasValue ? new NSNumber (enableAutoMode.Value) : null, airCirculationMode, fanSpeedIndex, fanSpeedPercentage, relativeFanSpeedSetting, temperature, relativeTemperatureSetting, climateZone) { diff --git a/src/Makefile b/src/Makefile index d15d03fcb9a0..c8bc8765e3e4 100644 --- a/src/Makefile +++ b/src/Makefile @@ -511,7 +511,7 @@ $(2)_DOTNET_PLATFORM_ASSEMBLY_DIR_DEPENDENCIES = \ $($(2)_DOTNET_BUILD_DIR)/ref \ ifeq ($(4),64) -PLATFORM_$(1)_CSPROJ = $(DOTNET_BUILD_DIR)/$(1)/platform/Microsoft.$(1).csproj +PLATFORM_$(1)_CSPROJ = $(DOTNET_BUILD_DIR)/$(1)/csproj/platform/Microsoft.$(1).csproj CSPROJECTS += $$(PLATFORM_$(1)_CSPROJ) $$(PLATFORM_$(1)_CSPROJ): $($(2)_DOTNET_BUILD_DIR)/Microsoft.$(1).rsp Makefile $(RSP_TO_CSPROJ) $($(2)_DOTNET_BUILD_DIR)/embed-files.rsp $$(Q) rm -f $$@ diff --git a/src/MapKit/MapKit.cs b/src/MapKit/MapKit.cs index a0f966bf0919..a5ae570ccccf 100644 --- a/src/MapKit/MapKit.cs +++ b/src/MapKit/MapKit.cs @@ -466,7 +466,7 @@ public static class MKGeometry { } #if COREBUILD - public partial class MKMapLaunchOptions : NSObject { + public partial class MKMapLaunchOptions :NSObject { } #endif } diff --git a/src/MediaExtension/MEByteSource.cs b/src/MediaExtension/MEByteSource.cs index 3a5f1ef2968e..7db378b6fbc1 100644 --- a/src/MediaExtension/MEByteSource.cs +++ b/src/MediaExtension/MEByteSource.cs @@ -12,7 +12,7 @@ public partial class MEByteSource { /// The byte array to write the data into. /// The delegate which is called when the read operation has completed. /// This overload will try to fill the byte array with data. - public void ReadData (long offset, byte [] data, MEByteSourceReadBytesCallback completionHandler) + public void ReadData (long offset, byte[] data, MEByteSourceReadBytesCallback completionHandler) { ReadData ((nuint) data.Length, offset, data, completionHandler); } @@ -22,7 +22,7 @@ public void ReadData (long offset, byte [] data, MEByteSourceReadBytesCallback c /// The offset (relative to the start of the ifle) where to start reading. /// The byte array to write the data into. /// The delegate which is called when the read operation has completed. - public void ReadData (nuint length, long offset, byte [] data, MEByteSourceReadBytesCallback completionHandler) + public void ReadData (nuint length, long offset, byte[] data, MEByteSourceReadBytesCallback completionHandler) { if (data is null) ThrowHelper.ThrowArgumentNullException (nameof (data)); @@ -44,7 +44,7 @@ public void ReadData (nuint length, long offset, byte [] data, MEByteSourceReadB /// Null if an error occurred, otherwise an instance with information about the error. The error will be if the end was reached. /// True if successful, false otherwise. /// This overload will try to fill the byte array with data. - public bool ReadData (long offset, byte [] data, out nuint bytesRead, out NSError? error) + public bool ReadData (long offset, byte[] data, out nuint bytesRead, out NSError? error) { return ReadData ((nuint) data.Length, offset, data, out bytesRead, out error); } @@ -56,7 +56,7 @@ public bool ReadData (long offset, byte [] data, out nuint bytesRead, out NSErro /// Upon return, will contain the number of read bytes. /// Null if an error occurred, otherwise an instance with information about the error. The error will be if the end was reached. /// True if successful, false otherwise. - public bool ReadData (nuint length, long offset, byte [] data, out nuint bytesRead, out NSError? error) + public bool ReadData (nuint length, long offset, byte[] data, out nuint bytesRead, out NSError? error) { if (data is null) ThrowHelper.ThrowArgumentNullException (nameof (data)); diff --git a/src/MediaExtension/MERawProcessingListParameter.cs b/src/MediaExtension/MERawProcessingListParameter.cs index c5642d5487b8..35aaba9a5026 100644 --- a/src/MediaExtension/MERawProcessingListParameter.cs +++ b/src/MediaExtension/MERawProcessingListParameter.cs @@ -23,7 +23,7 @@ public partial class MERawProcessingListParameter { /// The parameter's initial value. /// The parameter's neutral or camera value. /// Specifies whether is a neutral or a camera value. - public MERawProcessingListParameter (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralOrCameraValue, MERawProcessingListParameterInitializationOption option) + public MERawProcessingListParameter (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralOrCameraValue, MERawProcessingListParameterInitializationOption option) : base (NSObjectFlag.Empty) { switch (option) { diff --git a/src/MediaExtension/MESampleCursor.cs b/src/MediaExtension/MESampleCursor.cs index 2f610ea787a1..340ac8de24fb 100644 --- a/src/MediaExtension/MESampleCursor.cs +++ b/src/MediaExtension/MESampleCursor.cs @@ -14,7 +14,7 @@ public partial interface IMESampleCursor { /// Upon return, the exact location of the sample. /// Upon return, null if successful, otherwise an instance for the error. /// True if successful, false otherwise. - public bool RefineSampleLocation (AVSampleCursorStorageRange estimatedSampleLocation, byte [] refinementData, out AVSampleCursorStorageRange refinedLocation, out NSError? error) + public bool RefineSampleLocation (AVSampleCursorStorageRange estimatedSampleLocation, byte [] refinementData, out AVSampleCursorStorageRange refinedLocation, out NSError? error) { unsafe { fixed (byte* refinementDataPtr = refinementData) { diff --git a/src/MediaToolbox/MTAudioProcessingTap.cs b/src/MediaToolbox/MTAudioProcessingTap.cs index 9bb28c656b6b..df910cd2e4ac 100644 --- a/src/MediaToolbox/MTAudioProcessingTap.cs +++ b/src/MediaToolbox/MTAudioProcessingTap.cs @@ -44,17 +44,19 @@ using AudioToolbox; using CoreMedia; -namespace MediaToolbox { - public class MTAudioProcessingTap : NativeObject { +namespace MediaToolbox +{ + public class MTAudioProcessingTap : NativeObject + { #if !COREBUILD delegate void Action_IntPtr (IntPtr arg); // MTAudioProcessingTapCallbacks [StructLayout (LayoutKind.Sequential, Pack = 1)] - unsafe struct Callbacks { + unsafe struct Callbacks + { #pragma warning disable 169 - /* int */ - int version; // kMTAudioProcessingTapCallbacksVersion_0 == 0 + /* int */ int version; // kMTAudioProcessingTapCallbacksVersion_0 == 0 public /* void* */ IntPtr clientInfo; #if NET public /* MTAudioProcessingTapInitCallback */ delegate* unmanaged init; @@ -75,8 +77,8 @@ unsafe struct Callbacks { // MTAudioProcessingTapInitCallback unsafe delegate void MTAudioProcessingTapInitCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, /* void* */ IntPtr clientInfo, /* void** */ out void* tapStorageOut); - delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, - IntPtr numberFrames, MTAudioProcessingTapFlags flags, /* AudioBufferList* */ IntPtr bufferListInOut, + delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, + IntPtr numberFrames, MTAudioProcessingTapFlags flags, /* AudioBufferList* */ IntPtr bufferListInOut, out IntPtr numberFramesOut, out MTAudioProcessingTapFlags flagsOut); delegate void MTAudioProcessingTapPrepareCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, IntPtr maxFrames, ref AudioStreamBasicDescription processingFormat); @@ -84,10 +86,10 @@ delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapR static readonly Dictionary handles = new Dictionary (Runtime.IntPtrEqualityComparer); MTAudioProcessingTapCallbacks callbacks; - + internal static MTAudioProcessingTap? FromHandle (IntPtr handle, bool owns) { - lock (handles) { + lock (handles){ if (handles.TryGetValue (handle, out var ret)) return ret; return null; @@ -96,8 +98,8 @@ delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapR [DllImport (Constants.MediaToolboxLibrary)] unsafe extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapCreate ( - /* CFAllocatorRef*/ IntPtr allocator, - /* const MTAudioProcessingTapCallbacks* */ Callbacks* callbacks, + /* CFAllocatorRef*/ IntPtr allocator, + /* const MTAudioProcessingTapCallbacks* */ Callbacks* callbacks, MTAudioProcessingTapCreationFlags flags, /* MTAudioProcessingTapRef* */ IntPtr* tapOut); @@ -142,7 +144,7 @@ public MTAudioProcessingTap (MTAudioProcessingTapCallbacks callbacks, MTAudioPro // and that will call the InitializeProxy. So using this (short-lived) GCHandle allow us to find back the // original managed instance var gch = GCHandle.Alloc (this); - c.clientInfo = (IntPtr) gch; + c.clientInfo = (IntPtr)gch; IntPtr handle; MTAudioProcessingTapError res; @@ -181,7 +183,7 @@ protected override void Dispose (bool disposing) [DllImport (Constants.MediaToolboxLibrary)] unsafe extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapGetSourceAudio ( - /* MTAudioProcessingTapRef */ IntPtr tap, IntPtr numberFrames, + /* MTAudioProcessingTapRef */ IntPtr tap, IntPtr numberFrames, /* AudioBufferList* */ IntPtr bufferListInOut, MTAudioProcessingTapFlags* flagsOut, CMTimeRange* timeRangeOut, IntPtr* numberFramesOut); @@ -198,14 +200,14 @@ public MTAudioProcessingTapError GetSourceAudio (nint frames, AudioBuffers buffe r = MTAudioProcessingTapGetSourceAudio (Handle, (IntPtr) frames, (IntPtr) bufferList, - (MTAudioProcessingTapFlags*) Unsafe.AsPointer (ref flags), - (CMTimeRange*) Unsafe.AsPointer (ref timeRange), + (MTAudioProcessingTapFlags *) Unsafe.AsPointer (ref flags), + (CMTimeRange *) Unsafe.AsPointer (ref timeRange), &result); } framesProvided = (nint) result; return r; } - + // // Proxy callbacks @@ -220,7 +222,7 @@ unsafe static void InitializeProxy (IntPtr tap, IntPtr /*void**/ clientInfo, out #endif { #if NET - void* tempTapStorage = null; + void *tempTapStorage = null; *tapStorage = tempTapStorage; #else tapStorage = null; @@ -236,7 +238,7 @@ unsafe static void InitializeProxy (IntPtr tap, IntPtr /*void**/ clientInfo, out apt?.callbacks.Initialize (apt, out tapStorage); #endif } - } + } #if NET [UnmanagedCallersOnly] @@ -326,26 +328,30 @@ static void UnprepareProxy (IntPtr tap) // uint32_t -> MTAudioProcessingTap.h [Flags] - public enum MTAudioProcessingTapCreationFlags : uint { - PreEffects = (1 << 0), - PostEffects = (1 << 1), + public enum MTAudioProcessingTapCreationFlags : uint + { + PreEffects = (1 << 0), + PostEffects = (1 << 1), } // uint32_t -> MTAudioProcessingTap.h [Flags] - public enum MTAudioProcessingTapFlags : uint { - StartOfStream = (1 << 8), - EndOfStream = (1 << 9), + public enum MTAudioProcessingTapFlags : uint + { + StartOfStream = (1 << 8), + EndOfStream = (1 << 9), } // used as OSStatus (4 bytes) // Not documented error codes - public enum MTAudioProcessingTapError { - None = 0, - InvalidArgument = -12780 + public enum MTAudioProcessingTapError + { + None = 0, + InvalidArgument = -12780 } - public class MTAudioProcessingTapCallbacks { + public class MTAudioProcessingTapCallbacks + { public MTAudioProcessingTapCallbacks (MTAudioProcessingTapProcessDelegate process) { if (process is null) @@ -368,7 +374,7 @@ public delegate void MTAudioProcessingTapProcessDelegate (MTAudioProcessingTap t AudioBuffers bufferList, out nint numberFramesOut, out MTAudioProcessingTapFlags flagsOut); #if COREBUILD - public class AudioBufferList { } + public class AudioBufferList {} #endif } #endif // HAS_MEDIATOOLBOX diff --git a/src/Metal/Defs.cs b/src/Metal/Defs.cs index 4d01f7e01b29..e3dfdfec36aa 100644 --- a/src/Metal/Defs.cs +++ b/src/Metal/Defs.cs @@ -531,7 +531,8 @@ public partial interface IMTLTexture { [NoiOS] [NoTV] #endif - public struct MTLIndirectCommandBufferExecutionRange { + public struct MTLIndirectCommandBufferExecutionRange + { public uint Location; public uint Length; diff --git a/src/Metal/MTLArgumentEncoder.cs b/src/Metal/MTLArgumentEncoder.cs index 19eedb5c37be..021d89204685 100644 --- a/src/Metal/MTLArgumentEncoder.cs +++ b/src/Metal/MTLArgumentEncoder.cs @@ -10,14 +10,14 @@ namespace Metal { public static partial class MTLArgumentEncoder_Extensions { #if NET - public static void SetBuffers (this IMTLArgumentEncoder encoder, IMTLBuffer [] buffers, nuint [] offsets, NSRange range) + public static void SetBuffers (this IMTLArgumentEncoder encoder, IMTLBuffer[] buffers, nuint[] offsets, NSRange range) { if (buffers is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (buffers)); if (offsets is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (offsets)); - var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr [buffers.Length] : new IntPtr [buffers.Length]; + var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr[buffers.Length] : new IntPtr [buffers.Length]; // get all intptr from the array to pass to the lower level call for (var i = 0; i < buffers.Length; i++) { bufferPtrArray [i] = buffers [i].Handle; diff --git a/src/Metal/MTLArrays.cs b/src/Metal/MTLArrays.cs index 8d073882b350..0152d4b7f357 100644 --- a/src/Metal/MTLArrays.cs +++ b/src/Metal/MTLArrays.cs @@ -94,7 +94,8 @@ public MTLPipelineBufferDescriptor this [nuint index] { #if IOS public partial class MTLTileRenderPipelineColorAttachmentDescriptorArray { - public MTLTileRenderPipelineColorAttachmentDescriptor this [nuint index] { + public MTLTileRenderPipelineColorAttachmentDescriptor this [nuint index] + { get { return GetObject (index); } diff --git a/src/Metal/MTLComputeCommandEncoder.cs b/src/Metal/MTLComputeCommandEncoder.cs index ac6351703dbb..d8d38c414c1e 100644 --- a/src/Metal/MTLComputeCommandEncoder.cs +++ b/src/Metal/MTLComputeCommandEncoder.cs @@ -12,14 +12,14 @@ namespace Metal { // add some extension methods to make the API of the protocol nicer public static class IMTLComputeCommandEncoderExtensions { - public static void SetBuffers (this IMTLComputeCommandEncoder table, IMTLBuffer [] buffers, nuint [] offsets, NSRange range) + public static void SetBuffers (this IMTLComputeCommandEncoder table, IMTLBuffer[] buffers, nuint[] offsets, NSRange range) { if (buffers is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (buffers)); if (offsets is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (offsets)); - var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr [buffers.Length] : new IntPtr [buffers.Length]; + var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr[buffers.Length] : new IntPtr [buffers.Length]; // get all intptr from the array to pass to the lower level call for (var i = 0; i < buffers.Length; i++) { bufferPtrArray [i] = buffers [i].Handle; diff --git a/src/Metal/MTLRasterizationRateLayerDescriptor.cs b/src/Metal/MTLRasterizationRateLayerDescriptor.cs index ac0fb739b845..1c893a8c2682 100644 --- a/src/Metal/MTLRasterizationRateLayerDescriptor.cs +++ b/src/Metal/MTLRasterizationRateLayerDescriptor.cs @@ -9,7 +9,8 @@ #nullable enable namespace Metal { - public partial class MTLRasterizationRateLayerDescriptor { + public partial class MTLRasterizationRateLayerDescriptor + { #if NET [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("ios13.0")] @@ -18,10 +19,10 @@ public partial class MTLRasterizationRateLayerDescriptor { #else [MacCatalyst (15,0)] #endif - public double [] HorizontalSampleStorage { + public double[] HorizontalSampleStorage { get { - var width = (int) SampleCount.Width; - var floatArray = new double [width]; + var width = (int)SampleCount.Width; + var floatArray = new double[width]; Marshal.Copy (_HorizontalSampleStorage, floatArray, 0, width); return floatArray; } @@ -35,10 +36,10 @@ public double [] HorizontalSampleStorage { #else [MacCatalyst (15,0)] #endif - public double [] VerticalSampleStorage { + public double[] VerticalSampleStorage { get { - var height = (int) SampleCount.Height; - var floatArray = new double [height]; + var height = (int)SampleCount.Height; + var floatArray = new double[height]; Marshal.Copy (_VerticalSampleStorage, floatArray, 0, height); return floatArray; } @@ -52,7 +53,7 @@ public double [] VerticalSampleStorage { #else [MacCatalyst (15,0)] #endif - static public MTLRasterizationRateLayerDescriptor Create (MTLSize sampleCount, float [] horizontal, float [] vertical) + static public MTLRasterizationRateLayerDescriptor Create (MTLSize sampleCount, float[] horizontal, float[] vertical) { if (horizontal is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (horizontal)); diff --git a/src/Metal/MTLResourceStateCommandEncoder.cs b/src/Metal/MTLResourceStateCommandEncoder.cs index d79726e4ecfa..428fc8ba235b 100644 --- a/src/Metal/MTLResourceStateCommandEncoder.cs +++ b/src/Metal/MTLResourceStateCommandEncoder.cs @@ -32,7 +32,7 @@ public static partial class MTLResourceStateCommandEncoder_Extensions { [NoMac] [NoTV] #endif - public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTexture texture, MTLSparseTextureMappingMode mode, MTLRegion [] regions, nuint [] mipLevels, nuint [] slices) + public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTexture texture, MTLSparseTextureMappingMode mode, MTLRegion[] regions, nuint[] mipLevels, nuint[] slices) { if (texture is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (texture)); @@ -43,14 +43,14 @@ public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTextur if (slices is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (slices)); - var regionsHandle = GCHandle.Alloc (regions, GCHandleType.Pinned); - var mipLevelsHandle = GCHandle.Alloc (mipLevels, GCHandleType.Pinned); - var slicesHandle = GCHandle.Alloc (slices, GCHandleType.Pinned); + var regionsHandle = GCHandle.Alloc (regions, GCHandleType.Pinned); + var mipLevelsHandle = GCHandle.Alloc (mipLevels, GCHandleType.Pinned); + var slicesHandle = GCHandle.Alloc (slices, GCHandleType.Pinned); try { var regionsPtr = regionsHandle.AddrOfPinnedObject (); var mipLevelsPtr = mipLevelsHandle.AddrOfPinnedObject (); var slicesPtr = slicesHandle.AddrOfPinnedObject (); - This.Update (texture, mode, regionsPtr, mipLevelsPtr, slicesPtr, (nuint) regions.Length); + This.Update (texture, mode, regionsPtr, mipLevelsPtr, slicesPtr, (nuint)regions.Length); } finally { regionsHandle.Free (); mipLevelsHandle.Free (); diff --git a/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs b/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs index a350281ee0c4..03409a877687 100644 --- a/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs +++ b/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs @@ -12,10 +12,10 @@ namespace MetalPerformanceShadersGraph { /// This enum is used to select how to initialize a new instance of a . #if NET - [SupportedOSPlatform ("ios17.0")] - [SupportedOSPlatform ("maccatalyst17.0")] - [SupportedOSPlatform ("macos14.0")] - [SupportedOSPlatform ("tvos17.0")] + [SupportedOSPlatform ("ios17.0")] + [SupportedOSPlatform ("maccatalyst17.0")] + [SupportedOSPlatform ("macos14.0")] + [SupportedOSPlatform ("tvos17.0")] #else [TV (17, 0), Mac (14, 0), iOS (17, 0), MacCatalyst (17, 0)] #endif diff --git a/src/MetricKit/MXMetaData.cs b/src/MetricKit/MXMetaData.cs index e0df3dcfdecc..38ab71eda339 100644 --- a/src/MetricKit/MXMetaData.cs +++ b/src/MetricKit/MXMetaData.cs @@ -22,7 +22,7 @@ public partial class MXMetaData { #endif public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14, 0)) + if (SystemVersion.CheckiOS (14,0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/MetricKit/MXMetric.cs b/src/MetricKit/MXMetric.cs index 342b2ef0fb04..1aa2230fe4fd 100644 --- a/src/MetricKit/MXMetric.cs +++ b/src/MetricKit/MXMetric.cs @@ -14,7 +14,7 @@ public partial class MXMetric { public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14, 0)) + if (SystemVersion.CheckiOS (14,0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/MetricKit/MXMetricPayload.cs b/src/MetricKit/MXMetricPayload.cs index bc4d54a1a0fa..567f5b71f77b 100644 --- a/src/MetricKit/MXMetricPayload.cs +++ b/src/MetricKit/MXMetricPayload.cs @@ -14,7 +14,7 @@ public partial class MXMetricPayload { public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14, 0)) + if (SystemVersion.CheckiOS (14,0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs b/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs index a207c9d05efa..01d69a593730 100644 --- a/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs +++ b/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs @@ -22,7 +22,8 @@ #endif namespace NearbyInteraction { - public partial class NIAlgorithmConvergenceStatusReasonValues { + public partial class NIAlgorithmConvergenceStatusReasonValues + { #if NET [SupportedOSPlatform ("ios16.0")] [SupportedOSPlatform ("maccatalyst16.0")] diff --git a/src/NearbyInteraction/NINearbyObject.cs b/src/NearbyInteraction/NINearbyObject.cs index 658e36c83126..18f691c36940 100644 --- a/src/NearbyInteraction/NINearbyObject.cs +++ b/src/NearbyInteraction/NINearbyObject.cs @@ -25,21 +25,22 @@ #if __IOS__ namespace NearbyInteraction { - partial class NINearbyObject { + partial class NINearbyObject + { static Vector3? _DirectionNotAvailable; // TODO: https://github.com/xamarin/maccore/issues/2274 // We do not have generator support to trampoline Vector3 -> vector_float3 for Fields - [Field ("NINearbyObjectDirectionNotAvailable", "NearbyInteraction")] + [Field ("NINearbyObjectDirectionNotAvailable", "NearbyInteraction")] public static Vector3 DirectionNotAvailable { get { if (_DirectionNotAvailable is null) { unsafe { - Vector3* pointer = (Vector3*) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectDirectionNotAvailable"); + Vector3 *pointer = (Vector3 *) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectDirectionNotAvailable"); _DirectionNotAvailable = *pointer; } } - return (Vector3) _DirectionNotAvailable; + return (Vector3)_DirectionNotAvailable; } } @@ -54,18 +55,18 @@ public static Vector3 DirectionNotAvailable { [iOS (16,0), MacCatalyst (16,0)] #endif // NET // Following similar strategy found here: https://github.com/xamarin/maccore/issues/2274 - [Field ("NINearbyObjectWorldTransformNotAvailable", "NearbyInteraction")] + [Field ("NINearbyObjectWorldTransformNotAvailable", "NearbyInteraction")] public static MatrixFloat4x4 WorldTransformNotAvailable { get { if (_WorldTransformNotAvailable is null) { unsafe { - MatrixFloat4x4* pointer = (MatrixFloat4x4*) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectWorldTransformNotAvailable"); + MatrixFloat4x4 *pointer = (MatrixFloat4x4 *) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectWorldTransformNotAvailable"); if (pointer is null) throw new PlatformNotSupportedException ("This property is not supported on this version of the OS"); _WorldTransformNotAvailable = *pointer; } } - return (MatrixFloat4x4) _WorldTransformNotAvailable; + return (MatrixFloat4x4)_WorldTransformNotAvailable; } } } diff --git a/src/Network/NWConnection.cs b/src/Network/NWConnection.cs index 21677dfbdd19..5fd4ce6c4ad2 100644 --- a/src/Network/NWConnection.cs +++ b/src/Network/NWConnection.cs @@ -55,7 +55,7 @@ namespace Network { public class NWConnection : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWConnection (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWConnection (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWConnection (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWConnectionGroup.cs b/src/Network/NWConnectionGroup.cs index 893b191e7af3..e2388e91882b 100644 --- a/src/Network/NWConnectionGroup.cs +++ b/src/Network/NWConnectionGroup.cs @@ -298,7 +298,7 @@ public void SetStateChangedHandler (NWConnectionGroupStateChangedDelegate handle } #if NET - delegate* unmanaged trampoline = &TrampolineStateChangedHandler; + delegate* unmanaged trampoline= &TrampolineStateChangedHandler; using var block = new BlockLiteral (trampoline, handler, typeof (NWConnectionGroup), nameof (TrampolineStateChangedHandler)); #else using var block = new BlockLiteral (); diff --git a/src/Network/NWEndpoint.cs b/src/Network/NWEndpoint.cs index 1f2298edbd08..ccb21c14341a 100644 --- a/src/Network/NWEndpoint.cs +++ b/src/Network/NWEndpoint.cs @@ -35,7 +35,7 @@ namespace Network { public class NWEndpoint : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWEstablishmentReport.cs b/src/Network/NWEstablishmentReport.cs index 6fa5da127fec..f04b6fcb2a6d 100644 --- a/src/Network/NWEstablishmentReport.cs +++ b/src/Network/NWEstablishmentReport.cs @@ -98,7 +98,7 @@ public void EnumerateResolutions (Action trampoline = &TrampolineResolutionEnumeratorHandler; - using var block = new BlockLiteral (trampoline, handler, typeof (NWEstablishmentReport), nameof (TrampolineResolutionEnumeratorHandler)); + using var block = new BlockLiteral (trampoline, handler, typeof (NWEstablishmentReport),nameof (TrampolineResolutionEnumeratorHandler)); #else using var block = new BlockLiteral (); block.SetupBlockUnsafe (static_ResolutionEnumeratorHandler, handler); diff --git a/src/Network/NWEthernetChannel.cs b/src/Network/NWEthernetChannel.cs index c761c8ea0668..1011665380b6 100644 --- a/src/Network/NWEthernetChannel.cs +++ b/src/Network/NWEthernetChannel.cs @@ -18,10 +18,10 @@ using Foundation; using CoreFoundation; -using OS_nw_ethernet_channel = System.IntPtr; -using OS_nw_interface = System.IntPtr; -using OS_dispatch_data = System.IntPtr; -using OS_nw_parameters = System.IntPtr; +using OS_nw_ethernet_channel=System.IntPtr; +using OS_nw_interface=System.IntPtr; +using OS_dispatch_data=System.IntPtr; +using OS_nw_parameters=System.IntPtr; #if !NET @@ -48,7 +48,7 @@ namespace Network { public class NWEthernetChannel : NativeObject { [Preserve (Conditional = true)] - internal NWEthernetChannel (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWEthernetChannel (NativeHandle handle, bool owns) : base (handle, owns) {} [DllImport (Constants.NetworkLibrary)] static extern OS_nw_ethernet_channel nw_ethernet_channel_create (ushort ether_type, OS_nw_interface networkInterface); @@ -89,13 +89,13 @@ public NWEthernetChannel (ushort ethernetType, NWInterface networkInterface) [Mac (13,0)] #endif public NWEthernetChannel (ushort ethernetType, NWInterface networkInterface, NWParameters parameters) => - InitializeHandle (nw_ethernet_channel_create_with_parameters (ethernetType, + InitializeHandle (nw_ethernet_channel_create_with_parameters (ethernetType, networkInterface.GetNonNullHandle (nameof (networkInterface)), parameters.GetNonNullHandle (nameof (parameters)))); [DllImport (Constants.NetworkLibrary)] static extern void nw_ethernet_channel_start (OS_nw_ethernet_channel ethernet_channel); - public void Start () => nw_ethernet_channel_start (GetCheckedHandle ()); + public void Start () => nw_ethernet_channel_start (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] static extern void nw_ethernet_channel_cancel (OS_nw_ethernet_channel ethernet_channel); @@ -160,7 +160,7 @@ public void Send (ReadOnlySpan content, ushort vlanTag, string remoteAddre } [DllImport (Constants.NetworkLibrary)] - unsafe static extern void nw_ethernet_channel_set_receive_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral* handler); + unsafe static extern void nw_ethernet_channel_set_receive_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral *handler); #if !NET delegate void nw_ethernet_channel_receive_handler_t (IntPtr block, OS_dispatch_data content, ushort vlan_tag, IntPtr local_address, IntPtr remote_address); @@ -206,7 +206,7 @@ public void SetReceiveHandler (NWEthernetChannelReceiveDelegate handler) } [DllImport (Constants.NetworkLibrary)] - unsafe static extern void nw_ethernet_channel_set_state_changed_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral* handler); + unsafe static extern void nw_ethernet_channel_set_state_changed_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral *handler); #if !NET delegate void nw_ethernet_channel_state_changed_handler_t (IntPtr block, NWEthernetChannelState state, IntPtr error); @@ -243,7 +243,7 @@ public void SetStateChangesHandler (Action handler) #endif nw_ethernet_channel_set_state_changed_handler (GetCheckedHandle (), &block); } - } + } #if NET [SupportedOSPlatform ("macos13.0")] @@ -262,7 +262,7 @@ public void SetStateChangesHandler (Action handler) #else [Mac (13,0)] #endif - public uint MaximumPayloadSize => nw_ethernet_channel_get_maximum_payload_size (GetCheckedHandle ()); + public uint MaximumPayloadSize => nw_ethernet_channel_get_maximum_payload_size (GetCheckedHandle ()); } } #endif diff --git a/src/Network/NWInterface.cs b/src/Network/NWInterface.cs index 5edce0ce0f53..b37d41851a4d 100644 --- a/src/Network/NWInterface.cs +++ b/src/Network/NWInterface.cs @@ -33,7 +33,7 @@ namespace Network { public class NWInterface : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWInterface (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWInterface (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWInterface (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWParameters.cs b/src/Network/NWParameters.cs index c12df72e7be5..5e562febdd81 100644 --- a/src/Network/NWParameters.cs +++ b/src/Network/NWParameters.cs @@ -36,7 +36,7 @@ namespace Network { public class NWParameters : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWParameters (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWParameters (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWParameters (NativeHandle handle, bool owns) : base (handle, owns) { } #endif @@ -222,7 +222,7 @@ public unsafe static NWParameters CreateUdp (Action? configur [NoiOS] #endif [DllImport (Constants.NetworkLibrary)] - unsafe static extern IntPtr nw_parameters_create_custom_ip (byte custom_ip_protocol_number, BlockLiteral* configure_ip); + unsafe static extern IntPtr nw_parameters_create_custom_ip (byte custom_ip_protocol_number, BlockLiteral *configure_ip); #if NET [SupportedOSPlatform ("macos")] diff --git a/src/Network/NWPath.cs b/src/Network/NWPath.cs index 8e8ccd3026b2..84c4e1f5595c 100644 --- a/src/Network/NWPath.cs +++ b/src/Network/NWPath.cs @@ -32,7 +32,7 @@ namespace Network { public class NWPath : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWPath (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWPath (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWPath (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWPrivacyContext.cs b/src/Network/NWPrivacyContext.cs index 8a8eb745d2a9..eef58bb15bfb 100644 --- a/src/Network/NWPrivacyContext.cs +++ b/src/Network/NWPrivacyContext.cs @@ -31,7 +31,7 @@ public class NWPrivacyContext : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolDefinition.cs b/src/Network/NWProtocolDefinition.cs index 95816b3cdda1..f96c8cccceb6 100644 --- a/src/Network/NWProtocolDefinition.cs +++ b/src/Network/NWProtocolDefinition.cs @@ -33,7 +33,7 @@ namespace Network { public class NWProtocolDefinition : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolFramerOptions.cs b/src/Network/NWProtocolFramerOptions.cs index eacf836029b3..7b49cca2d57d 100644 --- a/src/Network/NWProtocolFramerOptions.cs +++ b/src/Network/NWProtocolFramerOptions.cs @@ -22,7 +22,7 @@ using OS_nw_protocol_options = System.IntPtr; using NativeHandle = System.IntPtr; #else -using OS_nw_protocol_options = ObjCRuntime.NativeHandle; +using OS_nw_protocol_options=ObjCRuntime.NativeHandle; #endif namespace Network { diff --git a/src/Network/NWProtocolMetadata.cs b/src/Network/NWProtocolMetadata.cs index e36314084129..93dbc81c74d4 100644 --- a/src/Network/NWProtocolMetadata.cs +++ b/src/Network/NWProtocolMetadata.cs @@ -58,7 +58,7 @@ public static NWProtocolMetadata CreateUdpMetadata () [Preserve (Conditional = true)] #if NET - internal NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolOptions.cs b/src/Network/NWProtocolOptions.cs index 14c6f2692767..c3d8267019ca 100644 --- a/src/Network/NWProtocolOptions.cs +++ b/src/Network/NWProtocolOptions.cs @@ -34,7 +34,7 @@ namespace Network { public class NWProtocolOptions : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolStack.cs b/src/Network/NWProtocolStack.cs index 8aaacdab0041..d43e247558eb 100644 --- a/src/Network/NWProtocolStack.cs +++ b/src/Network/NWProtocolStack.cs @@ -36,7 +36,7 @@ namespace Network { public class NWProtocolStack : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProxyConfig.cs b/src/Network/NWProxyConfig.cs index 57a790831af6..86c631dd7b37 100644 --- a/src/Network/NWProxyConfig.cs +++ b/src/Network/NWProxyConfig.cs @@ -29,7 +29,7 @@ namespace Network { public class NWProxyConfig : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWRelayHop.cs b/src/Network/NWRelayHop.cs index c2c4018c9bb2..d56f895f324a 100644 --- a/src/Network/NWRelayHop.cs +++ b/src/Network/NWRelayHop.cs @@ -28,7 +28,7 @@ namespace Network { public class NWRelayHop : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWResolverConfig.cs b/src/Network/NWResolverConfig.cs index 247554347975..0f0b69bec429 100644 --- a/src/Network/NWResolverConfig.cs +++ b/src/Network/NWResolverConfig.cs @@ -30,7 +30,7 @@ public class NWResolverConfig : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) { } + internal NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) {} #else public NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/ObjCBindings/BindFromAttribute.cs b/src/ObjCBindings/BindFromAttribute.cs new file mode 100644 index 000000000000..ee6fe08ebc24 --- /dev/null +++ b/src/ObjCBindings/BindFromAttribute.cs @@ -0,0 +1,35 @@ +using System; +using System.Reflection; +using System.Diagnostics.CodeAnalysis; +using ObjCRuntime; + +#nullable enable + +namespace ObjCBindings { + + /// + /// Attribute to bind from a specific type. + /// + [Experimental ("APL0003")] + [AttributeUsage (AttributeTargets.ReturnValue | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)] + public class BindFromAttribute : Attribute { + + /// + /// Initializes a new instance of the class. + /// + public BindFromAttribute (Type type) + { + Type = type; + } + + /// + /// The type to bind from. + /// + public Type Type { get; set; } + + /// + /// The original type that was bound from. + /// + public Type? OriginalType { get; set; } = null; + } +} diff --git a/src/ObjCBindings/BindingTypeAttribute.cs b/src/ObjCBindings/BindingTypeAttribute.cs index 79f2f7499385..b9c6934b2714 100644 --- a/src/ObjCBindings/BindingTypeAttribute.cs +++ b/src/ObjCBindings/BindingTypeAttribute.cs @@ -37,5 +37,50 @@ public class BindingTypeAttribute : Attribute where T : Enum { /// Get/Set the export configuration flags. /// public T? Flags { get; set; } = default (T); + + /// + /// Get/set the visibility of the default constructor for a core image filter. + /// + public MethodAttributes DefaultCtorVisibility { get; set; } + + /// + /// Get/set the visibility of the IntPtr constructor for a core image filter. + /// + public MethodAttributes IntPtrCtorVisibility { get; set; } + + /// + ///Get/set the visibility of the string constructor for a core image filter. + /// + public MethodAttributes StringCtorVisibility { get; set; } + + /// + /// Creates a binding type attribute with the default flag value; + /// + public BindingTypeAttribute () { } + + /// + /// Creates a binding type attribute with the specified flags. + /// + public BindingTypeAttribute (T flags) + { + Flags = flags; + } + + /// + /// Creates a binding type attribute with the specified flags. + /// + public BindingTypeAttribute (string name) + { + Name = name; + } + + /// + /// Creates a binding type attribute with the specified flags. + /// + public BindingTypeAttribute (string name, T flags) + { + Name = name; + Flags = flags; + } } } diff --git a/src/ObjCBindings/BindingTypeTag.cs b/src/ObjCBindings/BindingTypeTag.cs index aeb3d3734955..de7a598cee79 100644 --- a/src/ObjCBindings/BindingTypeTag.cs +++ b/src/ObjCBindings/BindingTypeTag.cs @@ -20,6 +20,11 @@ public enum Class : Int64 { /// Use to let the generator know that the default constructor should not be generated. /// DisableDefaultCtor = 1 << 2, + + /// + /// Flags the object as being thread safe. + /// + IsThreadSafe = 1 << 3, } /// @@ -32,6 +37,11 @@ public enum Protocol : Int64 { /// Use the default values. /// Default = 0, + + /// + /// Flags the object as being thread safe. + /// + IsThreadSafe = 1 << 2, } /// @@ -44,6 +54,11 @@ public enum Category : Int64 { /// Use the default values. /// Default = 0, + + /// + /// Flags the object as being thread safe. + /// + IsThreadSafe = 1 << 2, } /// @@ -57,4 +72,16 @@ public enum StrongDictionary : Int64 { /// Default = 0, } + + /// + /// Flags to be used on core image filter bindings. + /// + [Flags] + [Experimental ("APL0003")] + public enum CoreImageFilter : Int64 { + /// + /// Use the default values. + /// + Default = 0, + } } diff --git a/src/ObjCBindings/ExportAttribute.cs b/src/ObjCBindings/ExportAttribute.cs index 147ee0ffce15..ab68597a9b4f 100644 --- a/src/ObjCBindings/ExportAttribute.cs +++ b/src/ObjCBindings/ExportAttribute.cs @@ -27,6 +27,45 @@ public class ExportAttribute : Attribute where T : Enum { /// public ArgumentSemantic ArgumentSemantic { get; set; } = ArgumentSemantic.None; + /// + /// Get/Set the native prefix to be used in the custom marshal directive. + /// + /// The generator will only respect this value if the CustomMarshalDirective flag is set. + /// If the flag is not set the analyzer will raise an compiling error. + /// + public string? NativePrefix { get; set; } = null; + + /// + /// Get/Set the native suffix to be used in the custom marshal directive. + /// + /// The generator will only respect this value if the CustomMarshalDirective flag is set. + /// If the flag is not set the analyzer will raise an compiling error. + /// + public string? NativeSuffix { get; set; } = null; + + /// + /// Get/Set the library to be used in the custom marshal directive. + /// + /// The generator will only respect this value if the CustomMarshalDirective flag is set. + /// If the flag is not set the analyzer will raise an compiling error. + /// + public string? Library { get; set; } = null; + + /// + /// + /// + public MethodAttributes DefaultCtorVisibility { get; set; } + + /// + /// + /// + public MethodAttributes IntPtrCtorVisibility { get; set; } + + /// + /// + /// + public MethodAttributes StringCtorVisibility { get; set; } + protected ExportAttribute () { } /// diff --git a/src/ObjCBindings/ExportTag.cs b/src/ObjCBindings/ExportTag.cs index fdc91745bfe9..acf65e9633cc 100644 --- a/src/ObjCBindings/ExportTag.cs +++ b/src/ObjCBindings/ExportTag.cs @@ -20,6 +20,17 @@ public enum Constructor : Int64 { /// Map to Objective-C/clang use of __attribute__((objc_designated_initializer)). /// DesignatedInitializer = 1 << 2, + + /// + /// Flags the object as being thread safe. + /// + IsThreadSafe = 1 << 3, + + /// + /// If this flag is applied to a property, we do not generate a NSString for + /// marshalling the property. + /// + PlainString = 1 << 4, } /// @@ -49,6 +60,31 @@ public enum Method : Int64 { /// MarshalNativeExceptions = 1 << 4, + + /// + /// Instruct the generator to use a custom marshal directive for the method. When this flag is applied the + /// following name parameters must be provided: + /// - NativePrefix: The prefix to be used in the native method name. + /// - NativeSuffix: The suffix to be used in the native method name. + /// - Library: The library to be used in the custom marshal directive. + /// + CustomMarshalDirective = 1 << 5, + + /// + /// Flags the object as being thread safe. + /// + IsThreadSafe = 1 << 6, + + /// + /// If this flag is applied to a property, we do not generate a NSString for + /// marshalling the property. + /// + PlainString = 1 << 7, + + /// + /// Use this flag on method to wrap the invocation in a NSAutoReleasePool. + /// + AutoRelease = 1 << 8, } /// @@ -71,6 +107,66 @@ public enum Property : Int64 { /// Generate a notification for the property. /// Notification = 1 << 3, + + /// + /// Make a method support native (Objective-C) exceptions. Instead of calling objc_msgSend directly, the invocation + /// will go through a custom trampoline which catches ObjectiveC exceptions and marshals them into managed exceptions. + /// + MarshalNativeExceptions = 1 << 4, + + /// + /// Instruct the generator to use a custom marshal directive for the method. When this flag is applied the + /// following name parameters must be provided: + /// - NativePrefix: The prefix to be used in the native method name. + /// - NativeSuffix: The suffix to be used in the native method name. + /// - Library: The library to be used in the custom marshal directive. + /// + CustomMarshalDirective = 1 << 5, + + /// + /// Apply to strings parameters that are merely retained or assigned, + /// not copied this is an exception as it is advised in the coding + /// standard for Objective-C to avoid this, but a few properties do use + /// this. Use this falg for properties flagged with `retain' or + /// `assign', which look like this: + /// + /// @property (retain) NSString foo; + /// @property (assign) NSString assigned; + /// + /// This forced the generator to create an NSString before calling the + /// API instead of using the fast string marshalling code. + /// + DisableZeroCopy = 1 << 6, + + /// + /// Flags the object as being thread safe. + /// + IsThreadSafe = 1 << 7, + + /// + /// If this falgs is applied to a property, we do not generate a + /// backing field. See bugzilla #3359 and Assistly 7032 for some + /// background information + /// + Transient = 1 << 8, + + /// + /// If this flag is applied to a property, we do not generate a NSString for + /// marshalling the property. + /// + PlainString = 1 << 9, + + /// + /// If this flag is applied to a property, the generator will consider the property to be + /// part of a CoreImage filter and will generate the property as a CoreImage filter property. + /// + CoreImageFilterProperty = 1 << 10, + + /// + /// Use this flag on method to wrap the invocation in a NSAutoReleasePool. + /// + AutoRelease = 1 << 11, + } } diff --git a/src/ObjCRuntime/BackingField.cs b/src/ObjCRuntime/BackingField.cs index 88fcae65964e..8f85291feda5 100644 --- a/src/ObjCRuntime/BackingField.cs +++ b/src/ObjCRuntime/BackingField.cs @@ -46,7 +46,8 @@ namespace ObjCRuntime { - static class BackingField { + static class BackingField + { public static T Get (ref T value, IntPtr handle, Converter c) where T : class, INativeObject, IDisposable { diff --git a/src/ObjCRuntime/BindAs.cs b/src/ObjCRuntime/BindAs.cs index 35b10aede41c..2722caa1cd4a 100644 --- a/src/ObjCRuntime/BindAs.cs +++ b/src/ObjCRuntime/BindAs.cs @@ -37,7 +37,7 @@ static T Identity (T obj) return obj; } - unsafe static T []? ConvertNSArrayToManagedArray (IntPtr nsarray, delegate* convert) where T : struct + unsafe static T[]? ConvertNSArrayToManagedArray (IntPtr nsarray, delegate* convert) where T: struct { if (nsarray == IntPtr.Zero) return null; @@ -45,7 +45,7 @@ static T Identity (T obj) return ConvertNSArrayToManagedArray2 (nsarray, convert, &Identity); } - unsafe static IntPtr ConvertManagedArrayToNSArray (T []? array, delegate* convert) where T : struct + unsafe static IntPtr ConvertManagedArrayToNSArray (T[]? array, delegate* convert) where T: struct { if (array is null) return IntPtr.Zero; @@ -53,7 +53,7 @@ unsafe static IntPtr ConvertManagedArrayToNSArray (T []? array, delegate* (array, &Identity, convert); } - unsafe static T []? ConvertNSArrayToManagedArray2 (IntPtr nsarray, delegate* convert1, delegate* convert2) where T : struct + unsafe static T[]? ConvertNSArrayToManagedArray2 (IntPtr nsarray, delegate* convert1, delegate* convert2) where T: struct { if (nsarray == IntPtr.Zero) return null; @@ -61,7 +61,7 @@ unsafe static IntPtr ConvertManagedArrayToNSArray (T []? array, delegate* (nsarray, (ptr) => convert2 (convert1 (ptr))); } - unsafe static IntPtr ConvertManagedArrayToNSArray2 (T []? array, delegate* convert1, delegate* convert2) where T : struct + unsafe static IntPtr ConvertManagedArrayToNSArray2 (T[]? array, delegate* convert1, delegate* convert2) where T: struct { if (array is null) return IntPtr.Zero; @@ -90,14 +90,14 @@ unsafe static IntPtr ConvertManagedArrayToNSArray2 (T []? array, delegate* return rv; } - unsafe static T? CreateNullable (IntPtr handle, delegate* convert) where T : struct + unsafe static T? CreateNullable (IntPtr handle, delegate* convert) where T: struct { if (handle == IntPtr.Zero) return null; return convert (handle); } - unsafe static T? CreateNullable2 (IntPtr handle, delegate* convert1, delegate* convert2) where T : struct + unsafe static T? CreateNullable2 (IntPtr handle, delegate* convert1, delegate* convert2) where T: struct { if (handle == IntPtr.Zero) return null; diff --git a/src/ObjCRuntime/Blocks.cs b/src/ObjCRuntime/Blocks.cs index 2c3389e1c9a9..cb3b4091fbe3 100644 --- a/src/ObjCRuntime/Blocks.cs +++ b/src/ObjCRuntime/Blocks.cs @@ -410,7 +410,7 @@ public object Target { } #if NET - public T GetDelegateForBlock () where T : System.MulticastDelegate + public T GetDelegateForBlock () where T: System.MulticastDelegate #else public T GetDelegateForBlock () where T : class #endif @@ -419,7 +419,7 @@ public T GetDelegateForBlock () where T : class } #if NET - public unsafe static T GetTarget (IntPtr block) where T : System.MulticastDelegate + public unsafe static T GetTarget (IntPtr block) where T: System.MulticastDelegate #else public unsafe static T GetTarget (IntPtr block) where T : class /* /* requires C# 7.3+: System.MulticastDelegate */ #endif @@ -443,9 +443,9 @@ public static bool IsManagedBlock (IntPtr block) // This method doesn't necessarily work with NativeAOT, but this is covered by the exception, because the managed static registrar is required for NativeAOT. // // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.Interfaces' in call to 'System.Type.GetInterfaces()'. The return value of method 'System.Reflection.MemberInfo.DeclaringType.get' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - [UnconditionalSuppressMessage ("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] // IL2062: Value passed to parameter 'interfaceType' of method 'System.Type.GetInterfaceMap(Type)' can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - [UnconditionalSuppressMessage ("", "IL2062", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage("", "IL2062", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif static Type GetDelegateProxyType (MethodInfo minfo, uint token_ref, out MethodInfo baseMethod) { @@ -499,7 +499,7 @@ static Type GetDelegateProxyType (MethodInfo minfo, uint token_ref, out MethodIn [BindingImpl (BindingImplOptions.Optimizable)] unsafe static IntPtr GetBlockForFunctionPointer (MethodInfo delegateInvokeMethod, object @delegate, string signature) { - void* invokeFunctionPointer = (void*) delegateInvokeMethod.MethodHandle.GetFunctionPointer (); + void* invokeFunctionPointer = (void *) delegateInvokeMethod.MethodHandle.GetFunctionPointer (); if (signature is null) { if (!Runtime.DynamicRegistrationSupported) throw ErrorHelper.CreateError (8026, $"BlockLiteral.GetBlockForDelegate with a null signature is not supported when the dynamic registrar has been linked away (delegate type: {@delegate.GetType ().FullName})."); @@ -547,7 +547,7 @@ static IntPtr CreateBlockForDelegate (Delegate @delegate, Delegate delegateProxy // // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicFields' in call to 'System.Type.GetField(String, BindingFlags)'. The return value of method 'ObjCRuntime.BlockLiteral.GetDelegateProxyType(MethodInfo, UInt32, MethodInfo&)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Type.GetMethod(String, BindingFlags)'. The return value of method 'ObjCRuntime.BlockLiteral.GetDelegateProxyType(MethodInfo, UInt32, MethodInfo&)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to." - [UnconditionalSuppressMessage ("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif internal static IntPtr GetBlockForDelegate (MethodInfo minfo, object @delegate, uint token_ref, string signature) { diff --git a/src/ObjCRuntime/Class.cs b/src/ObjCRuntime/Class.cs index 1bfa062aebbb..4135e6d8cb9d 100644 --- a/src/ObjCRuntime/Class.cs +++ b/src/ObjCRuntime/Class.cs @@ -537,7 +537,7 @@ internal static unsafe int FindMapIndex (Runtime.MTClassMap* array, int lo, int // // IL2026: Using member 'System.Reflection.Module.ResolveMethod(Int32)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Trimming changes metadata tokens. // IL2026: Using member 'System.Reflection.Module.ResolveType(Int32)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Trimming changes metadata tokens. - [UnconditionalSuppressMessage ("", "IL2026", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage("", "IL2026", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif static MemberInfo? ResolveTokenNonManagedStatic (Assembly assembly, Module? module, uint token) { diff --git a/src/ObjCRuntime/DelayedRegistrationAttribute.cs b/src/ObjCRuntime/DelayedRegistrationAttribute.cs index c1b57b383a01..097d486714f2 100644 --- a/src/ObjCRuntime/DelayedRegistrationAttribute.cs +++ b/src/ObjCRuntime/DelayedRegistrationAttribute.cs @@ -29,7 +29,8 @@ namespace ObjCRuntime { [AttributeUsage (AttributeTargets.Assembly)] - public abstract class DelayedRegistrationAttribute : Attribute { + public abstract class DelayedRegistrationAttribute : Attribute + { public abstract bool Delay { get; } } } diff --git a/src/ObjCRuntime/Dlfcn.cs b/src/ObjCRuntime/Dlfcn.cs index 725be061da61..a1b10999b496 100644 --- a/src/ObjCRuntime/Dlfcn.cs +++ b/src/ObjCRuntime/Dlfcn.cs @@ -56,7 +56,8 @@ static public class LibC { static public readonly IntPtr Handle = Dlfcn._dlopen (Constants.libcLibrary, 0); } #if HAS_OPENGLES - static public class OpenGLES { + static public class OpenGLES + { static public readonly IntPtr Handle = Dlfcn._dlopen (Constants.OpenGLESLibrary, 0); } #endif diff --git a/src/ObjCRuntime/INativeObject.cs b/src/ObjCRuntime/INativeObject.cs index aa4823b9642f..f464c21fd741 100644 --- a/src/ObjCRuntime/INativeObject.cs +++ b/src/ObjCRuntime/INativeObject.cs @@ -21,7 +21,7 @@ NativeHandle Handle { // The method will be implemented via custom linker step if the managed static registrar is used // for classes which have an (NativeHandle, bool) or (IntPtr, bool) constructor. // This method will be made public when the managed static registrar is used. - [MethodImpl (MethodImplOptions.NoInlining)] + [MethodImpl(MethodImplOptions.NoInlining)] internal static virtual INativeObject? _Xamarin_ConstructINativeObject (NativeHandle handle, bool owns) => null; #endif } diff --git a/src/ObjCRuntime/NativeHandle.cs b/src/ObjCRuntime/NativeHandle.cs index 9844e9d25e03..d9f1453b2e1b 100644 --- a/src/ObjCRuntime/NativeHandle.cs +++ b/src/ObjCRuntime/NativeHandle.cs @@ -72,10 +72,10 @@ public static implicit operator NativeHandle (IntPtr value) public unsafe static explicit operator void* (NativeHandle value) { - return (void*) (IntPtr) value; + return (void *) (IntPtr) value; } - public unsafe static explicit operator NativeHandle (void* value) + public unsafe static explicit operator NativeHandle (void * value) { return new NativeHandle ((IntPtr) value); } diff --git a/src/ObjCRuntime/PlatformAvailability.cs b/src/ObjCRuntime/PlatformAvailability.cs index 9f455bfdcd26..41887c7773b8 100644 --- a/src/ObjCRuntime/PlatformAvailability.cs +++ b/src/ObjCRuntime/PlatformAvailability.cs @@ -568,7 +568,7 @@ public MacAttribute (byte major, byte minor, PlatformArchitecture arch) public MacAttribute (byte major, byte minor, byte subminor) #if NET - : base ((Platform) ((ulong) major << 48 | (ulong) minor << 40 | (ulong) subminor << 32)) + : base ((Platform)((ulong)major << 48 | (ulong)minor << 40 | (ulong)subminor << 32)) #else : this (major, minor, subminor, false) #endif diff --git a/src/ObjCRuntime/RegistrarHelper.cs b/src/ObjCRuntime/RegistrarHelper.cs index c145d6e8f844..f5ba5b46b689 100644 --- a/src/ObjCRuntime/RegistrarHelper.cs +++ b/src/ObjCRuntime/RegistrarHelper.cs @@ -69,7 +69,7 @@ internal static void Initialize () wrapper_types = new Dictionary (RuntimeTypeHandleEqualityComparer); } - static NativeHandle CreateCFArray (params string []? values) + static NativeHandle CreateCFArray (params string[]? values) { if (values is null) return NativeHandle.Zero; @@ -252,9 +252,9 @@ static NativeHandle ManagedArrayToNSArray (object array, bool retain) return NativeHandle.Zero; NSObject rv; - if (array is NSObject [] nsobjs) { + if (array is NSObject[] nsobjs) { rv = NSArray.FromNSObjects (nsobjs); - } else if (array is INativeObject [] inativeobjs) { + } else if (array is INativeObject[] inativeobjs) { rv = NSArray.FromNSObjects (inativeobjs); } else { throw new InvalidOperationException ($"Can't convert {array.GetType ()} to an NSArray."); // FIXME: better error @@ -265,7 +265,7 @@ static NativeHandle ManagedArrayToNSArray (object array, bool retain) return Runtime.RetainAndAutoreleaseNSObject (rv); } - unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string []? value, ref string []? copy) + unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string[]? value, ref string[]? copy) { if (ptr is not null) { value = NSArray.StringArrayFromHandle (*ptr); @@ -275,7 +275,7 @@ unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string []? copy = value; } - unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string [] value, string [] copy, bool isOut) + unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string[] value, string[] copy, bool isOut) { if (ptr is null) return; @@ -301,7 +301,7 @@ unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string [] valu *ptr = rv; } - unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T []? value, ref T []? copy) where T : class, INativeObject + unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T[]? value, ref T[]? copy) where T: class, INativeObject { if (ptr is not null) { value = NSArray.ArrayFromHandle (*ptr); @@ -311,7 +311,7 @@ unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T []? value, r copy = value; } - unsafe static void NSArray_managed_to_native (IntPtr* ptr, T [] value, T [] copy, bool isOut) where T : class, INativeObject + unsafe static void NSArray_managed_to_native (IntPtr* ptr, T[] value, T[] copy, bool isOut) where T: class, INativeObject { if (ptr is null) { #if TRACE @@ -340,7 +340,7 @@ unsafe static void NSArray_managed_to_native (IntPtr* ptr, T [] value, T [] c *ptr = rv; } - unsafe static void NSObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy) where T : NSObject + unsafe static void NSObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy) where T: NSObject { if (ptr is not null) { value = Runtime.GetNSObject (*ptr, owns: false); @@ -371,7 +371,7 @@ unsafe static void NSObject_managed_to_native (IntPtr* ptr, NSObject value, NSOb *ptr = rv; } - unsafe static void string_native_to_managed (NativeHandle* ptr, ref string? value, ref string? copy) + unsafe static void string_native_to_managed (NativeHandle *ptr, ref string? value, ref string? copy) { if (ptr is not null) { value = CFString.FromHandle (*ptr); @@ -381,7 +381,7 @@ unsafe static void string_native_to_managed (NativeHandle* ptr, ref string? valu copy = value; } - unsafe static void string_managed_to_native (NativeHandle* ptr, string value, string copy, bool isOut) + unsafe static void string_managed_to_native (NativeHandle *ptr, string value, string copy, bool isOut) { if (ptr is null) { #if TRACE @@ -402,7 +402,7 @@ unsafe static void string_managed_to_native (NativeHandle* ptr, string value, st *ptr = rv; } - unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy, RuntimeTypeHandle implementationType) where T : class, INativeObject + unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy, RuntimeTypeHandle implementationType) where T: class, INativeObject { if (ptr is not null) { value = Runtime.GetINativeObject (*ptr, implementation: Type.GetTypeFromHandle (implementationType), forced_type: false, owns: false); @@ -412,7 +412,7 @@ unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value copy = value; } - unsafe static void INativeObject_managed_to_native (IntPtr* ptr, INativeObject value, INativeObject copy, bool isOut) + unsafe static void INativeObject_managed_to_native (IntPtr *ptr, INativeObject value, INativeObject copy, bool isOut) { if (ptr is null) { #if TRACE diff --git a/src/ObjCRuntime/RequiredFrameworkAttribute.cs b/src/ObjCRuntime/RequiredFrameworkAttribute.cs index ac1b8cc56505..afc789075980 100644 --- a/src/ObjCRuntime/RequiredFrameworkAttribute.cs +++ b/src/ObjCRuntime/RequiredFrameworkAttribute.cs @@ -29,10 +29,11 @@ namespace ObjCRuntime { - [AttributeUsage (AttributeTargets.Assembly, AllowMultiple = true)] - public class RequiredFrameworkAttribute : Attribute { + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public class RequiredFrameworkAttribute : Attribute + { public string Name { get; private set; } - + public RequiredFrameworkAttribute (string name) { Name = name; diff --git a/src/ObjCRuntime/Runtime.CoreCLR.cs b/src/ObjCRuntime/Runtime.CoreCLR.cs index f7a1f4cdf369..3de830102738 100644 --- a/src/ObjCRuntime/Runtime.CoreCLR.cs +++ b/src/ObjCRuntime/Runtime.CoreCLR.cs @@ -37,7 +37,7 @@ using Xamarin.Bundler; -using MonoObjectPtr = System.IntPtr; +using MonoObjectPtr=System.IntPtr; namespace ObjCRuntime { @@ -98,7 +98,7 @@ static void log_coreclr (string message) // Define VERBOSE_LOG at the top of this file to get all printfs [System.Diagnostics.Conditional ("VERBOSE_LOG")] - static void log_coreclr_render (string message, params object? [] argumentsToRender) + static void log_coreclr_render (string message, params object?[] argumentsToRender) { var args = new string [argumentsToRender.Length]; for (var i = 0; i < args.Length; i++) { @@ -212,7 +212,7 @@ internal static GCHandle CreateTrackingGCHandle (NSObject obj, IntPtr handle) unsafe { TrackedObjectInfo* tracked_info; fixed (void* ptr = info) - tracked_info = (TrackedObjectInfo*) ptr; + tracked_info = (TrackedObjectInfo *) ptr; tracked_info->Handle = handle; tracked_info->Flags = obj.FlagsInternal; obj.tracked_object_info = tracked_info; @@ -264,7 +264,7 @@ internal static void RegisterToggleReferenceCoreCLR (NSObject obj, IntPtr handle } // Returns a retained MonoObject. Caller must release. - [UnconditionalSuppressMessage ("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "This method is only called to retrieve the assembly where the entry point is, and the entry point is not trimmed away, so this is safe.")] + [UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "This method is only called to retrieve the assembly where the entry point is, and the entry point is not trimmed away, so this is safe.")] static IntPtr FindAssembly (IntPtr assembly_name) { if (IsNativeAOT) @@ -306,7 +306,7 @@ static unsafe void SetPendingException (MonoObject* exception_obj) ObjectiveCMarshal.SetMessageSendPendingException (exc); } - unsafe static sbyte IsClassOfType (MonoObject* typeobj, TypeLookup match) + unsafe static sbyte IsClassOfType (MonoObject *typeobj, TypeLookup match) { var rv = IsClassOfType ((Type?) GetMonoObjectTarget (typeobj), match); return (sbyte) (rv ? 1 : 0); @@ -459,7 +459,7 @@ static IntPtr GetMonoObjectImpl (object obj) return null; unsafe { - MonoObject* monoobj = (MonoObject*) mobj; + MonoObject *monoobj = (MonoObject *) mobj; return GetGCHandleTarget (monoobj->GCHandle); } } @@ -469,7 +469,7 @@ static IntPtr GetMonoObjectImpl (object obj) static extern void xamarin_bridge_log_monoobject (IntPtr mono_object, string stack_trace); #endif - static IntPtr MarshalStructure (T value) where T : unmanaged + static IntPtr MarshalStructure (T value) where T: unmanaged { var destination = Marshal.AllocHGlobal (Marshal.SizeOf ()); @@ -564,10 +564,10 @@ static byte GetFlagsForNSObject (IntPtr gchandle) return (byte) obj.FlagsInternal; } - static unsafe MonoObject* GetMethodDeclaringType (MonoObject* mobj) + static unsafe MonoObject* GetMethodDeclaringType (MonoObject *mobj) { var method = (MethodBase) GetMonoObjectTarget (mobj)!; - return (MonoObject*) GetMonoObject (method.DeclaringType); + return (MonoObject *) GetMonoObject (method.DeclaringType); } static IntPtr ObjectGetType (MonoObjectPtr mobj) @@ -611,16 +611,16 @@ static unsafe IntPtr GetMethodSignature (MonoObject* methodobj) var parameterCount = parameters.Length; var rv = Marshal.AllocHGlobal (sizeof (MonoMethodSignature) + sizeof (MonoObjectPtr) * parameterCount); - MonoMethodSignature* signature = (MonoMethodSignature*) rv; + MonoMethodSignature* signature = (MonoMethodSignature *) rv; signature->Method = methodobj; xamarin_mono_object_retain (methodobj); signature->ParameterCount = parameterCount; - signature->ReturnType = (MonoObject*) GetMonoObject (GetMethodReturnType (method)); + signature->ReturnType = (MonoObject *) GetMonoObject (GetMethodReturnType (method)); MonoObject** mparams = &signature->Parameters; for (var i = 0; i < parameterCount; i++) { var p = parameters [i]; - mparams [i] = (MonoObject*) GetMonoObject (p.ParameterType); + mparams [i] = (MonoObject *) GetMonoObject (p.ParameterType); } return rv; @@ -638,14 +638,14 @@ static unsafe IntPtr GetMethodSignature (MonoObject* methodobj) return null; } - unsafe static IntPtr ClassGetNamespace (MonoObject* typeobj) + unsafe static IntPtr ClassGetNamespace (MonoObject *typeobj) { var type = (Type?) GetMonoObjectTarget (typeobj); var rv = type?.Namespace; return Marshal.StringToHGlobalAuto (rv); } - unsafe static IntPtr ClassGetName (MonoObject* typeobj) + unsafe static IntPtr ClassGetName (MonoObject *typeobj) { var type = (Type?) GetMonoObjectTarget (typeobj); var rv = type?.Name; @@ -658,7 +658,7 @@ unsafe static IntPtr ClassGetName (MonoObject* typeobj) var type = (Type?) GetMonoObjectTarget (typeobj); if (type?.IsByRef == true) type = type.GetElementType (); - return (MonoObject*) GetMonoObject (type); + return (MonoObject *) GetMonoObject (type); } static unsafe int SizeOf (MonoObject* typeobj) @@ -682,7 +682,7 @@ static int SizeOf (Type type) var method = (MethodBase) GetMonoObjectTarget (methodobj)!; var instance = GetMonoObjectTarget (instanceobj)!; var rv = InvokeMethod (method, instance, native_parameters); - return (MonoObject*) GetMonoObject (rv); + return (MonoObject *) GetMonoObject (rv); } // Return value: NULL or a MonoObject* that must be released with xamarin_mono_object_safe_release. @@ -744,7 +744,7 @@ static int SizeOf (Type type) log_coreclr ($" IsClass/IsInterface/IsNullable IsByRef: {isByRef} IsOut: {p.IsOut} ParameterType: {paramType}"); if (nativeParam != IntPtr.Zero) { unsafe { - MonoObject* mono_obj = (MonoObject*) nativeParam; + MonoObject* mono_obj = (MonoObject *) nativeParam; // dereference if it's a byref type if (isByRef) mono_obj = *(MonoObject**) mono_obj; @@ -788,7 +788,7 @@ static int SizeOf (Type type) try { rv = method.Invoke (instance, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, parameters, null); - } catch (TargetInvocationException tie) { + } catch (TargetInvocationException tie) { var ex = tie.InnerException ?? tie; // This will re-throw the original exception and preserve the stacktrace. ExceptionDispatchInfo.Capture (ex).Throw (); @@ -855,7 +855,7 @@ static unsafe IntPtr StringToUtf8 (MonoObject* obj) static unsafe MonoObject* NewString (IntPtr text) { - return (MonoObject*) GetMonoObject (Marshal.PtrToStringAuto (text)); + return (MonoObject *) GetMonoObject (Marshal.PtrToStringAuto (text)); } static unsafe MonoObject* CreateArray (MonoObject* typeobj, ulong elements) @@ -874,14 +874,14 @@ static unsafe ulong GetArrayLength (MonoObject* obj) return (ulong) array.Length; } - static unsafe void SetArrayObjectValue (MonoObject* arrayobj, ulong index, MonoObject* mobj) + static unsafe void SetArrayObjectValue (MonoObject *arrayobj, ulong index, MonoObject *mobj) { var array = (Array) GetMonoObjectTarget (arrayobj)!; var obj = GetMonoObjectTarget (mobj); array.SetValue (obj, (long) index); } - static unsafe void SetArrayStructValue (MonoObject* arrayobj, ulong index, MonoObject* typeobj, IntPtr valueptr) + static unsafe void SetArrayStructValue (MonoObject *arrayobj, ulong index, MonoObject *typeobj, IntPtr valueptr) { var array = (Array) GetMonoObjectTarget (arrayobj)!; var elementType = (Type) GetMonoObjectTarget (typeobj)!; @@ -893,14 +893,14 @@ static unsafe void SetArrayStructValue (MonoObject* arrayobj, ulong index, MonoO { var array = (Array) GetMonoObjectTarget (arrayobj)!; var obj = array.GetValue ((long) index); - return (MonoObject*) GetMonoObject (obj); + return (MonoObject *) GetMonoObject (obj); } static unsafe MonoObject* Box (MonoObject* typeobj, IntPtr value) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = Box (type, value); - return (MonoObject*) GetMonoObject (rv); + return (MonoObject *) GetMonoObject (rv); } static object? Box (Type type, IntPtr value) @@ -948,21 +948,21 @@ static bool IsNullable (Type type) return false; } - unsafe static sbyte IsByRef (MonoObject* typeobj) + unsafe static sbyte IsByRef (MonoObject *typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsByRef; return (sbyte) (rv ? 1 : 0); } - unsafe static sbyte IsValueType (MonoObject* typeobj) + unsafe static sbyte IsValueType (MonoObject *typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsValueType; return (sbyte) (rv ? 1 : 0); } - unsafe static sbyte IsEnum (MonoObject* typeobj) + unsafe static sbyte IsEnum (MonoObject *typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsEnum; diff --git a/src/ObjCRuntime/Runtime.cs b/src/ObjCRuntime/Runtime.cs index 138e94b76e5a..66aedf65af84 100644 --- a/src/ObjCRuntime/Runtime.cs +++ b/src/ObjCRuntime/Runtime.cs @@ -177,8 +177,8 @@ internal enum InitializationFlags : int { /* unused = 0x08,*/ IsSimulator = 0x10, #if NET - IsCoreCLR = 0x20, - IsNativeAOT = 0x40, + IsCoreCLR = 0x20, + IsNativeAOT = 0x40, #endif } @@ -226,7 +226,8 @@ public bool IsSimulator { internal static unsafe InitializationOptions* options; #if NET - public static class ClassHandles { + public static class ClassHandles + { static NativeHandle unused; internal static unsafe void InitializeClassHandles (IntPtr* map) { @@ -237,7 +238,7 @@ internal static unsafe void InitializeClassHandles (IntPtr* map) // Rewriter uses those. // In the case of NO class handle rewriting, // this is a no-op - fixed (NativeHandle* ptr = &unused) { + fixed (NativeHandle *ptr = &unused) { SetHandle (-1, ptr, map); } } @@ -247,9 +248,9 @@ internal static unsafe void SetHandle (int index, NativeHandle* handle, IntPtr* { if (index < 0) return; - + var nativeHandle = map [index]; - *handle = (NativeHandle) nativeHandle; + *handle = (NativeHandle)nativeHandle; } } #endif @@ -296,10 +297,10 @@ internal static bool Initialized { [DllImport (Constants.libcLibrary)] unsafe static extern int _NSGetExecutablePath (byte* buf, int* bufsize); - unsafe static int _NSGetExecutablePath (byte [] buf, ref int bufsize) + unsafe static int _NSGetExecutablePath (byte[] buf, ref int bufsize) { fixed (byte* bufptr = buf) - return _NSGetExecutablePath (bufptr, (int*) Unsafe.AsPointer (ref bufsize)); + return _NSGetExecutablePath (bufptr, (int *) Unsafe.AsPointer (ref bufsize)); } #endif @@ -459,7 +460,8 @@ static bool ThreadPoolDispatcher (Func callback) static bool OnAssemblyRegistration (AssemblyName assembly_name) { if (AssemblyRegistration is not null) { - var args = new AssemblyRegistrationEventArgs { + var args = new AssemblyRegistrationEventArgs + { Register = true, AssemblyName = assembly_name }; @@ -784,13 +786,14 @@ public static void RegisterAssembly (Assembly a) var attributes = a.GetCustomAttributes (typeof (RequiredFrameworkAttribute), false); foreach (var attribute in attributes) { - var requiredFramework = (RequiredFrameworkAttribute) attribute; + var requiredFramework = (RequiredFrameworkAttribute)attribute; string libPath; string libName = requiredFramework.Name; if (libName.Contains (".dylib")) { libPath = ResourcesPath!; - } else { + } + else { libPath = FrameworksPath!; libPath = Path.Combine (libPath, libName); libName = libName.Replace (".frameworks", ""); @@ -799,7 +802,7 @@ public static void RegisterAssembly (Assembly a) if (Dlfcn.dlopen (libPath, 0) == IntPtr.Zero) throw new Exception ($"Unable to load required framework: '{requiredFramework.Name}'", - new Exception (Dlfcn.dlerror ())); + new Exception (Dlfcn.dlerror())); } attributes = a.GetCustomAttributes (typeof (DelayedRegistrationAttribute), false); @@ -1604,7 +1607,7 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM // If type is an NSObject, we prefer the NSObject lookup table if (instance is null && type != typeof (NSObject) && type.IsSubclassOf (typeof (NSObject))) { - instance = (T?) (INativeObject?) RegistrarHelper.ConstructNSObject (type, nativeHandle); + instance = (T?)(INativeObject?) RegistrarHelper.ConstructNSObject (type, nativeHandle); if (instance is not null && owns) { Runtime.TryReleaseINativeObject (instance); } @@ -2143,7 +2146,7 @@ static Type LookupINativeObjectImplementation (IntPtr ptr, Type target_type, Typ // For other registrars other than managed-static the generic parameter of ConstructNSObject is used // only to cast the return value so we can safely pass NSObject here to satisfy the constraints of the // generic parameter. - var rv = (T?) (INativeObject?) ConstructNSObject (ptr, implementation, MissingCtorResolution.ThrowConstructor1NotFound, sel, method_handle); + var rv = (T?)(INativeObject?) ConstructNSObject (ptr, implementation, MissingCtorResolution.ThrowConstructor1NotFound, sel, method_handle); if (owns) TryReleaseINativeObject (rv); return rv; diff --git a/src/ObjCRuntime/Runtime.mac.cs b/src/ObjCRuntime/Runtime.mac.cs index 56b55d9e03b8..d8630d44ee69 100644 --- a/src/ObjCRuntime/Runtime.mac.cs +++ b/src/ObjCRuntime/Runtime.mac.cs @@ -54,9 +54,9 @@ public static string? FrameworksPath { public static string? ResourcesPath { get; set; } - + delegate void initialize_func (); - unsafe delegate sbyte* get_sbyteptr_func (); + unsafe delegate sbyte *get_sbyteptr_func (); #if !NET // There's a different implementation for other platforms + .NET macOS in Runtime.cs static volatile bool originalWorkingDirectoryIsSet; diff --git a/src/ObjCRuntime/Stret.cs b/src/ObjCRuntime/Stret.cs index 53e52767cfbc..d0352a1fd0c8 100644 --- a/src/ObjCRuntime/Stret.cs +++ b/src/ObjCRuntime/Stret.cs @@ -29,7 +29,9 @@ #endif using System.Runtime.InteropServices; +#if !RGEN using Foundation; +#endif // Disable until we get around to enable + fix any issues. #nullable disable @@ -41,7 +43,7 @@ static bool IsHomogeneousAggregateSmallEnough_Armv7k (Type t, int members) // https://github.com/llvm-mirror/clang/blob/82f6d5c9ae84c04d6e7b402f72c33638d1fb6bc8/lib/CodeGen/TargetInfo.cpp#L5516-L5519 return members <= 4; } - +#if !RGEN static bool IsHomogeneousAggregateBaseType_Armv7k (Type t, Generator generator) { // https://github.com/llvm-mirror/clang/blob/82f6d5c9ae84c04d6e7b402f72c33638d1fb6bc8/lib/CodeGen/TargetInfo.cpp#L5500-L5514 @@ -77,6 +79,7 @@ static bool IsHomogeneousAggregate_Armv7k (List fieldTypes, Generator gene return true; } +#endif #if BGENERATOR public static bool ArmNeedStret (Type returnType, Generator generator) @@ -152,7 +155,7 @@ public static bool ArmNeedStret (Type returnType, Generator generator) } #endif // BGENERATOR -#if BGENERATOR +#if BGENERATOR || RGEN public static bool X86NeedStret (Type returnType, Generator generator) { Type t = returnType; @@ -188,7 +191,7 @@ public static bool X86_64NeedStret (Type returnType, Generator generator) // IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicFields', 'DynamicallyAccessedMemberTypes.NonPublicFields' in call to 'System.Type.GetFields(BindingFlags)'. The parameter 'type' of method 'ObjCRuntime.Stret.GetValueTypeSize(Type, List, Boolean, Object)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. [UnconditionalSuppressMessage ("", "IL2070", Justification = "Computing the size of a struct is safe, because the trimmer can't remove fields that would affect the size of a marshallable struct (it could affect marshalling behavior).")] #endif - static int GetValueTypeSize (Type type, List fieldTypes, bool is_64_bits, Generator generator) + internal static int GetValueTypeSize (Type type, List fieldTypes, bool is_64_bits, Generator generator) { int size = 0; int maxElementSize = 1; @@ -228,7 +231,7 @@ static bool IsBuiltInType (Type type) return IsBuiltInType (type, true /* doesn't matter */, out var _); } - static bool IsBuiltInType (Type type, bool is_64_bits, out int type_size) + internal static bool IsBuiltInType (Type type, bool is_64_bits, out int type_size) { type_size = 0; diff --git a/src/PassKit/PKCompat.cs b/src/PassKit/PKCompat.cs index de76bf7fdb6f..d8e889f5785b 100644 --- a/src/PassKit/PKCompat.cs +++ b/src/PassKit/PKCompat.cs @@ -87,7 +87,7 @@ public unsafe virtual void AuthorizeDisbursement (global::System.Action> AuthorizeDisbursementAsync () + public unsafe virtual Task> AuthorizeDisbursementAsync () { throw new InvalidOperationException (Constants.RemovedFromPassKit); } @@ -125,7 +125,8 @@ protected override void Dispose (bool disposing) #endif // NET [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("This class is removed.")] - public partial interface IPKDisbursementAuthorizationControllerDelegate : INativeObject, IDisposable { + public partial interface IPKDisbursementAuthorizationControllerDelegate : INativeObject, IDisposable + { void DidAuthorize (PKDisbursementAuthorizationController controller, PKDisbursementVoucher disbursementVoucher); void DidFinish (PKDisbursementAuthorizationController controller); } diff --git a/src/PdfKit/Enums.cs b/src/PdfKit/Enums.cs index 45cba05bb9cf..cd3ff0ac0476 100644 --- a/src/PdfKit/Enums.cs +++ b/src/PdfKit/Enums.cs @@ -39,37 +39,37 @@ namespace PdfKit { [Native] [TV (18, 2)] public enum PdfActionNamedName : long { - None = 0, - NextPage = 1, + None = 0, + NextPage = 1, PreviousPage = 2, - FirstPage = 3, - LastPage = 4, - GoBack = 5, - GoForward = 6, - GoToPage = 7, - Find = 8, - Print = 9, - ZoomIn = 10, - ZoomOut = 11 + FirstPage = 3, + LastPage = 4, + GoBack = 5, + GoForward = 6, + GoToPage = 7, + Find = 8, + Print = 9, + ZoomIn = 10, + ZoomOut = 11 } [Native] [TV (18, 2)] public enum PdfWidgetControlType : long { - Unknown = -1, - PushButton = 0, + Unknown = -1, + PushButton = 0, RadioButton = 1, - CheckBox = 2 + CheckBox = 2 } [Native] [TV (18, 2)] public enum PdfLineStyle : long { - None = 0, - Square = 1, - Circle = 2, - Diamond = 3, - OpenArrow = 4, + None = 0, + Square = 1, + Circle = 2, + Diamond = 3, + OpenArrow = 4, ClosedArrow = 5 } @@ -79,28 +79,28 @@ public enum PdfMarkupType : long { Highlight = 0, StrikeOut = 1, Underline = 2, - Redact = 3, + Redact = 3, } [Native] [TV (18, 2)] public enum PdfTextAnnotationIconType : long { - Comment = 0, - Key = 1, - Note = 2, - Help = 3, + Comment = 0, + Key = 1, + Note = 2, + Help = 3, NewParagraph = 4, - Paragraph = 5, - Insert = 6 + Paragraph = 5, + Insert = 6 } [Native] [TV (18, 2)] public enum PdfBorderStyle : long { - Solid = 0, - Dashed = 1, - Beveled = 2, - Inset = 3, + Solid = 0, + Dashed = 1, + Beveled = 2, + Inset = 3, Underline = 4 } @@ -110,16 +110,16 @@ public enum PdfBorderStyle : long { [Unavailable (PlatformName.MacCatalyst)] [Native] public enum PdfPrintScalingMode : long { - None = 0, - ToFit = 1, + None = 0, + ToFit = 1, DownToFit = 2 } [Native] [TV (18, 2)] public enum PdfDocumentPermissions : long { - None = 0, - User = 1, + None = 0, + User = 1, Owner = 2 } @@ -127,36 +127,36 @@ public enum PdfDocumentPermissions : long { [TV (18, 2)] public enum PdfDisplayBox : long { Media = 0, - Crop = 1, + Crop = 1, Bleed = 2, - Trim = 3, - Art = 4 + Trim = 3, + Art = 4 } [Native] [TV (18, 2)] public enum PdfDisplayMode : long { - SinglePage = 0, + SinglePage = 0, SinglePageContinuous = 1, - TwoUp = 2, - TwoUpContinuous = 3 + TwoUp = 2, + TwoUpContinuous = 3 } [Flags] [Native] [TV (18, 2)] public enum PdfAreaOfInterest : long { - NoArea = 0, - PageArea = 1 << 0, - TextArea = 1 << 1, + NoArea = 0, + PageArea = 1 << 0, + TextArea = 1 << 1, AnnotationArea = 1 << 2, - LinkArea = 1 << 3, - ControlArea = 1 << 4, - TextFieldArea = 1 << 5, - IconArea = 1 << 6, - PopupArea = 1 << 7, - ImageArea = 1 << 8, - [iOS (15, 0), MacCatalyst (15, 0)] + LinkArea = 1 << 3, + ControlArea = 1 << 4, + TextFieldArea = 1 << 5, + IconArea = 1 << 6, + PopupArea = 1 << 7, + ImageArea = 1 << 8, + [iOS (15,0), MacCatalyst (15,0)] AnyArea = Int64.MaxValue, } diff --git a/src/PhotosUI/PHEnums.cs b/src/PhotosUI/PHEnums.cs index 5673e478f07b..8753917b1c49 100644 --- a/src/PhotosUI/PHEnums.cs +++ b/src/PhotosUI/PHEnums.cs @@ -14,9 +14,7 @@ public enum PHLivePhotoViewPlaybackStyle : long { } #if MONOMAC - [NoiOS] - [NoTV] - [NoMacCatalyst] + [NoiOS][NoTV][NoMacCatalyst] [Native] public enum PHLivePhotoViewContentMode : long { AspectFit, diff --git a/src/QuickLook/Thumbnail.cs b/src/QuickLook/Thumbnail.cs index 8f7f0f0d2c23..fa43d8107ead 100644 --- a/src/QuickLook/Thumbnail.cs +++ b/src/QuickLook/Thumbnail.cs @@ -52,7 +52,7 @@ public static partial class QLThumbnailImage { #else [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use the QuickLookThumbnailing framework instead for creating thumbnails for files.")] #endif - [DllImport (Constants.QuickLookLibrary)] + [DllImport(Constants.QuickLookLibrary)] extern static /* CGImageRef */ IntPtr QLThumbnailImageCreate (/* CFAllocatorRef */ IntPtr allocator, /* CFUrlRef */ IntPtr url, CGSize maxThumbnailSize, /* CFDictionaryRef */ IntPtr options); #if NET @@ -76,12 +76,12 @@ public static partial class QLThumbnailImage { dictionary.LowlevelSetObject ((NSNumber) scaleFactor, OptionScaleFactorKey.Handle); dictionary.LowlevelSetObject (iconMode ? CFBoolean.TrueHandle : CFBoolean.FalseHandle, OptionIconModeKey.Handle); } - + var handle = QLThumbnailImageCreate (IntPtr.Zero, url.Handle, maxThumbnailSize, dictionary.GetHandle ()); GC.KeepAlive (dictionary); if (handle != IntPtr.Zero) return new CGImage (handle, true); - + return null; } } diff --git a/src/SceneKit/Defs.cs b/src/SceneKit/Defs.cs index 8ebb75bc6fdc..8f1d6da893bf 100644 --- a/src/SceneKit/Defs.cs +++ b/src/SceneKit/Defs.cs @@ -276,12 +276,10 @@ public enum SCNAntialiasingMode : ulong { Multisampling2X, Multisampling4X, #if MONOMAC || __MACCATALYST__ - [NoiOS] - [NoTV] + [NoiOS][NoTV] [NoMacCatalyst] Multisampling8X, - [NoiOS] - [NoTV] + [NoiOS][NoTV] [NoMacCatalyst] Multisampling16X, #endif @@ -363,17 +361,11 @@ public enum SCNRenderingApi : ulong { [NoMac] OpenGLES2, #else - [NoiOS] - [NoTV] - [NoMacCatalyst] + [NoiOS][NoTV][NoMacCatalyst] OpenGLLegacy, - [NoiOS] - [NoTV] - [NoMacCatalyst] + [NoiOS][NoTV][NoMacCatalyst] OpenGLCore32, - [NoiOS] - [NoTV] - [NoMacCatalyst] + [NoiOS][NoTV][NoMacCatalyst] OpenGLCore41, #endif } diff --git a/src/SceneKit/SCNMatrix4_dotnet.cs b/src/SceneKit/SCNMatrix4_dotnet.cs index 6f685e707d19..ffb1efc0484d 100644 --- a/src/SceneKit/SCNMatrix4_dotnet.cs +++ b/src/SceneKit/SCNMatrix4_dotnet.cs @@ -53,7 +53,7 @@ namespace SceneKit { /// [Serializable] public struct SCNMatrix4 : IEquatable { - #region Fields +#region Fields /* * SCNMatrix4 is defined like this for iOS, tvOS and watchOS: @@ -104,9 +104,9 @@ public struct SCNMatrix4 : IEquatable { /// public readonly static SCNMatrix4 Identity = new SCNMatrix4 (SCNVector4.UnitX, SCNVector4.UnitY, SCNVector4.UnitZ, SCNVector4.UnitW); - #endregion +#endregion - #region Constructors +#region Constructors /// /// Constructs a new instance. @@ -162,11 +162,11 @@ public SCNMatrix4 (CoreAnimation.CATransform3D transform) Column3 = new SCNVector4 ((pfloat) transform.M41, (pfloat) transform.M42, (pfloat) transform.M43, (pfloat) transform.M44); } - #endregion +#endregion - #region Public Members +#region Public Members - #region Properties +#region Properties /// /// The determinant of this matrix @@ -315,11 +315,11 @@ public SCNVector4 Row3 { /// public pfloat M44 { get { return Column3.W; } set { Column3.W = value; } } - #endregion +#endregion - #region Instance +#region Instance - #region public void Invert() +#region public void Invert() /// /// Converts this instance into its inverse. @@ -329,9 +329,9 @@ public void Invert () this = SCNMatrix4.Invert (this); } - #endregion +#endregion - #region public void Transpose() +#region public void Transpose() /// /// Converts this instance into its transpose. @@ -341,13 +341,13 @@ public void Transpose () this = SCNMatrix4.Transpose (this); } - #endregion +#endregion - #endregion +#endregion - #region Static +#region Static - #region CreateFromColumns +#region CreateFromColumns public static SCNMatrix4 CreateFromColumns (SCNVector4 column0, SCNVector4 column1, SCNVector4 column2, SCNVector4 column3) { @@ -368,9 +368,9 @@ public static void CreateFromColumns (SCNVector4 column0, SCNVector4 column1, SC result.Column3 = column3; } - #endregion +#endregion - #region CreateFromAxisAngle +#region CreateFromAxisAngle /// /// Build a rotation matrix from the specified axis/angle rotation. @@ -424,9 +424,9 @@ static void CreateFromAxisAngle (float x, float y, float z, float angle, out SCN var m33 = t * z * z + cos; result = new SCNMatrix4 ( - m11, m21, m31, 0.0f, - m12, m22, m32, 0.0f, - m13, m23, m33, 0.0f, + m11, m21, m31, 0.0f, + m12, m22, m32, 0.0f, + m13, m23, m33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } @@ -455,9 +455,9 @@ static void CreateFromAxisAngle (double x, double y, double z, double angle, out var m33 = (pfloat) (t * z * z + cos); result = new SCNMatrix4 ( - m11, m21, m31, 0.0f, - m12, m22, m32, 0.0f, - m13, m23, m33, 0.0f, + m11, m21, m31, 0.0f, + m12, m22, m32, 0.0f, + m13, m23, m33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } @@ -474,9 +474,9 @@ public static SCNMatrix4 CreateFromAxisAngle (SCNVector3 axis, pfloat angle) return result; } - #endregion +#endregion - #region CreateRotation[XYZ] +#region CreateRotation[XYZ] /// /// Builds a rotation matrix for a rotation around the x-axis. @@ -489,10 +489,10 @@ public static void CreateRotationX (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - 1, 0, 0, 0, - 0, cos, -sin, 0, - 0, sin, cos, 0, - 0, 0, 0, 1); + 1, 0, 0, 0, + 0, cos, -sin, 0, + 0, sin, cos, 0, + 0, 0, 0, 1); } /// @@ -518,10 +518,10 @@ public static void CreateRotationY (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - cos, 0, sin, 0, - 0, 1, 0, 0, - -sin, 0, cos, 0, - 0, 0, 0, 1); + cos, 0, sin, 0, + 0, 1, 0, 0, + -sin, 0, cos, 0, + 0, 0, 0, 1); } /// @@ -547,10 +547,10 @@ public static void CreateRotationZ (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - cos, -sin, 0, 0, - sin, cos, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); + cos, -sin, 0, 0, + sin, cos, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); } /// @@ -565,9 +565,9 @@ public static SCNMatrix4 CreateRotationZ (pfloat angle) return result; } - #endregion +#endregion - #region CreateTranslation +#region CreateTranslation /// /// Creates a translation matrix. @@ -621,9 +621,9 @@ public static SCNMatrix4 CreateTranslation (SCNVector3 vector) return result; } - #endregion +#endregion - #region CreateOrthographic +#region CreateOrthographic /// /// Creates an orthographic projection matrix. @@ -653,9 +653,9 @@ public static SCNMatrix4 CreateOrthographic (pfloat width, pfloat height, pfloat return result; } - #endregion +#endregion - #region CreateOrthographicOffCenter +#region CreateOrthographicOffCenter /// /// Creates an orthographic projection matrix. @@ -702,9 +702,9 @@ public static SCNMatrix4 CreateOrthographicOffCenter (pfloat left, pfloat right, return result; } - #endregion +#endregion - #region CreatePerspectiveFieldOfView +#region CreatePerspectiveFieldOfView /// /// Creates a perspective projection matrix. @@ -770,9 +770,9 @@ public static SCNMatrix4 CreatePerspectiveFieldOfView (pfloat fovy, pfloat aspec return result; } - #endregion +#endregion - #region CreatePerspectiveOffCenter +#region CreatePerspectiveOffCenter /// /// Creates a perspective projection matrix. @@ -809,10 +809,10 @@ public static void CreatePerspectiveOffCenter (pfloat left, pfloat right, pfloat pfloat d = -(2.0f * zFar * zNear) / (zFar - zNear); result = new SCNMatrix4 ( - x, 0, a, 0, - 0, y, b, 0, - 0, 0, c, d, - 0, 0, -1, 0); + x, 0, a, 0, + 0, y, b, 0, + 0, 0, c, d, + 0, 0, -1, 0); } /// @@ -840,9 +840,9 @@ public static SCNMatrix4 CreatePerspectiveOffCenter (pfloat left, pfloat right, return result; } - #endregion +#endregion - #region Scale Functions +#region Scale Functions /// /// Build a scaling matrix @@ -880,9 +880,9 @@ public static SCNMatrix4 Scale (pfloat x, pfloat y, pfloat z) 0, 0, 0, 1); } - #endregion +#endregion - #region Rotation Functions +#region Rotation Functions /// /// Build a rotation matrix from a quaternion @@ -913,9 +913,9 @@ public static SCNMatrix4 Rotate (Quaterniond q) CreateFromAxisAngle (axis, angle, out result); return result; } - #endregion +#endregion - #region Camera Helper Functions +#region Camera Helper Functions /// /// Build a world space to camera space matrix @@ -931,9 +931,9 @@ public static SCNMatrix4 LookAt (SCNVector3 eye, SCNVector3 target, SCNVector3 u SCNVector3 y = SCNVector3.Normalize (SCNVector3.Cross (z, x)); SCNMatrix4 rot = new SCNMatrix4 ( - x.X, x.Y, x.Z, 0.0f, - y.X, y.Y, y.Z, 0.0f, - z.X, z.Y, z.Z, 0.0f, + x.X, x.Y, x.Z, 0.0f, + y.X, y.Y, y.Z, 0.0f, + z.X, z.Y, z.Z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); SCNMatrix4 trans = SCNMatrix4.CreateTranslation (-eye); @@ -959,9 +959,9 @@ public static SCNMatrix4 LookAt (pfloat eyeX, pfloat eyeY, pfloat eyeZ, pfloat t return LookAt (new SCNVector3 (eyeX, eyeY, eyeZ), new SCNVector3 (targetX, targetY, targetZ), new SCNVector3 (upX, upY, upZ)); } - #endregion +#endregion - #region Multiply Functions +#region Multiply Functions #if XAMCORE_5_0 /// @@ -987,7 +987,7 @@ public static SCNMatrix4 LookAt (pfloat eyeX, pfloat eyeY, pfloat eyeZ, pfloat t #if XAMCORE_5_0 public static SCNMatrix4 Mult (SCNMatrix4 firstTransformation, SCNMatrix4 secondTransformation) #else - public static SCNMatrix4 Mult (SCNMatrix4 left, SCNMatrix4 right) + public static SCNMatrix4 Mult(SCNMatrix4 left, SCNMatrix4 right) #endif { SCNMatrix4 result; @@ -1024,7 +1024,7 @@ public static SCNMatrix4 Mult (SCNMatrix4 left, SCNMatrix4 right) #if XAMCORE_5_0 public static void Mult (ref SCNMatrix4 firstTransformation, ref SCNMatrix4 secondTransformation, out SCNMatrix4 result) #else - public static void Mult (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) + public static void Mult(ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) #endif { // the matrices are reversed: https://github.com/xamarin/xamarin-macios/issues/15094#issuecomment-1139699662 @@ -1038,7 +1038,7 @@ public static void Mult (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatri // Multiply two matrices in the order you'd expect (left * right). static void MatrixMultiply (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) { - result = new SCNMatrix4 ( + result = new SCNMatrix4( left.Column0.X * right.Column0.X + left.Column1.X * right.Column0.Y + left.Column2.X * right.Column0.Z + left.Column3.X * right.Column0.W, left.Column0.X * right.Column1.X + left.Column1.X * right.Column1.Y + left.Column2.X * right.Column1.Z + left.Column3.X * right.Column1.W, left.Column0.X * right.Column2.X + left.Column1.X * right.Column2.Y + left.Column2.X * right.Column2.Z + left.Column3.X * right.Column2.W, @@ -1060,9 +1060,9 @@ static void MatrixMultiply (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMa left.Column0.W * right.Column3.X + left.Column1.W * right.Column3.Y + left.Column2.W * right.Column3.Z + left.Column3.W * right.Column3.W); } - #endregion +#endregion - #region Invert Functions +#region Invert Functions static bool InvertSoftware (SCNMatrix4 matrix, out SCNMatrix4 result) { @@ -1094,9 +1094,9 @@ static bool InvertSoftware (SCNMatrix4 matrix, out SCNMatrix4 result) #endif { result = new SCNMatrix4 (pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN); + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN); return false; } @@ -1154,9 +1154,9 @@ public static SCNMatrix4 Invert (SCNMatrix4 matrix) return inverse; } - #endregion +#endregion - #region Transpose +#region Transpose /// /// Calculate the transpose of the given matrix @@ -1179,11 +1179,11 @@ public static void Transpose (ref SCNMatrix4 mat, out SCNMatrix4 result) result = new SCNMatrix4 (mat.Column0, mat.Column1, mat.Column2, mat.Column3); } - #endregion +#endregion - #endregion +#endregion - #region Operators +#region Operators /// /// Matrix multiplication @@ -1218,11 +1218,11 @@ public static void Transpose (ref SCNMatrix4 mat, out SCNMatrix4 result) return !left.Equals (right); } - #endregion +#endregion - #region Overrides +#region Overrides - #region public override string ToString() +#region public override string ToString() /// /// Returns a System.String that represents the current SCNMatrix4. @@ -1233,9 +1233,9 @@ public override string ToString () return String.Format ("{0}\n{1}\n{2}\n{3}", Row0, Row1, Row2, Row3); } - #endregion +#endregion - #region public override int GetHashCode() +#region public override int GetHashCode() /// /// Returns the hashcode for this instance. @@ -1243,12 +1243,12 @@ public override string ToString () /// A System.Int32 containing the unique hashcode for this instance. public override int GetHashCode () { - return HashCode.Combine (Column0, Column1, Column2, Column3); + return HashCode.Combine(Column0, Column1, Column2, Column3); } - #endregion +#endregion - #region public override bool Equals(object obj) +#region public override bool Equals(object obj) /// /// Indicates whether this instance and a specified object are equal. @@ -1263,13 +1263,13 @@ public override bool Equals (object? obj) return this.Equals ((SCNMatrix4) obj); } - #endregion +#endregion - #endregion +#endregion - #endregion +#endregion - #region IEquatable Members +#region IEquatable Members /// Indicates whether the current matrix is equal to another matrix. /// An matrix to compare with this matrix. @@ -1283,17 +1283,17 @@ public bool Equals (SCNMatrix4 other) Column3 == other.Column3; } - #endregion +#endregion static void ToAxisAngle (Quaternion q, out Vector3 axis, out float angle) { if (q.W > 1.0f) - q = Quaternion.Normalize (q); + q = Quaternion.Normalize (q); angle = 2.0f * (float) System.Math.Acos (q.W); // angle var den = (float) System.Math.Sqrt (1.0 - q.W * q.W); if (den > 0.0001f) { - axis = new Vector3 (q.X, q.Y, q.Z) / den; + axis = new Vector3(q.X, q.Y, q.Z) / den; } else { // This occurs when the angle is zero. // Not a problem: just set an arbitrary normalized axis. diff --git a/src/SceneKit/SCNQuaternion.cs b/src/SceneKit/SCNQuaternion.cs index a71754c5f07c..24c45a7529e1 100644 --- a/src/SceneKit/SCNQuaternion.cs +++ b/src/SceneKit/SCNQuaternion.cs @@ -60,10 +60,10 @@ namespace SceneKit { /// Represents a Quaternion. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -102,7 +102,7 @@ public SCNQuaternion (pfloat x, pfloat y, pfloat z, pfloat w) public SCNQuaternion (ref Matrix3 matrix) { #if NET - double scale = System.Math.Pow (matrix.GetDeterminant (), 1.0d / 3.0d); + double scale = System.Math.Pow (matrix.GetDeterminant (), 1.0d / 3.0d); #else double scale = System.Math.Pow (matrix.Determinant, 1.0d / 3.0d); #endif @@ -121,10 +121,10 @@ public SCNQuaternion (ref Matrix3 matrix) } #if NET - public SCNQuaternion (Quaternion quaternion) - : this (quaternion.X, quaternion.Y, quaternion.Z, quaternion.W) - { - } + public SCNQuaternion (Quaternion quaternion) + : this (quaternion.X, quaternion.Y, quaternion.Z, quaternion.W) + { + } #else public SCNQuaternion (Quaternion openTkQuaternion) : this (new SCNVector3 (openTkQuaternion.XYZ), openTkQuaternion.W) { diff --git a/src/SceneKit/SCNVector3.cs b/src/SceneKit/SCNVector3.cs index 5242ae663659..19c4abf1c243 100644 --- a/src/SceneKit/SCNVector3.cs +++ b/src/SceneKit/SCNVector3.cs @@ -61,10 +61,10 @@ namespace SceneKit { /// The Vector3 structure is suitable for interoperation with unmanaged code requiring three consecutive floats. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -771,17 +771,17 @@ public static SCNVector3 TransformVector (SCNVector3 vec, SCNMatrix4 mat) public static void TransformVector (ref SCNVector3 vec, ref SCNMatrix4 mat, out SCNVector3 result) { #if NET - result.X = vec.X * mat.Row0.X + - vec.Y * mat.Row0.Y + - vec.Z * mat.Row0.Z; + result.X = vec.X * mat.Row0.X + + vec.Y * mat.Row0.Y + + vec.Z * mat.Row0.Z; - result.Y = vec.X * mat.Row1.X + - vec.Y * mat.Row1.Y + - vec.Z * mat.Row1.Z; + result.Y = vec.X * mat.Row1.X + + vec.Y * mat.Row1.Y + + vec.Z * mat.Row1.Z; - result.Z = vec.X * mat.Row2.X + - vec.Y * mat.Row2.Y + - vec.Z * mat.Row2.Z; + result.Z = vec.X * mat.Row2.X + + vec.Y * mat.Row2.Y + + vec.Z * mat.Row2.Z; #else result.X = vec.X * mat.Row0.X + vec.Y * mat.Row1.X + @@ -803,7 +803,7 @@ public static void TransformVector (ref SCNVector3 vec, ref SCNMatrix4 mat, out /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// - /// The column-based normal to transform + /// The column-based normal to transform /// The desired transformation /// The transformed normal #else @@ -828,7 +828,7 @@ public static SCNVector3 TransformNormal (SCNVector3 norm, SCNMatrix4 mat) /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// - /// The column-based normal to transform + /// The column-based normal to transform /// The desired transformation /// The transformed normal #else @@ -853,7 +853,7 @@ public static void TransformNormal (ref SCNVector3 norm, ref SCNMatrix4 mat, out /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// - /// The column-based normal to transform + /// The column-based normal to transform /// The inverse of the desired transformation /// The transformed normal #else @@ -878,7 +878,7 @@ public static SCNVector3 TransformNormalInverse (SCNVector3 norm, SCNMatrix4 inv /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// - /// The column-based normal to transform + /// The column-based normal to transform /// The inverse of the desired transformation /// The transformed normal #else @@ -894,17 +894,17 @@ public static SCNVector3 TransformNormalInverse (SCNVector3 norm, SCNMatrix4 inv public static void TransformNormalInverse (ref SCNVector3 norm, ref SCNMatrix4 invMat, out SCNVector3 result) { #if NET - result.X = norm.X * invMat.Column0.X + - norm.Y * invMat.Column0.Y + - norm.Z * invMat.Column0.Z; + result.X = norm.X * invMat.Column0.X + + norm.Y * invMat.Column0.Y + + norm.Z * invMat.Column0.Z; - result.Y = norm.X * invMat.Column1.X + - norm.Y * invMat.Column1.Y + - norm.Z * invMat.Column1.Z; + result.Y = norm.X * invMat.Column1.X + + norm.Y * invMat.Column1.Y + + norm.Z * invMat.Column1.Z; - result.Z = norm.X * invMat.Column2.X + - norm.Y * invMat.Column2.Y + - norm.Z * invMat.Column2.Z; + result.Z = norm.X * invMat.Column2.X + + norm.Y * invMat.Column2.Y + + norm.Z * invMat.Column2.Z; #else result.X = norm.X * invMat.Row0.X + norm.Y * invMat.Row0.Y + @@ -922,7 +922,7 @@ public static void TransformNormalInverse (ref SCNVector3 norm, ref SCNMatrix4 i #if NET /// Transform a Position by the given Matrix - /// The column-based position to transform + /// The column-based position to transform /// The desired transformation /// The transformed position #else @@ -939,7 +939,7 @@ public static SCNVector3 TransformPosition (SCNVector3 pos, SCNMatrix4 mat) #if NET /// Transform a Position by the given Matrix - /// The column-based position to transform + /// The column-based position to transform /// The desired transformation /// The transformed position #else @@ -951,20 +951,20 @@ public static SCNVector3 TransformPosition (SCNVector3 pos, SCNMatrix4 mat) public static void TransformPosition (ref SCNVector3 pos, ref SCNMatrix4 mat, out SCNVector3 result) { #if NET - result.X = mat.Row0.X * pos.X + - mat.Row0.Y * pos.Y + - mat.Row0.Z * pos.Z + - mat.Row0.W; - - result.Y = mat.Row1.X * pos.X + - mat.Row1.Y * pos.Y + - mat.Row1.Z * pos.Z + - mat.Row1.W; - - result.Z = mat.Row2.X * pos.X + - mat.Row2.Y * pos.Y + - mat.Row2.Z * pos.Z + - mat.Row2.W; + result.X = mat.Row0.X * pos.X + + mat.Row0.Y * pos.Y + + mat.Row0.Z * pos.Z + + mat.Row0.W; + + result.Y = mat.Row1.X * pos.X + + mat.Row1.Y * pos.Y + + mat.Row1.Z * pos.Z + + mat.Row1.W; + + result.Z = mat.Row2.X * pos.X + + mat.Row2.Y * pos.Y + + mat.Row2.Z * pos.Z + + mat.Row2.W; #else result.X = pos.X * mat.Row0.X + pos.Y * mat.Row1.X + @@ -985,7 +985,7 @@ public static void TransformPosition (ref SCNVector3 pos, ref SCNMatrix4 mat, ou #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -1002,7 +1002,7 @@ public static SCNVector4 Transform (SCNVector3 vec, SCNMatrix4 mat) #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else diff --git a/src/SceneKit/SCNVector4.cs b/src/SceneKit/SCNVector4.cs index 5e95a1576bd9..e28a85ffbe38 100644 --- a/src/SceneKit/SCNVector4.cs +++ b/src/SceneKit/SCNVector4.cs @@ -60,10 +60,10 @@ namespace SceneKit { /// The Vector4 structure is suitable for interoperation with unmanaged code requiring four consecutive floats. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -836,7 +836,7 @@ public static void BaryCentric (ref SCNVector4 a, ref SCNVector4 b, ref SCNVecto #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -853,7 +853,7 @@ public static SCNVector4 Transform (SCNVector4 vec, SCNMatrix4 mat) #if NET /// Transform a Vector by the given Matrix. - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -865,25 +865,25 @@ public static SCNVector4 Transform (SCNVector4 vec, SCNMatrix4 mat) public static void Transform (ref SCNVector4 vec, ref SCNMatrix4 mat, out SCNVector4 result) { #if NET - result.X = vec.X * mat.Column0.X + - vec.Y * mat.Column1.X + - vec.Z * mat.Column2.X + - vec.W * mat.Column3.X; - - result.Y = vec.X * mat.Column0.Y + - vec.Y * mat.Column1.Y + - vec.Z * mat.Column2.Y + - vec.W * mat.Column3.Y; - - result.Z = vec.X * mat.Column0.Z + - vec.Y * mat.Column1.Z + - vec.Z * mat.Column2.Z + - vec.W * mat.Column3.Z; - - result.W = vec.X * mat.Column0.W + - vec.Y * mat.Column1.W + - vec.Z * mat.Column2.W + - vec.W * mat.Column3.W; + result.X = vec.X * mat.Column0.X + + vec.Y * mat.Column1.X + + vec.Z * mat.Column2.X + + vec.W * mat.Column3.X; + + result.Y = vec.X * mat.Column0.Y + + vec.Y * mat.Column1.Y + + vec.Z * mat.Column2.Y + + vec.W * mat.Column3.Y; + + result.Z = vec.X * mat.Column0.Z + + vec.Y * mat.Column1.Z + + vec.Z * mat.Column2.Z + + vec.W * mat.Column3.Z; + + result.W = vec.X * mat.Column0.W + + vec.Y * mat.Column1.W + + vec.Z * mat.Column2.W + + vec.W * mat.Column3.W; #else result.X = vec.X * mat.Row0.X + vec.Y * mat.Row1.X + diff --git a/src/Security/Authorization.cs b/src/Security/Authorization.cs index da53d2a4d823..3b62567fedb2 100644 --- a/src/Security/Authorization.cs +++ b/src/Security/Authorization.cs @@ -48,21 +48,21 @@ namespace Security { #endif // Untyped enum in ObjC public enum AuthorizationStatus { - Success = 0, - InvalidSet = -60001, - InvalidRef = -60002, - InvalidTag = -60003, - InvalidPointer = -60004, - Denied = -60005, - Canceled = -60006, - InteractionNotAllowed = -60007, - Internal = -60008, - ExternalizeNotAllowed = -60009, - InternalizeNotAllowed = -60010, - InvalidFlags = -60011, - ToolExecuteFailure = -60031, - ToolEnvironmentError = -60032, - BadAddress = -60033, + Success = 0, + InvalidSet = -60001, + InvalidRef = -60002, + InvalidTag = -60003, + InvalidPointer = -60004, + Denied = -60005, + Canceled = -60006, + InteractionNotAllowed = -60007, + Internal = -60008, + ExternalizeNotAllowed = -60009, + InternalizeNotAllowed = -60010, + InvalidFlags = -60011, + ToolExecuteFailure = -60031, + ToolEnvironmentError = -60032, + BadAddress = -60033, } #if NET @@ -115,7 +115,7 @@ public class AuthorizationParameters { public class AuthorizationEnvironment { public string? Username; public string? Password; - public bool AddToSharedCredentialPool; + public bool AddToSharedCredentialPool; } #if NET @@ -140,7 +140,7 @@ struct AuthorizationItem { #endif unsafe struct AuthorizationItemSet { public int /* UInt32 */ count; - public AuthorizationItem* /* AuthorizationItem* */ ptrToAuthorization; + public AuthorizationItem * /* AuthorizationItem* */ ptrToAuthorization; } #if NET @@ -151,7 +151,7 @@ unsafe struct AuthorizationItemSet { #endif public unsafe class Authorization : DisposableObject { [DllImport (Constants.SecurityLibrary)] - unsafe extern static int /* OSStatus = int */ AuthorizationCreate (AuthorizationItemSet* rights, AuthorizationItemSet* environment, AuthorizationFlags flags, IntPtr* auth); + unsafe extern static int /* OSStatus = int */ AuthorizationCreate (AuthorizationItemSet *rights, AuthorizationItemSet *environment, AuthorizationFlags flags, IntPtr* auth); #if NET [SupportedOSPlatform ("maccatalyst")] @@ -170,7 +170,7 @@ public unsafe class Authorization : DisposableObject { [DllImport (Constants.SecurityLibrary)] extern static int /* OSStatus = int */ AuthorizationFree (IntPtr handle, AuthorizationFlags flags); - + [Preserve (Conditional = true)] internal Authorization (NativeHandle handle, bool owns) : base (handle, owns) @@ -186,7 +186,7 @@ internal Authorization (NativeHandle handle, bool owns) #endif public int ExecuteWithPrivileges (string pathToTool, AuthorizationFlags flags, string []? args) { - string? []? arguments = args!; + string?[]? arguments = args!; if (arguments is not null) { // The arguments array must be null-terminated, so make sure that's the case @@ -213,19 +213,19 @@ protected override void Dispose (bool disposing) { Dispose (0, disposing); } - + public virtual void Dispose (AuthorizationFlags flags, bool disposing) { if (Handle != IntPtr.Zero && Owns) AuthorizationFree (Handle, flags); base.Dispose (disposing); } - + public static Authorization? Create (AuthorizationFlags flags) { return Create (null, null, flags); } - + static void EncodeString (ref AuthorizationItem item, string key, string? value) { item.name = Marshal.StringToHGlobalAuto (key); @@ -234,32 +234,32 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) item.valueLen = value.Length; } } - + public static Authorization? Create (AuthorizationParameters? parameters, AuthorizationEnvironment? environment, AuthorizationFlags flags) { AuthorizationItemSet pars = new AuthorizationItemSet (); - AuthorizationItemSet* ppars = null; - AuthorizationItem* pitems = null; + AuthorizationItemSet *ppars = null; + AuthorizationItem *pitems = null; AuthorizationItemSet env = new AuthorizationItemSet (); - AuthorizationItemSet* penv = null; - AuthorizationItem* eitems = null; + AuthorizationItemSet *penv = null; + AuthorizationItem *eitems = null; int code; IntPtr auth; try { unsafe { - if (parameters is not null) { + if (parameters is not null){ ppars = &pars; - pars.ptrToAuthorization = (AuthorizationItem*) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 2); + pars.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 2); if (parameters.PathToSystemPrivilegeTool is not null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "system.privilege.admin", parameters.PathToSystemPrivilegeTool); if (parameters.IconPath is not null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "icon", parameters.IconPath); } - if (environment is not null || (parameters is not null && parameters.Prompt is not null)) { + if (environment is not null || (parameters is not null && parameters.Prompt is not null)){ penv = &env; - env.ptrToAuthorization = (AuthorizationItem*) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 4); - if (environment is not null) { + env.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 4); + if (environment is not null){ if (environment.Username is not null) EncodeString (ref env.ptrToAuthorization [env.count++], "username", environment.Username); if (environment.Password is not null) @@ -267,7 +267,7 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) if (environment.AddToSharedCredentialPool) EncodeString (ref env.ptrToAuthorization [env.count++], "shared", null); } - if (parameters is not null) { + if (parameters is not null){ if (parameters.Prompt is not null) EncodeString (ref env.ptrToAuthorization [env.count++], "prompt", parameters.Prompt); } @@ -278,20 +278,20 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) return new Authorization (auth, true); } } finally { - if (ppars is not null) { - for (int i = 0; i < pars.count; i++) { + if (ppars is not null){ + for (int i = 0; i < pars.count; i++){ Marshal.FreeHGlobal (pars.ptrToAuthorization [i].name); Marshal.FreeHGlobal (pars.ptrToAuthorization [i].value); } - Marshal.FreeHGlobal ((IntPtr) pars.ptrToAuthorization); + Marshal.FreeHGlobal ((IntPtr)pars.ptrToAuthorization); } - if (penv is not null) { - for (int i = 0; i < env.count; i++) { + if (penv is not null){ + for (int i = 0; i < env.count; i++){ Marshal.FreeHGlobal (env.ptrToAuthorization [i].name); if (env.ptrToAuthorization [i].value != IntPtr.Zero) Marshal.FreeHGlobal (env.ptrToAuthorization [i].value); } - Marshal.FreeHGlobal ((IntPtr) env.ptrToAuthorization); + Marshal.FreeHGlobal ((IntPtr)env.ptrToAuthorization); } } } diff --git a/src/Security/Enums.cs b/src/Security/Enums.cs index 5db43f766fcd..e8266599bef3 100644 --- a/src/Security/Enums.cs +++ b/src/Security/Enums.cs @@ -316,7 +316,7 @@ public enum SecStatusCode { InvalidCRLAuthority = -67827, /* The CRL authority was not valid. */ #if MONOMAC [Obsolete ("Use InvalidCRLAuthority.")] - InvaldCRLAuthority = InvalidCRLAuthority, + InvaldCRLAuthority = InvalidCRLAuthority, #endif InvalidCRLEncoding = -67828, /* The CRL encoding was not valid. */ InvalidCRLType = -67829, /* The CRL type was not valid. */ @@ -345,7 +345,7 @@ public enum SecStatusCode { InvalidTupleCredentials = -67852, /* The tuple credentials are not valid. */ #if MONOMAC [Obsolete ("Use InvalidTupleCredentials.")] - InvalidTupleCredendtials = InvalidTupleCredentials, + InvalidTupleCredendtials = InvalidTupleCredentials, #endif InvalidEncoding = -67853, /* The encoding was not valid. */ InvalidValidityPeriod = -67854, /* The validity period was not valid. */ diff --git a/src/Security/Items.cs b/src/Security/Items.cs index 5c7fb45b6de7..6f49c0e74dfb 100644 --- a/src/Security/Items.cs +++ b/src/Security/Items.cs @@ -338,11 +338,11 @@ public static SecStatusCode Update (SecRecord query, SecRecord newAttributes) extern static SecStatusCode SecKeychainAddGenericPassword ( IntPtr keychain, int serviceNameLength, - byte []? serviceName, + byte[]? serviceName, int accountNameLength, - byte []? accountName, + byte[]? accountName, int passwordLength, - byte [] passwordData, + byte[] passwordData, IntPtr itemRef); #if NET @@ -370,18 +370,18 @@ unsafe extern static SecStatusCode SecKeychainFindGenericPassword ( extern static SecStatusCode SecKeychainAddInternetPassword ( IntPtr keychain, int serverNameLength, - byte []? serverName, + byte[]? serverName, int securityDomainLength, - byte []? securityDomain, + byte[]? securityDomain, int accountNameLength, - byte []? accountName, + byte[]? accountName, int pathLength, - byte []? path, + byte[]? path, short port, IntPtr protocol, IntPtr authenticationType, int passwordLength, - byte [] passwordData, + byte[] passwordData, IntPtr itemRef); #if NET @@ -418,30 +418,30 @@ unsafe extern static SecStatusCode SecKeychainFindInternetPassword ( public static SecStatusCode AddInternetPassword ( string serverName, string accountName, - byte [] password, + byte[] password, SecProtocol protocolType = SecProtocol.Http, short port = 0, string? path = null, SecAuthenticationType authenticationType = SecAuthenticationType.Default, string? securityDomain = null) { - byte []? serverNameBytes = null; - byte []? securityDomainBytes = null; - byte []? accountNameBytes = null; - byte []? pathBytes = null; - + byte[]? serverNameBytes = null; + byte[]? securityDomainBytes = null; + byte[]? accountNameBytes = null; + byte[]? pathBytes = null; + if (!String.IsNullOrEmpty (serverName)) serverNameBytes = System.Text.Encoding.UTF8.GetBytes (serverName); - + if (!String.IsNullOrEmpty (securityDomain)) securityDomainBytes = System.Text.Encoding.UTF8.GetBytes (securityDomain); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - + if (!String.IsNullOrEmpty (path)) pathBytes = System.Text.Encoding.UTF8.GetBytes (path); - + return SecKeychainAddInternetPassword ( IntPtr.Zero, serverNameBytes?.Length ?? 0, @@ -459,12 +459,12 @@ public static SecStatusCode AddInternetPassword ( password!, IntPtr.Zero); } - - - public static SecStatusCode FindInternetPassword ( + + + public static SecStatusCode FindInternetPassword( string serverName, string accountName, - out byte []? password, + out byte[]? password, SecProtocol protocolType = SecProtocol.Http, short port = 0, string? path = null, @@ -472,36 +472,36 @@ public static SecStatusCode FindInternetPassword ( string? securityDomain = null) { password = null; - - byte []? serverBytes = null; - byte []? securityDomainBytes = null; - byte []? accountNameBytes = null; - byte []? pathBytes = null; + + byte[]? serverBytes = null; + byte[]? securityDomainBytes = null; + byte[]? accountNameBytes = null; + byte[]? pathBytes = null; IntPtr passwordPtr = IntPtr.Zero; - + try { if (!String.IsNullOrEmpty (serverName)) serverBytes = System.Text.Encoding.UTF8.GetBytes (serverName); - + if (!String.IsNullOrEmpty (securityDomain)) securityDomainBytes = System.Text.Encoding.UTF8.GetBytes (securityDomain); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - - if (!String.IsNullOrEmpty (path)) + + if (!String.IsNullOrEmpty(path)) pathBytes = System.Text.Encoding.UTF8.GetBytes (path); - + int passwordLength = 0; - + SecStatusCode code; unsafe { fixed (byte* serverBytesPtr = serverBytes) { fixed (byte* securityDomainBytesPtr = securityDomainBytes) { fixed (byte* accountNameBytesPtr = accountNameBytes) { fixed (byte* pathBytesPtr = pathBytes) { - code = SecKeychainFindInternetPassword ( + code = SecKeychainFindInternetPassword( IntPtr.Zero, serverBytes?.Length ?? 0, serverBytesPtr, @@ -512,8 +512,8 @@ public static SecStatusCode FindInternetPassword ( pathBytes?.Length ?? 0, pathBytesPtr, port, - SecProtocolKeys.FromSecProtocol (protocolType), - KeysAuthenticationType.FromSecAuthenticationType (authenticationType), + SecProtocolKeys.FromSecProtocol(protocolType), + KeysAuthenticationType.FromSecAuthenticationType(authenticationType), &passwordLength, &passwordPtr, IntPtr.Zero); @@ -522,32 +522,32 @@ public static SecStatusCode FindInternetPassword ( } } } - + if (code == SecStatusCode.Success && passwordLength > 0) { - password = new byte [passwordLength]; - Marshal.Copy (passwordPtr, password, 0, passwordLength); + password = new byte[passwordLength]; + Marshal.Copy(passwordPtr, password, 0, passwordLength); } - + return code; - + } finally { if (passwordPtr != IntPtr.Zero) - SecKeychainItemFreeContent (IntPtr.Zero, passwordPtr); + SecKeychainItemFreeContent(IntPtr.Zero, passwordPtr); } } - public static SecStatusCode AddGenericPassword (string serviceName, string accountName, byte [] password) + public static SecStatusCode AddGenericPassword (string serviceName, string accountName, byte[] password) { - byte []? serviceNameBytes = null; - byte []? accountNameBytes = null; - + byte[]? serviceNameBytes = null; + byte[]? accountNameBytes = null; + if (!String.IsNullOrEmpty (serviceName)) serviceNameBytes = System.Text.Encoding.UTF8.GetBytes (serviceName); if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - return SecKeychainAddGenericPassword ( + return SecKeychainAddGenericPassword( IntPtr.Zero, serviceNameBytes?.Length ?? 0, serviceNameBytes, @@ -559,30 +559,30 @@ public static SecStatusCode AddGenericPassword (string serviceName, string accou ); } - public static SecStatusCode FindGenericPassword (string serviceName, string accountName, out byte []? password) + public static SecStatusCode FindGenericPassword (string serviceName, string accountName, out byte[]? password) { password = null; - byte []? serviceNameBytes = null; - byte []? accountNameBytes = null; - + byte[]? serviceNameBytes = null; + byte[]? accountNameBytes = null; + IntPtr passwordPtr = IntPtr.Zero; - + try { - + if (!String.IsNullOrEmpty (serviceName)) serviceNameBytes = System.Text.Encoding.UTF8.GetBytes (serviceName); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - + int passwordLength = 0; - + SecStatusCode code; unsafe { fixed (byte* serviceNameBytesPtr = serviceNameBytes) { fixed (byte* accountNameBytesPtr = accountNameBytes) { - code = SecKeychainFindGenericPassword ( + code = SecKeychainFindGenericPassword( IntPtr.Zero, serviceNameBytes?.Length ?? 0, serviceNameBytesPtr, @@ -595,17 +595,17 @@ public static SecStatusCode FindGenericPassword (string serviceName, string acco } } } - - if (code == SecStatusCode.Success && passwordLength > 0) { - password = new byte [passwordLength]; - Marshal.Copy (passwordPtr, password, 0, passwordLength); + + if (code == SecStatusCode.Success && passwordLength > 0){ + password = new byte[passwordLength]; + Marshal.Copy(passwordPtr, password, 0, passwordLength); } - + return code; - + } finally { if (passwordPtr != IntPtr.Zero) - SecKeychainItemFreeContent (IntPtr.Zero, passwordPtr); + SecKeychainItemFreeContent(IntPtr.Zero, passwordPtr); } } #else diff --git a/src/Security/SecCertificate2.cs b/src/Security/SecCertificate2.cs index 2f48736262d9..1ca0f1ba97e4 100644 --- a/src/Security/SecCertificate2.cs +++ b/src/Security/SecCertificate2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecCertificate2 : NativeObject { [Preserve (Conditional = true)] #if NET - internal SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) { } + internal SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) {} #else public SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Security/SecIdentity2.cs b/src/Security/SecIdentity2.cs index 0bc7f441890c..6db4f0df505b 100644 --- a/src/Security/SecIdentity2.cs +++ b/src/Security/SecIdentity2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecIdentity2 : NativeObject { #if NET [Preserve (Conditional = true)] - internal SecIdentity2 (NativeHandle handle, bool owns) : base (handle, owns) { } + internal SecIdentity2 (NativeHandle handle, bool owns) : base (handle, owns) {} #else internal SecIdentity2 (NativeHandle handle) : base (handle, false) { } [Preserve (Conditional = true)] diff --git a/src/Security/SecSharedCredential.cs b/src/Security/SecSharedCredential.cs index 149ac4d5d322..3749b610945e 100644 --- a/src/Security/SecSharedCredential.cs +++ b/src/Security/SecSharedCredential.cs @@ -17,12 +17,12 @@ public static partial class SecSharedCredential { [DllImport (Constants.SecurityLibrary)] unsafe extern static void SecAddSharedWebCredential (IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, IntPtr /* CFStringRef */ password, BlockLiteral* /* void (^completionHandler)( CFErrorRef error) ) */ completionHandler); - + #if !NET [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)] internal delegate void DActionArity1V12 (IntPtr block, IntPtr obj); #endif - + // This class bridges native block invocations that call into C# static internal class ActionTrampoline { #if !NET @@ -32,15 +32,14 @@ static internal class ActionTrampoline { #else [UnmanagedCallersOnly] #endif - internal static unsafe void Invoke (IntPtr block, IntPtr obj) - { - var descriptor = (BlockLiteral*) block; + internal static unsafe void Invoke (IntPtr block, IntPtr obj) { + var descriptor = (BlockLiteral *) block; var del = (global::System.Action) (descriptor->Target); if (del is not null) { - del (Runtime.GetNSObject (obj)); + del ( Runtime.GetNSObject (obj)); } - } - } + } + } [BindingImpl (BindingImplOptions.Optimizable)] public static void AddSharedWebCredential (string domainName, string account, string password, Action handler) @@ -79,7 +78,7 @@ public static void AddSharedWebCredential (string domainName, string account, st [Deprecated (PlatformName.MacOSX, 11,0)] #endif [DllImport (Constants.SecurityLibrary)] - unsafe extern static void SecRequestSharedWebCredential (IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, + unsafe extern static void SecRequestSharedWebCredential ( IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, BlockLiteral* /* void (^completionHandler)( CFArrayRef credentials, CFErrorRef error) */ completionHandler); #if !NET @@ -99,12 +98,11 @@ static internal class ArrayErrorActionTrampoline { #else [UnmanagedCallersOnly] #endif - internal static unsafe void Invoke (IntPtr block, IntPtr array, IntPtr err) - { - var descriptor = (BlockLiteral*) block; + internal static unsafe void Invoke (IntPtr block, IntPtr array, IntPtr err) { + var descriptor = (BlockLiteral *) block; var del = (global::System.Action) (descriptor->Target); if (del is not null) - del (Runtime.GetNSObject (array), Runtime.GetNSObject (err)); + del ( Runtime.GetNSObject (array), Runtime.GetNSObject (err)); } } @@ -128,7 +126,7 @@ public static void RequestSharedWebCredential (string domainName, string account [Deprecated (PlatformName.MacOSX, 11,0, message: "Use 'ASAuthorizationPasswordRequest' instead.")] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public static void RequestSharedWebCredential (string domainName, string account, Action handler) + public static void RequestSharedWebCredential (string domainName, string account, Action handler) { Action onComplete = (NSArray a, NSError e) => { var creds = new SecSharedCredentialInfo [a.Count]; diff --git a/src/Security/SecTrust2.cs b/src/Security/SecTrust2.cs index 50f338b88ab3..fec07746c4eb 100644 --- a/src/Security/SecTrust2.cs +++ b/src/Security/SecTrust2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecTrust2 : NativeObject { [Preserve (Conditional = true)] #if NET - internal SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) { } + internal SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) {} #else public SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Simd/MathHelper.cs b/src/Simd/MathHelper.cs index 5739adfe867a..2f2e0a93470b 100644 --- a/src/Simd/MathHelper.cs +++ b/src/Simd/MathHelper.cs @@ -16,7 +16,8 @@ static class MathHelper { /// internal static float InverseSqrtFast (float x) { - unsafe { + unsafe + { float xhalf = 0.5f * x; int i = *(int*) &x; // Read bits as integer. i = 0x5f375a86 - (i >> 1); // Make an initial guess for Newton-Raphson approximation diff --git a/src/Simd/MatrixFloat3x3RM.cs b/src/Simd/MatrixFloat3x3RM.cs index 66aa43926348..a4cc13c99fe1 100644 --- a/src/Simd/MatrixFloat3x3RM.cs +++ b/src/Simd/MatrixFloat3x3RM.cs @@ -25,10 +25,12 @@ // This type does not come from the CoreGraphics framework #if NET -namespace CoreGraphics { +namespace CoreGraphics +{ [NativeName ("GLKMatrix3")] [StructLayout (LayoutKind.Sequential)] - public struct RMatrix3 : IEquatable { + public struct RMatrix3 : IEquatable + { public float M11; public float M12; public float M13; @@ -121,7 +123,7 @@ public RMatrix3 ( break; } - throw new IndexOutOfRangeException (); + throw new IndexOutOfRangeException(); } set { switch (row) { @@ -148,7 +150,7 @@ public RMatrix3 ( break; } - throw new IndexOutOfRangeException (); + throw new IndexOutOfRangeException(); } } @@ -290,17 +292,17 @@ public override string ToString () public override int GetHashCode () { - var hash = new HashCode (); - hash.Add (M11); - hash.Add (M12); - hash.Add (M13); - hash.Add (M21); - hash.Add (M22); - hash.Add (M23); - hash.Add (M31); - hash.Add (M32); - hash.Add (M33); - return hash.ToHashCode (); + var hash = new HashCode(); + hash.Add(M11); + hash.Add(M12); + hash.Add(M13); + hash.Add(M21); + hash.Add(M22); + hash.Add(M23); + hash.Add(M31); + hash.Add(M32); + hash.Add(M33); + return hash.ToHashCode(); } public override bool Equals (object? obj) diff --git a/src/Simd/MatrixFloat4x3.cs b/src/Simd/MatrixFloat4x3.cs index f06a7c0154ad..cdb52fb94a5a 100644 --- a/src/Simd/MatrixFloat4x3.cs +++ b/src/Simd/MatrixFloat4x3.cs @@ -16,7 +16,7 @@ using System.Runtime.Versioning; #if NET -using VectorFloat4 = global::System.Numerics.Vector4; +using VectorFloat4=global::System.Numerics.Vector4; #else using VectorFloat4 = global::OpenTK.Vector4; #endif diff --git a/src/Simd/QuaternionDouble.cs b/src/Simd/QuaternionDouble.cs index a64edbe59ba6..d5725590a524 100644 --- a/src/Simd/QuaternionDouble.cs +++ b/src/Simd/QuaternionDouble.cs @@ -20,9 +20,11 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/quaternion.h #if NET -namespace CoreGraphics { +namespace CoreGraphics +{ [StructLayout (LayoutKind.Sequential)] - public struct NQuaterniond : IEquatable { + public struct NQuaterniond : IEquatable + { public double X; public double Y; public double Z; @@ -44,7 +46,8 @@ public NQuaterniond (NVector3d vectorPart, double scalarPart) W = scalarPart; } - internal NVector3d Xyz { + internal NVector3d Xyz + { get => new NVector3d (X, Y, Z); set { X = value.X; @@ -63,7 +66,7 @@ public override string ToString () => $"({X}, {Y}, {Z}, {W})"; public override int GetHashCode () => - HashCode.Combine (X, Y, Z, W); + HashCode.Combine(X, Y, Z, W); public override bool Equals (object? obj) { @@ -97,7 +100,7 @@ internal NVector4d ToAxisAngle () { NQuaterniond q = this; if (q.W > 1.0f) - q.Normalize (); + q.Normalize(); NVector4d result = new NVector4d (); diff --git a/src/Simd/VectorDouble2.cs b/src/Simd/VectorDouble2.cs index b33768c141ee..8f2c57e77309 100644 --- a/src/Simd/VectorDouble2.cs +++ b/src/Simd/VectorDouble2.cs @@ -16,9 +16,11 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics { +namespace CoreGraphics +{ [StructLayout (LayoutKind.Sequential)] - public struct NVector2d : IEquatable { + public struct NVector2d : IEquatable + { public double X; public double Y; @@ -45,7 +47,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine (X, Y); + return HashCode.Combine(X, Y); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorDouble4.cs b/src/Simd/VectorDouble4.cs index 5aa60c8c370a..2a8459dd8c7a 100644 --- a/src/Simd/VectorDouble4.cs +++ b/src/Simd/VectorDouble4.cs @@ -16,9 +16,11 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics { +namespace CoreGraphics +{ [StructLayout (LayoutKind.Sequential)] - public struct NVector4d : IEquatable { + public struct NVector4d : IEquatable + { public double X; public double Y; public double Z; @@ -32,7 +34,8 @@ public NVector4d (double x, double y, double z, double w) W = w; } - internal NVector3d Xyz { + internal NVector3d Xyz + { get => new NVector3d (X, Y, Z); set { X = value.X; @@ -58,7 +61,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine (X, Y, Z, W); + return HashCode.Combine(X, Y, Z, W); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt2.cs b/src/Simd/VectorInt2.cs index 5802b10cd0ee..e1682e07a5d3 100644 --- a/src/Simd/VectorInt2.cs +++ b/src/Simd/VectorInt2.cs @@ -16,9 +16,11 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics { +namespace CoreGraphics +{ [StructLayout (LayoutKind.Sequential)] - public struct NVector2i : IEquatable { + public struct NVector2i : IEquatable + { public int X; public int Y; @@ -45,7 +47,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine (X, Y); + return HashCode.Combine(X, Y); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt3.cs b/src/Simd/VectorInt3.cs index a1a811c2b0fb..40ae57929c98 100644 --- a/src/Simd/VectorInt3.cs +++ b/src/Simd/VectorInt3.cs @@ -16,9 +16,11 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics { +namespace CoreGraphics +{ [StructLayout (LayoutKind.Sequential)] - public struct NVector3i : IEquatable { + public struct NVector3i : IEquatable + { public int X; public int Y; public int Z; @@ -49,7 +51,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine (X, Y, Z); + return HashCode.Combine(X, Y, Z); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt4.cs b/src/Simd/VectorInt4.cs index 26336605fb02..a4ddc37c4397 100644 --- a/src/Simd/VectorInt4.cs +++ b/src/Simd/VectorInt4.cs @@ -16,9 +16,11 @@ #if NET // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h -namespace CoreGraphics { +namespace CoreGraphics +{ [StructLayout (LayoutKind.Sequential)] - public struct NVector4i : IEquatable { + public struct NVector4i : IEquatable + { public int X; public int Y; public int Z; @@ -49,7 +51,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine (X, Y, Z, W); + return HashCode.Combine(X, Y, Z, W); } public override bool Equals (object? obj) diff --git a/src/StoreKit/SKOverlayAppClipConfiguration.cs b/src/StoreKit/SKOverlayAppClipConfiguration.cs index 7f431db6a955..4fe5fbdd9871 100644 --- a/src/StoreKit/SKOverlayAppClipConfiguration.cs +++ b/src/StoreKit/SKOverlayAppClipConfiguration.cs @@ -10,9 +10,10 @@ namespace StoreKit { #if !COREBUILD - public partial class SKOverlayAppClipConfiguration { - public NSObject? this [string i] { - get => GetAdditionalValue (i); + public partial class SKOverlayAppClipConfiguration + { + public NSObject? this[string i] { + get => GetAdditionalValue (i); set => SetAdditionalValue (value, i); } } diff --git a/src/StoreKit/SKOverlayAppConfiguration.cs b/src/StoreKit/SKOverlayAppConfiguration.cs index 81d3da2f8c83..937f5b6b5e87 100644 --- a/src/StoreKit/SKOverlayAppConfiguration.cs +++ b/src/StoreKit/SKOverlayAppConfiguration.cs @@ -10,9 +10,10 @@ namespace StoreKit { #if !COREBUILD - public partial class SKOverlayAppConfiguration { - public NSObject? this [string i] { - get => GetAdditionalValue (i); + public partial class SKOverlayAppConfiguration + { + public NSObject? this[string i] { + get => GetAdditionalValue (i); set => SetAdditionalValue (value, i); } } diff --git a/src/System.Net.Http/CFNetworkHandler.cs b/src/System.Net.Http/CFNetworkHandler.cs index 521c50886157..b94bf44140e2 100644 --- a/src/System.Net.Http/CFNetworkHandler.cs +++ b/src/System.Net.Http/CFNetworkHandler.cs @@ -36,7 +36,7 @@ #if NET using CFNetwork; using CoreFoundation; -using CF = CoreFoundation; +using CF=CoreFoundation; #else using CoreServices; using CoreFoundation; diff --git a/src/UIKit/NSLayoutManager.cs b/src/UIKit/NSLayoutManager.cs index 3c04a9069a0c..530730812d64 100644 --- a/src/UIKit/NSLayoutManager.cs +++ b/src/UIKit/NSLayoutManager.cs @@ -19,7 +19,7 @@ using ObjCRuntime; #if MONOMAC -using UIFont = AppKit.NSFont; +using UIFont=AppKit.NSFont; #endif #if MONOMAC diff --git a/src/UIKit/UIActionSheet.cs b/src/UIKit/UIActionSheet.cs index 494a237b948f..285586845534 100644 --- a/src/UIKit/UIActionSheet.cs +++ b/src/UIKit/UIActionSheet.cs @@ -41,7 +41,7 @@ public UIActionSheet (string title, IUIActionSheetDelegate del, string cancelTit return; } - foreach (string b in other) { + foreach (string b in other){ if (b is not null) AddButton (b); } @@ -49,7 +49,7 @@ public UIActionSheet (string title, IUIActionSheetDelegate del, string cancelTit if (cancelTitle is not null) CancelButtonIndex = AddButton (cancelTitle); } - + #if !NET [Obsolete ("Use overload with a IUIActionSheetDelegate parameter")] public UIActionSheet (string title, UIActionSheetDelegate del) @@ -59,10 +59,10 @@ public UIActionSheet (string title, UIActionSheetDelegate del) #endif public UIActionSheet (string title, IUIActionSheetDelegate del) - : this (title, del, null, null, (string) null) { } + : this (title, del, null, null, (string) null) {} public UIActionSheet (string title) - : this (title, null, null, null, (string) null) { } + : this (title, null, null, null, (string) null) {} public void Add (string name) { @@ -75,7 +75,7 @@ public IEnumerator GetEnumerator () yield return ButtonTitle (i); } } - + } #endif // IOS diff --git a/src/UIKit/UIAppearance.cs b/src/UIKit/UIAppearance.cs index 481eaa9ca64c..da6d4b9a0b68 100644 --- a/src/UIKit/UIAppearance.cs +++ b/src/UIKit/UIAppearance.cs @@ -76,7 +76,7 @@ static IntPtr [] TypesToPointers (Type [] whenFoundIn) public static IntPtr GetAppearance (IntPtr class_ptr, params Type [] whenFoundIn) { using (var array = NSArray.FromIntPtrs (TypesToPointers (whenFoundIn))) { - return Messaging.IntPtr_objc_msgSend_IntPtr (class_ptr, + return Messaging.IntPtr_objc_msgSend_IntPtr (class_ptr, Selector.GetHandle (UIAppearance.selAppearanceWhenContainedInInstancesOfClasses), array.Handle); } } @@ -90,7 +90,7 @@ public static IntPtr GetAppearance (IntPtr class_ptr, UITraitCollection traits, throw new ArgumentNullException ("traits"); using (var array = NSArray.FromIntPtrs (TypesToPointers (whenFoundIn))) { - return Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, + return Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, Selector.GetHandle (UIAppearance.selAppearanceForTraitCollectionWhenContainedInInstancesOfClasses), traits.Handle, array.Handle); } diff --git a/src/UIKit/UIButton.cs b/src/UIKit/UIButton.cs index b389b49c995a..21bdc132fa36 100644 --- a/src/UIKit/UIButton.cs +++ b/src/UIKit/UIButton.cs @@ -15,7 +15,7 @@ public partial class UIButton { public UIButton (UIButtonType type) #if NET - : base (ObjCRuntime.Messaging.NativeHandle_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int) type)) + : base (ObjCRuntime.Messaging.NativeHandle_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int)type)) #else : base (ObjCRuntime.Messaging.IntPtr_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int) type)) #endif diff --git a/src/UIKit/UIDevice.cs b/src/UIKit/UIDevice.cs index cdbfe560d04a..afe3d44476c2 100644 --- a/src/UIKit/UIDevice.cs +++ b/src/UIKit/UIDevice.cs @@ -15,7 +15,7 @@ public partial class UIDevice { public bool CheckSystemVersion (int major, int minor) { #if __MACCATALYST__ - return Runtime.CheckSystemVersion (major, minor, Runtime.iOSSupportVersion); + return Runtime.CheckSystemVersion (major, minor, Runtime.iOSSupportVersion); #else return Runtime.CheckSystemVersion (major, minor, SystemVersion); #endif diff --git a/src/UIKit/UIDocumentBrowserViewController.cs b/src/UIKit/UIDocumentBrowserViewController.cs index 8781942e7b66..74668099e54b 100644 --- a/src/UIKit/UIDocumentBrowserViewController.cs +++ b/src/UIKit/UIDocumentBrowserViewController.cs @@ -31,10 +31,10 @@ namespace UIKit { - public partial class UIDocumentBrowserViewController { + public partial class UIDocumentBrowserViewController + { - static bool CheckSystemVersion () - { + static bool CheckSystemVersion () { #if IOS return SystemVersion.CheckiOS (12, 0); #else diff --git a/src/UIKit/UIImage.cs b/src/UIKit/UIImage.cs index 4b93d0387ef2..76fb5eadee3e 100644 --- a/src/UIKit/UIImage.cs +++ b/src/UIKit/UIImage.cs @@ -32,11 +32,11 @@ partial class UIImage { public void SaveToPhotosAlbum (SaveStatus status) { UIImageStatusDispatcher? dis = null; - UIApplication.EnsureUIThread (); + UIApplication.EnsureUIThread (); if (status is not null) dis = new UIImageStatusDispatcher (status); - + UIImageWriteToSavedPhotosAlbum (Handle, dis is not null ? dis.Handle : IntPtr.Zero, dis is not null ? Selector.GetHandle (UIImageStatusDispatcher.callbackSelector) : IntPtr.Zero, IntPtr.Zero); } #endif @@ -155,7 +155,7 @@ public DataWrapper (IntPtr buffer, uint len) internal class UIImageStatusDispatcher : NSObject { public const string callbackSelector = "Xamarin_Internal__image:didFinishSavingWithError:contextInfo:"; UIImage.SaveStatus status; - + public UIImageStatusDispatcher (UIImage.SaveStatus status) { IsDirectBinding = false; diff --git a/src/UIKit/UINavigationBar.cs b/src/UIKit/UINavigationBar.cs index 0e5579a415df..516a22786811 100644 --- a/src/UIKit/UINavigationBar.cs +++ b/src/UIKit/UINavigationBar.cs @@ -23,12 +23,12 @@ public virtual UITextAttributes GetTitleTextAttributes () { return new UITextAttributes (_TitleTextAttributes); } - + public virtual void SetTitleTextAttributes (UITextAttributes attributes) { if (attributes is null) throw new ArgumentNullException ("attributes"); - + _TitleTextAttributes = attributes.ToDictionary (); } } diff --git a/src/UIKit/UIPasteboard.cs b/src/UIKit/UIPasteboard.cs index c55b53c0a80c..9c9307db7074 100644 --- a/src/UIKit/UIPasteboard.cs +++ b/src/UIKit/UIPasteboard.cs @@ -25,16 +25,16 @@ UIImage [] GetImageArray (IntPtr handle) var obj = Runtime.GetNSObject (array.ValueAt (i)); var data = obj as NSData; UIImage img; - + if (data is not null) { img = new UIImage (data); } else { img = (UIImage) obj; } - + ret [i] = img; } - + return ret; } } @@ -46,11 +46,11 @@ UIImage [] GetImageArray (IntPtr handle) // API and not make users change their code. [CompilerGenerated] - public virtual UIImage [] Images { + public virtual UIImage[] Images { [Export ("images", ArgumentSemantic.Copy)] get { global::UIKit.UIApplication.EnsureUIThread (); - UIImage [] ret; + UIImage[] ret; if (IsDirectBinding) { ret = GetImageArray (ObjCRuntime.Messaging.IntPtr_objc_msgSend (this.Handle, Selector.GetHandle (selImages))); } else { @@ -58,12 +58,12 @@ public virtual UIImage [] Images { } return ret; } - + [Export ("setImages:", ArgumentSemantic.Copy)] set { global::UIKit.UIApplication.EnsureUIThread (); var nsa_value = NSArray.FromNSObjects (value); - + if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (selSetImages_), nsa_value.Handle); } else { diff --git a/src/UIKit/UIPickerView.cs b/src/UIKit/UIPickerView.cs index 8dce0b97fcc4..dd24a6ea2397 100644 --- a/src/UIKit/UIPickerView.cs +++ b/src/UIKit/UIPickerView.cs @@ -2,7 +2,7 @@ using System; -using Foundation; +using Foundation; using CoreGraphics; using ObjCRuntime; diff --git a/src/UIKit/UIPopoverPresentationController.cs b/src/UIKit/UIPopoverPresentationController.cs index 826a0e5ba8a6..61eb25a88b38 100644 --- a/src/UIKit/UIPopoverPresentationController.cs +++ b/src/UIKit/UIPopoverPresentationController.cs @@ -22,7 +22,7 @@ public virtual Type PopoverBackgroundViewType { return Class.Lookup (p); } set { - PopoverBackgroundViewClass = (value is null) ? IntPtr.Zero : + PopoverBackgroundViewClass = (value is null) ? IntPtr.Zero : Class.GetHandle (value); } } diff --git a/src/UIKit/UIStringDrawing.cs b/src/UIKit/UIStringDrawing.cs index 6720e7845b79..1fad3f3ebc22 100644 --- a/src/UIKit/UIStringDrawing.cs +++ b/src/UIKit/UIStringDrawing.cs @@ -8,7 +8,7 @@ using ObjCRuntime; namespace UIKit { - public unsafe static partial class UIStringDrawing { + public unsafe static partial class UIStringDrawing { #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] diff --git a/src/UIKit/UITextAttributes.cs b/src/UIKit/UITextAttributes.cs index b831b39010b3..68cee22e67ad 100644 --- a/src/UIKit/UITextAttributes.cs +++ b/src/UIKit/UITextAttributes.cs @@ -25,14 +25,14 @@ public class UITextAttributes { public UITextAttributes () { } - + internal UITextAttributes (NSDictionary dict) { if (dict is null) return; - + NSObject val; - + if (dict.TryGetValue (UITextAttributesConstants.Font, out val)) Font = val as UIFont; if (dict.TryGetValue (UITextAttributesConstants.TextColor, out val)) @@ -45,7 +45,7 @@ internal UITextAttributes (NSDictionary dict) TextShadowOffset = value.UIOffsetValue; } } - + internal NSDictionary ToDictionary () { int n = 0; @@ -67,27 +67,27 @@ internal NSDictionary ToDictionary () var keys = new NSObject [n]; var values = new NSObject [n]; n = 0; - if (font is not null) { + if (font is not null){ keys [n] = UITextAttributesConstants.Font; values [n] = font; n++; } - if (text_color is not null) { + if (text_color is not null){ keys [n] = UITextAttributesConstants.TextColor; values [n] = text_color; n++; } - if (text_shadow_color is not null) { + if (text_shadow_color is not null){ keys [n] = UITextAttributesConstants.TextShadowColor; values [n] = text_shadow_color; n++; } - if (text_shadow_offset.Horizontal != 0 || text_shadow_offset.Vertical != 0) { + if (text_shadow_offset.Horizontal != 0 || text_shadow_offset.Vertical != 0){ keys [n] = UITextAttributesConstants.TextShadowOffset; values [n] = NSValue.FromUIOffset (text_shadow_offset); } using (NSArray avalues = NSArray.FromObjects (values), - akeys = NSArray.FromObjects (keys)) { + akeys = NSArray.FromObjects (keys)){ return NSDictionary.FromObjectsAndKeysInternal (avalues, akeys); } } diff --git a/src/UIKit/UIToolbar.cs b/src/UIKit/UIToolbar.cs index fdeb2256aeb9..605190d7b70d 100644 --- a/src/UIKit/UIToolbar.cs +++ b/src/UIKit/UIToolbar.cs @@ -12,20 +12,20 @@ namespace UIKit { public partial class UIToolbar : UIView { - + // note: we cannot autogenerate this overload and still update the (same) __mt_Items_var local // previously we 'lost' the managed reference to the array and this caused bug #410 // http://bugzilla.xamarin.com/show_bug.cgi?id=410 [Export ("setItems:animated:")] - public virtual void SetItems (UIBarButtonItem [] items, bool animated) + public virtual void SetItems (UIBarButtonItem[] items, bool animated) { if (items is null) throw new ArgumentNullException ("items"); - + // must be identical the [get|set]_Items var nsa_items = NSArray.FromNSObjects (items); - + #if NET if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_bool (this.Handle, Selector.GetHandle ("setItems:animated:"), nsa_items.Handle, animated ? (byte) 1 : (byte) 0); diff --git a/src/UIKit/UIVideo.cs b/src/UIKit/UIVideo.cs index 82a8d14c1c01..64bc283fb7fb 100644 --- a/src/UIKit/UIVideo.cs +++ b/src/UIKit/UIVideo.cs @@ -22,7 +22,7 @@ namespace UIKit { internal class UIVideoStatusDispatcher : NSObject { public const string callbackSelector = "Xamarin_Internal__video:didFinishSavingWithError:contextInfo:"; UIVideo.SaveStatus status; - + public UIVideoStatusDispatcher (UIVideo.SaveStatus status) { this.status = status; @@ -38,13 +38,13 @@ public void Callback (string str, NSError err, IntPtr ctx) DangerousRelease (); } } - + public static class UIVideo { public delegate void SaveStatus (string path, NSError error); - + [DllImport (Constants.UIKitLibrary)] extern static /* BOOL */ byte UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (/* NSString* */ IntPtr videoPath); - + public static bool IsCompatibleWithSavedPhotosAlbum (string path) { UIApplication.EnsureUIThread (); @@ -63,11 +63,11 @@ public static void SaveToPhotosAlbum (string path, SaveStatus status) throw new ArgumentNullException ("status"); UIApplication.EnsureUIThread (); var dis = new UIVideoStatusDispatcher (status); - + using (var ns = new NSString (path)) UISaveVideoAtPathToSavedPhotosAlbum (ns.Handle, dis.Handle, Selector.GetHandle (UIVideoStatusDispatcher.callbackSelector), IntPtr.Zero); } - + } } diff --git a/src/VideoToolbox/VTCompressionSession.cs b/src/VideoToolbox/VTCompressionSession.cs index 83dd6febe765..deb4485ce60f 100644 --- a/src/VideoToolbox/VTCompressionSession.cs +++ b/src/VideoToolbox/VTCompressionSession.cs @@ -179,7 +179,7 @@ unsafe extern static VTStatus VTCompressionSessionCreate ( VTVideoEncoderSpecification? encoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. NSDictionary? sourceImageBufferAttributes, // Undocumented options, probably always null #if NET - delegate* unmanaged staticCback) + delegate* unmanaged staticCback) #else CompressionOutputCallback? staticCback) #endif diff --git a/src/VideoToolbox/VTDecompressionSession.cs b/src/VideoToolbox/VTDecompressionSession.cs index 802d6abc3795..3424ff153749 100644 --- a/src/VideoToolbox/VTDecompressionSession.cs +++ b/src/VideoToolbox/VTDecompressionSession.cs @@ -201,8 +201,8 @@ public static VTDecompressionSession Create (CMVideoFormatDescription formatDesc public static VTDecompressionSession? Create (VTDecompressionOutputCallback outputCallback, CMVideoFormatDescription formatDescription, #if NET - VTVideoDecoderSpecification? decoderSpecification = null, // hardware acceleration is default behavior on iOS. no opt-in required. - CVPixelBufferAttributes? destinationImageBufferAttributes = null) + VTVideoDecoderSpecification? decoderSpecification = null, // hardware acceleration is default behavior on iOS. no opt-in required. + CVPixelBufferAttributes? destinationImageBufferAttributes = null) #else VTVideoDecoderSpecification? decoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. CVPixelBufferAttributes? destinationImageBufferAttributes) @@ -222,7 +222,7 @@ public static VTDecompressionSession Create (CMVideoFormatDescription formatDesc VTVideoDecoderSpecification? decoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. NSDictionary? destinationImageBufferAttributes, #if NET - delegate* unmanaged cback) + delegate* unmanaged cback) #else IntPtr cback) #endif diff --git a/src/VideoToolbox/VTRawProcessingSession.cs b/src/VideoToolbox/VTRawProcessingSession.cs index 7663da13a70c..410529239c7a 100644 --- a/src/VideoToolbox/VTRawProcessingSession.cs +++ b/src/VideoToolbox/VTRawProcessingSession.cs @@ -111,7 +111,7 @@ public static nint GetTypeId () [DllImport (Constants.VideoToolboxLibrary)] unsafe static extern VTStatus VTRAWProcessingSessionSetParameterChangedHander ( IntPtr /* VTRAWProcessingSessionRef */ session, - BlockLiteral* /* VTRAWProcessingParameterChangeHandler */ parameterChangeHandler + BlockLiteral * /* VTRAWProcessingParameterChangeHandler */ parameterChangeHandler ); /// Provide a callback that will be called when the VTRawProcessingPlugin changes the set of processing parameters. @@ -145,7 +145,7 @@ unsafe static extern VTStatus VTRAWProcessingSessionProcessFrame ( IntPtr /* VTRAWProcessingSessionRef */ session, IntPtr /* CVPixelBufferRef */ inputPixelBuffer, IntPtr /* CM_NULLABLE CFDictionaryRef */ frameOptions, - BlockLiteral* /* VTRAWProcessingOutputHandler */ outputHandler + BlockLiteral * /* VTRAWProcessingOutputHandler */ outputHandler ); /// Use this function to submit RAW frames for processing using sequence and frame level parameters. diff --git a/src/accessorysetupkit.cs b/src/accessorysetupkit.cs index 0739adb6305d..d7338d289dcd 100644 --- a/src/accessorysetupkit.cs +++ b/src/accessorysetupkit.cs @@ -11,16 +11,16 @@ namespace AccessorySetupKit { [Native] [iOS (18, 0)] public enum ASAccessoryState : long { - Unauthorized = 0, - AwaitingAuthorization = 10, - Authorized = 20, + Unauthorized = 0, + AwaitingAuthorization = 10, + Authorized = 20, } [Flags] [Native] [iOS (18, 0)] public enum ASAccessoryRenameOptions : ulong { - Ssid = 1U << 0, + Ssid = 1U << 0, } [Flags] @@ -73,19 +73,19 @@ interface ASAccessory { [Native] [iOS (18, 0)] public enum ASAccessoryEventType : long { - Unknown = 0, - Activated = 10, - Invalidated = 11, - MigrationComplete = 20, - AccessoryAdded = 30, - AccessoryRemoved = 31, - AccessoryChanged = 32, - PickerDidPresent = 40, - PickerDidDismiss = 50, + Unknown = 0, + Activated = 10, + Invalidated = 11, + MigrationComplete = 20, + AccessoryAdded = 30, + AccessoryRemoved = 31, + AccessoryChanged = 32, + PickerDidPresent = 40, + PickerDidDismiss = 50, PickerSetupBridging = 60, - PickerSetupFailed = 70, - PickerSetupPairing = 80, - PickerSetupRename = 90, + PickerSetupFailed = 70, + PickerSetupPairing = 80, + PickerSetupRename = 90, } [BaseType (typeof (NSObject))] @@ -202,18 +202,18 @@ interface ASDiscoveryDescriptor { [iOS (18, 0)] [ErrorDomain ("ASErrorDomain")] enum ASErrorCode : long { - Success = 0, - Unknown = 1, - ActivationFailed = 100, - ConnectionFailed = 150, - DiscoveryTimeout = 200, - ExtensionNotFound = 300, - Invalidated = 400, - InvalidRequest = 450, + Success = 0, + Unknown = 1, + ActivationFailed = 100, + ConnectionFailed = 150, + DiscoveryTimeout = 200, + ExtensionNotFound = 300, + Invalidated = 400, + InvalidRequest = 450, PickerAlreadyActive = 500, - PickerRestricted = 550, - UserCancelled = 700, - UserRestricted = 750, + PickerRestricted = 550, + UserCancelled = 700, + UserRestricted = 750, } [BaseType (typeof (NSObject))] diff --git a/src/appkit.cs b/src/appkit.cs index 1a5346eefab9..7320ec7c35a6 100644 --- a/src/appkit.cs +++ b/src/appkit.cs @@ -15040,7 +15040,7 @@ partial interface NSSpellChecker { bool IsAutomaticTextCompletionEnabled { get; } #if NET - [Async (ResultTypeName = "NSSpellCheckerCandidates")] + [Async (ResultTypeName="NSSpellCheckerCandidates")] #else [Async (ResultTypeName = "NSSpellCheckerCanidates")] #endif @@ -19847,7 +19847,7 @@ NSTextContentType ContentType { // This came from the NSTextFinderClient protocol in legacy Xamarin, but NSTextView doesn't really implement that protocol, // so when it was removed for .NET, we still need to expose the API from NSTextFinderClient that NSTextView actually has. [Export ("selectedRanges", ArgumentSemantic.Copy)] - NSArray SelectedRanges { get; set; } + NSArray SelectedRanges { get; set; } #endif [NoiOS] diff --git a/src/authenticationservices.cs b/src/authenticationservices.cs index 1516e3f1d7bb..27bdb45f578f 100644 --- a/src/authenticationservices.cs +++ b/src/authenticationservices.cs @@ -630,8 +630,7 @@ interface IASAuthorizationControllerDelegate { } [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1049,8 +1048,7 @@ interface IASWebAuthenticationSessionRequestDelegate { } [NoTV] [NoiOS] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1164,8 +1162,7 @@ interface IASAccountAuthenticationModificationControllerDelegate { } [iOS (14, 0)] [NoTV, NoMac] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/avfoundation.cs b/src/avfoundation.cs index 3479fca03b7e..29f1b1c94063 100644 --- a/src/avfoundation.cs +++ b/src/avfoundation.cs @@ -1336,17 +1336,17 @@ interface AVAudio3DMixing { #if NET [Abstract] - [TV (13, 0), iOS (13, 0)] + [TV (13,0), iOS (13,0)] [MacCatalyst (13, 1)] [Export ("sourceMode", ArgumentSemantic.Assign)] AVAudio3DMixingSourceMode SourceMode { get; set; } [Abstract] - [TV (13, 0), iOS (13, 0)] + [TV (13,0), iOS (13,0)] [MacCatalyst (13, 1)] [Export ("pointSourceInHeadMode", ArgumentSemantic.Assign)] AVAudio3DMixingPointSourceInHeadMode PointSourceInHeadMode { get; set; } - + #else [TV (13, 0), iOS (13, 0)] [Export ("sourceMode", ArgumentSemantic.Assign)] @@ -8858,7 +8858,7 @@ interface AVAssetExportSession { [Export ("supportedFileTypes")] #if NET - string [] SupportedFileTypes { get; } + string [] SupportedFileTypes { get; } #else NSObject [] SupportedFileTypes { get; } #endif @@ -11857,7 +11857,7 @@ interface AVCaptureDeviceDiscoverySession { #else [Static] [Export ("discoverySessionWithDeviceTypes:mediaType:position:")] - AVCaptureDeviceDiscoverySession Create ([BindAs (typeof (AVCaptureDeviceType []))] NSString [] deviceTypes, [NullAllowed][BindAs (typeof (AVMediaTypes))] NSString mediaType, AVCaptureDevicePosition position); + AVCaptureDeviceDiscoverySession Create ([BindAs (typeof (AVCaptureDeviceType[]))] NSString[] deviceTypes, [NullAllowed] [BindAs (typeof (AVMediaTypes))] NSString mediaType, AVCaptureDevicePosition position); #endif [Export ("devices")] diff --git a/src/backgroundassets.cs b/src/backgroundassets.cs index 4ae0a5a877d8..d5dc0fb046f5 100644 --- a/src/backgroundassets.cs +++ b/src/backgroundassets.cs @@ -127,8 +127,7 @@ interface IBADownloadManagerDelegate { } [NoTV, Mac (13, 0), iOS (16, 0), MacCatalyst (16, 0)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/browserenginekit.cs b/src/browserenginekit.cs index 53ac4c0f7be8..e5788e8b1abf 100644 --- a/src/browserenginekit.cs +++ b/src/browserenginekit.cs @@ -52,10 +52,11 @@ using OS_xpc_object = Foundation.NSObject; namespace BrowserEngineKit { - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BELayerHierarchyHandle : NSSecureCoding { + interface BELayerHierarchyHandle : NSSecureCoding + { [Static] [Export ("handleWithXPCRepresentation:error:")] [return: NullAllowed] @@ -65,10 +66,11 @@ interface BELayerHierarchyHandle : NSSecureCoding { OS_xpc_object CreateXpcRepresentation (); } - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BELayerHierarchy { + interface BELayerHierarchy + { [Static] [Export ("layerHierarchyWithError:")] [return: NullAllowed] @@ -84,17 +86,19 @@ interface BELayerHierarchy { void Invalidate (); } - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] [BaseType (typeof (UIView))] - interface BELayerHierarchyHostingView { + interface BELayerHierarchyHostingView + { [Export ("handle", ArgumentSemantic.Strong), NullAllowed] BELayerHierarchyHandle LayerHierarchyHandle { get; set; } } - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding { + interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding + { [Static] [Export ("coordinatorWithError:")] [return: NullAllowed] @@ -119,10 +123,11 @@ interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding { void Commit (); } - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (UIContextMenuConfiguration))] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(UIContextMenuConfiguration))] [DisableDefaultCtor] - interface BEContextMenuConfiguration { + interface BEContextMenuConfiguration + { [DesignatedInitializer] [Export ("init")] NativeHandle Constructor (); @@ -131,12 +136,13 @@ interface BEContextMenuConfiguration { bool Fulfill ([NullAllowed] UIContextMenuConfiguration configuration); } - delegate bool BEDragInteractionDelegateGetDragItemsCallback (UIDragItem [] items); + delegate bool BEDragInteractionDelegateGetDragItemsCallback (UIDragItem[] items); - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] [BaseType (typeof (UIDragInteractionDelegate))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BEDragInteractionDelegate { + interface BEDragInteractionDelegate + { [Export ("dragInteraction:prepareDragSession:completion:")] void PrepareDragSession (BEDragInteraction dragInteraction, IUIDragSession session, Func completion); @@ -144,11 +150,12 @@ interface BEDragInteractionDelegate { void GetDragItems (BEDragInteraction dragInteraction, IUIDragSession session, CGPoint point, BEDragInteractionDelegateGetDragItemsCallback completion); } - interface IBEDragInteractionDelegate { } + interface IBEDragInteractionDelegate {} - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] [BaseType (typeof (UIDragInteraction))] - interface BEDragInteraction { + interface BEDragInteraction + { [Wrap ("WeakDelegate")] [NullAllowed] IBEDragInteractionDelegate Delegate { get; } @@ -161,10 +168,11 @@ interface BEDragInteraction { NativeHandle Constructor (IBEDragInteractionDelegate @delegate); } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [BaseType (typeof (UIScrollViewDelegate))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BEScrollViewDelegate { + interface BEScrollViewDelegate + { [Export ("scrollView:handleScrollUpdate:completion:")] void HandleScrollUpdate (BEScrollView scrollView, BEScrollViewScrollUpdate scrollUpdate, Action completion); @@ -173,11 +181,12 @@ interface BEScrollViewDelegate { BEScrollView GetParentScrollView (BEScrollView scrollView); } - interface IBEScrollViewDelegate { } + interface IBEScrollViewDelegate {} - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (UIScrollView))] - interface BEScrollView { + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(UIScrollView))] + interface BEScrollView + { [Wrap ("WeakDelegate")] [NullAllowed] IBEScrollViewDelegate Delegate { get; set; } @@ -186,19 +195,21 @@ interface BEScrollView { NSObject WeakDelegate { get; set; } } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Native] - public enum BEScrollViewScrollUpdatePhase : long { + public enum BEScrollViewScrollUpdatePhase : long + { Began, Changed, Ended, Cancelled, } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BEScrollViewScrollUpdate { + interface BEScrollViewScrollUpdate + { [Export ("timestamp")] double Timestamp { get; } @@ -214,10 +225,11 @@ interface BEScrollViewScrollUpdate { delegate void BEWebContentProcessCreateCallback ([NullAllowed] BEWebContentProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BEWebContentProcess { + interface BEWebContentProcess + { [Static] [Export ("webContentProcessWithInterruptionHandler:completion:")] [Async] @@ -245,7 +257,7 @@ interface BEWebContentProcess { IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error); // Inlined from the CapabilityInvalidationHandler (BEWebContentProcess) category - [NoTV, NoMac, iOS (17, 6), MacCatalyst (17, 6)] + [NoTV, NoMac, iOS (17,6), MacCatalyst (17, 6)] [Export ("grantCapability:error:invalidationHandler:")] [return: NullAllowed] IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error, Action invalidationHandler); @@ -253,10 +265,11 @@ interface BEWebContentProcess { delegate void BENetworkingProcessCreateCallback ([NullAllowed] BENetworkingProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BENetworkingProcess { + interface BENetworkingProcess + { [Static] [Export ("networkProcessWithInterruptionHandler:completion:")] [Async] @@ -289,10 +302,11 @@ interface BENetworkingProcess { delegate void BERenderingProcessCreateCallback ([NullAllowed] BERenderingProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, Mac (14, 3), iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BERenderingProcess { + interface BERenderingProcess + { [Static] [Export ("renderingProcessWithInterruptionHandler:completion:")] [Async] @@ -320,24 +334,25 @@ interface BERenderingProcess { IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error); // Inlined from the CapabilityInvalidationHandler (BERenderingProcess) category - [NoTV, NoMac, iOS (17, 6), MacCatalyst (17, 6)] + [NoTV, NoMac, iOS (17,6), MacCatalyst (17, 6)] [Export ("grantCapability:error:invalidationHandler:")] [return: NullAllowed] IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error, Action invalidationHandler); } // Headers say this is available on macOS 14.3, but the BETextInput type isn't, so just remove this type from macOS as well. - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [BaseType (typeof (NSObject))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BETextInputDelegate { + interface BETextInputDelegate + { [Abstract] [Export ("shouldDeferEventHandlingToSystemForTextInput:context:")] bool ShouldDeferEventHandlingToSystem (IBETextInput textInput, BEKeyEntryContext keyEventContext); [Abstract] [Export ("textInput:setCandidateSuggestions:")] - void SetCandidateSuggestions (IBETextInput textInput, [NullAllowed] BETextSuggestion [] suggestions); + void SetCandidateSuggestions (IBETextInput textInput, [NullAllowed] BETextSuggestion[] suggestions); [Abstract] [Export ("selectionWillChangeForTextInput:")] @@ -356,19 +371,21 @@ interface BETextInputDelegate { void InvalidateTextEntryContext (IBETextInput textInput); } - interface IBETextInputDelegate { } + interface IBETextInputDelegate {} - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Native] - public enum BEKeyPressState : long { + public enum BEKeyPressState : long + { Down = 1, Up = 2, } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BEKeyEntry { + interface BEKeyEntry + { [Export ("key")] UIKey Key { get; } @@ -382,9 +399,10 @@ interface BEKeyEntry { double Timestamp { get; } } - [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] [Native] - public enum BEGestureType : long { + public enum BEGestureType : long + { Loupe = 0, OneFingerTap = 1, DoubleTapAndHold = 2, @@ -397,9 +415,10 @@ public enum BEGestureType : long { ForceTouch = 15, } - [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] [Native] - public enum BESelectionTouchPhase : long { + public enum BESelectionTouchPhase : long + { Started, Moved, Ended, @@ -409,46 +428,51 @@ public enum BESelectionTouchPhase : long { } [Flags] - [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] [Native] - public enum BESelectionFlags : ulong { + public enum BESelectionFlags : ulong + { None = 0x0, WordIsNearTap = 1uL << 0, SelectionFlipped = 1uL << 1, PhraseBoundaryChanged = 1uL << 2, } - [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BETextAlternatives { + interface BETextAlternatives + { [Export ("primaryString")] string PrimaryString { get; } [Export ("alternativeStrings")] - string [] AlternativeStrings { get; } + string[] AlternativeStrings { get; } } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Flags] [Native] - public enum BETextReplacementOptions : ulong { + public enum BETextReplacementOptions : ulong + { None = 0x0, AddUnderline = 1uL << 0, } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Flags] [Native] - public enum BEKeyModifierFlags : long { + public enum BEKeyModifierFlags : long + { None, Shift, CapsLock, } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEResponderEditActions : UIResponderStandardEditActions { + interface BEResponderEditActions : UIResponderStandardEditActions + { [Export ("share:")] void Share ([NullAllowed] NSObject sender); @@ -474,9 +498,10 @@ interface BEResponderEditActions : UIResponderStandardEditActions { void TransliterateChinese ([NullAllowed] NSObject sender); } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BETextSelectionDirectionNavigation { + interface BETextSelectionDirectionNavigation + { [Abstract] [Export ("moveInLayoutDirection:")] void MoveInLayoutDirection (UITextLayoutDirection direction); @@ -494,9 +519,10 @@ interface BETextSelectionDirectionNavigation { void ExtendInStorageDirection (UITextStorageDirection direction, UITextGranularity granularity); } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEExtendedTextInputTraits : UITextInputTraits { + interface BEExtendedTextInputTraits : UITextInputTraits + { [Export ("singleLineDocument")] bool SingleLineDocument { [Bind ("isSingleLineDocument")] get; } @@ -513,16 +539,17 @@ interface BEExtendedTextInputTraits : UITextInputTraits { UIColor SelectionHighlightColor { get; } } - interface IBEExtendedTextInputTraits { } + interface IBEExtendedTextInputTraits {} delegate void BETextInputHandleKeyEntryCallback (BEKeyEntry entry, bool handled); - delegate void BETextInputReplaceTextCallback (UITextSelectionRect [] rects); + delegate void BETextInputReplaceTextCallback (UITextSelectionRect[] rects); delegate void BETextInputRequestTextContextForAutocorrectionCallback (BETextDocumentContext context); - delegate void BETextInputRequestTextRectsCallback (UITextSelectionRect [] rects); + delegate void BETextInputRequestTextRectsCallback (UITextSelectionRect[] rects); - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BEResponderEditActions { + interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BEResponderEditActions + { [Wrap ("WeakAsyncInputDelegate"), Abstract] [NullAllowed] IBETextInputDelegate AsyncInputDelegate { get; set; } @@ -650,7 +677,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Abstract] [Export ("selectionRectsForRange:")] - UITextSelectionRect [] GetSelectionRects (UITextRange range); + UITextSelectionRect[] GetSelectionRects (UITextRange range); [Abstract] [Export ("selectWordForReplacement")] @@ -739,7 +766,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Abstract] [return: NullAllowed] [Export ("alternativesForSelectedText")] - BETextAlternatives [] GetAlternativesForSelectedText (); + BETextAlternatives[] GetAlternativesForSelectedText (); [Abstract] [Export ("addTextAlternatives:")] @@ -749,7 +776,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Export ("insertTextAlternatives:")] void InsertTextAlternatives (BETextAlternatives alternatives); - [iOS (18, 0), MacCatalyst (18, 0), TV (18, 0)] + [iOS (18,0), MacCatalyst (18, 0), TV (18, 0)] [Export ("removeTextAlternatives")] void RemoveTextAlternatives (); @@ -797,17 +824,18 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Export ("cancelAutoscroll")] void CancelAutoscroll (); - [iOS (18, 0), MacCatalyst (18, 0), TV (18, 0)] + [iOS (18,0), MacCatalyst (18, 0), TV (18, 0)] [Export ("keyboardWillDismiss")] void KeyboardWillDismiss (); } - interface IBETextInput { } + interface IBETextInput {} - [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BETextSuggestion { + interface BETextSuggestion + { [Export ("initWithInputText:")] NativeHandle Constructor (string inputText); @@ -815,17 +843,19 @@ interface BETextSuggestion { string InputText { get; } } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (BETextSuggestion))] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(BETextSuggestion))] [DisableDefaultCtor] - interface BEAutoFillTextSuggestion { + interface BEAutoFillTextSuggestion + { [Export ("contents", ArgumentSemantic.Copy)] NSDictionary Contents { get; } } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] - interface BETextInteraction : UIInteraction { + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] + interface BETextInteraction : UIInteraction + { [Wrap ("WeakDelegate")] [NullAllowed] IBETextInteractionDelegate Delegate { get; set; } @@ -886,10 +916,11 @@ interface BETextInteraction : UIInteraction { } // Headers say this is available on macOS 14.3, but the BETextInteraction type isn't, so just remove this type from macOS as well. - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [BaseType (typeof (NSObject))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BETextInteractionDelegate { + interface BETextInteractionDelegate + { [Abstract] [Export ("systemWillChangeSelectionForInteraction:")] void SystemWillChangeSelection (BETextInteraction textInteraction); @@ -899,12 +930,13 @@ interface BETextInteractionDelegate { void SystemDidChangeSelection (BETextInteraction textInteraction); } - interface IBETextInteractionDelegate { } + interface IBETextInteractionDelegate {} - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BEKeyEntryContext { + interface BEKeyEntryContext + { [Export ("keyEntry", ArgumentSemantic.Strong)] BEKeyEntry KeyEntry { get; } @@ -923,9 +955,10 @@ interface BEKeyEntryContext { } [Flags] - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] [Native] - public enum BETextDocumentRequestOptions : long { + public enum BETextDocumentRequestOptions : long + { None = 0x0, Text = 1L << 0, AttributedText = 1L << 1, @@ -934,10 +967,11 @@ public enum BETextDocumentRequestOptions : long { AutocorrectedRanges = 1L << 7, } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BETextDocumentRequest { + interface BETextDocumentRequest + { [Export ("options", ArgumentSemantic.Assign)] BETextDocumentRequestOptions Options { get; set; } @@ -948,10 +982,11 @@ interface BETextDocumentRequest { nint GranularityCount { get; set; } } - [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BETextDocumentContext { + interface BETextDocumentContext + { [Export ("initWithSelectedText:contextBefore:contextAfter:markedText:selectedRangeInMarkedText:")] NativeHandle Constructor ([NullAllowed] string selectedText, [NullAllowed] string contextBefore, [NullAllowed] string contextAfter, [NullAllowed] string markedText, NSRange selectedRangeInMarkedText); @@ -962,12 +997,13 @@ interface BETextDocumentContext { void AddTextRect (CGRect rect, NSRange range); [Export ("autocorrectedRanges", ArgumentSemantic.Copy)] - NSValue [] AutocorrectedRanges { get; set; } + NSValue[] AutocorrectedRanges { get; set; } } - [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEProcessCapabilityGrant { + interface BEProcessCapabilityGrant + { [Abstract] [Export ("invalidate")] bool Invalidate (); @@ -977,12 +1013,13 @@ interface BEProcessCapabilityGrant { bool Valid { [Bind ("isValid")] get; } } - interface IBEProcessCapabilityGrant { } + interface IBEProcessCapabilityGrant {} - [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BEMediaEnvironment { + interface BEMediaEnvironment + { [Export ("initWithWebPageURL:")] [DesignatedInitializer] NativeHandle Constructor (NSUrl url); @@ -1004,10 +1041,11 @@ interface BEMediaEnvironment { AVCaptureSession MakeCaptureSession ([NullAllowed] out NSError error); } - [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] - [BaseType (typeof (NSObject))] + [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BEProcessCapability { + interface BEProcessCapability + { [NoMac] [Static] [Export ("mediaPlaybackAndCaptureWithEnvironment:")] @@ -1029,10 +1067,11 @@ interface BEProcessCapability { IBEProcessCapabilityGrant Request ([NullAllowed] out NSError error); } - [TV (17, 5), Mac (14, 5), iOS (17, 5), MacCatalyst (17, 5)] - [BaseType (typeof (NSObject))] + [TV (17, 5), Mac (14, 5), iOS (17,5), MacCatalyst (17, 5)] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface BEWebAppManifest { + interface BEWebAppManifest + { [Export ("initWithJSONData:manifestURL:")] [DesignatedInitializer] NativeHandle Constructor (NSData jsonData, NSUrl manifestUrl); @@ -1046,7 +1085,8 @@ interface BEWebAppManifest { [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Native] - public enum BEAccessibilityPressedState : long { + public enum BEAccessibilityPressedState : long + { Undefined = 0, False, True, @@ -1056,7 +1096,8 @@ public enum BEAccessibilityPressedState : long { [Flags] [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Native] - public enum BEAccessibilityContainerType : ulong { + public enum BEAccessibilityContainerType : ulong + { None = 0x0, Landmark = 1uL << 0, Table = 1uL << 1, @@ -1075,7 +1116,8 @@ public enum BEAccessibilityContainerType : ulong { [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Category] [BaseType (typeof (NSObject))] - interface NSObject_BEAccessibility { + interface NSObject_BEAccessibility + { [Export ("browserAccessibilityCurrentStatus")] [return: NullAllowed] string GetBrowserAccessibilityCurrentStatus (); @@ -1183,12 +1225,14 @@ public enum BEAccessibilityNotification : long { [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] - interface BEAccessibilityTextMarker : NSCopying, NSSecureCoding { + interface BEAccessibilityTextMarker : NSCopying, NSSecureCoding + { } [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] - interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding { + interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding + { [Export ("startMarker", ArgumentSemantic.Strong)] BEAccessibilityTextMarker StartMarker { get; set; } @@ -1198,7 +1242,8 @@ interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding { [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEAccessibilityTextMarkerSupport { + interface BEAccessibilityTextMarkerSupport + { [Abstract] [Export ("accessibilityBoundsForTextMarkerRange:")] CGRect GetAccessibilityBounds (BEAccessibilityTextMarkerRange range); @@ -1260,7 +1305,8 @@ interface BEAccessibilityTextMarkerSupport { [NoTV, NoMac, iOS (18, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEDownloadMonitorLocation { + interface BEDownloadMonitorLocation + { [Export ("url")] NSUrl Url { get; } @@ -1275,7 +1321,8 @@ interface BEDownloadMonitorLocation { [NoTV, NoMac, iOS (18, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEDownloadMonitor { + interface BEDownloadMonitor + { [Export ("initWithSourceURL:destinationURL:observedProgress:liveActivityAccessToken:")] NativeHandle Constructor (NSUrl sourceUrl, NSUrl destinationUrl, NSProgress observedProgress, NSData liveActivityAccessToken); diff --git a/src/contactsui.cs b/src/contactsui.cs index e4bafaa3c6aa..21e5fb594382 100644 --- a/src/contactsui.cs +++ b/src/contactsui.cs @@ -69,12 +69,11 @@ interface CNContactPickerViewController { interface ICNContactPickerDelegate { } #if MONOMAC - [NoiOS] - [NoMacCatalyst] - [NoTV] + [NoiOS][NoMacCatalyst][NoTV] [Protocol, Model] - [BaseType (typeof (NSObject))] - interface CNContactPickerDelegate { + [BaseType (typeof(NSObject))] + interface CNContactPickerDelegate + { [Export ("contactPicker:didSelectContact:")] void ContactSelected (CNContactPicker picker, CNContact contact); diff --git a/src/coreanimation.cs b/src/coreanimation.cs index 701e61be1182..929bd78831e8 100644 --- a/src/coreanimation.cs +++ b/src/coreanimation.cs @@ -1272,8 +1272,7 @@ interface CALayerDelegate { /// /// /// Apple documentation for CAEAGLLayer - [NoMac] - [NoMacCatalyst] + [NoMac][NoMacCatalyst] [Deprecated (PlatformName.TvOS, 12, 0, message: "Use 'CAMetalLayer' instead.")] [Deprecated (PlatformName.iOS, 12, 0, message: "Use 'CAMetalLayer' instead.")] [BaseType (typeof (CALayer))] @@ -1302,7 +1301,7 @@ interface CAAction { /// [BaseType (typeof (NSObject) #if NET - , Delegates = new string [] { "WeakDelegate" }, Events = new Type [] { typeof (CAAnimationDelegate) } + , Delegates = new string [] {"WeakDelegate"}, Events = new Type [] { typeof (CAAnimationDelegate) } #endif )] interface CAAnimation : CAAction, CAMediaTiming, NSSecureCoding, NSMutableCopying, SCNAnimationProtocol { diff --git a/src/coredata.cs b/src/coredata.cs index 6fd01dfced52..5b807e12de6c 100644 --- a/src/coredata.cs +++ b/src/coredata.cs @@ -624,7 +624,7 @@ interface NSFetchedResultsController { string GetSectionIndexTitle (string sectionName); [Export ("sectionIndexTitles")] - string [] SectionIndexTitles { get; } + string[] SectionIndexTitles { get; } #endif [Static] @@ -895,7 +895,7 @@ interface NSManagedObject : NSFetchRequestResult { #if XAMCORE_5_0 NSDictionary GetCommittedValues ([NullAllowed] string[] keys); #elif NET - NSDictionary GetCommittedValues ([NullAllowed] string [] keys); + NSDictionary GetCommittedValues ([NullAllowed] string[] keys); #else NSDictionary CommittedValuesForKeys ([NullAllowed] string [] keys); #endif @@ -1271,7 +1271,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { [Static, Export ("mergedModelFromBundles:")] [return: NullAllowed] #if NET - NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle [] bundles); + NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles); #else NSManagedObjectModel MergedModelFromBundles ([NullAllowed] NSBundle [] bundles); #endif @@ -1337,7 +1337,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { #if XAMCORE_5_0 NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles, NSDictionary metadata); #elif NET - NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle [] bundles, NSDictionary metadata); + NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles, NSDictionary metadata); #else NSManagedObjectModel MergedModelFromBundles ([NullAllowed] NSBundle [] bundles, NSDictionary metadata); #endif @@ -1347,7 +1347,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { #if XAMCORE_5_0 NSManagedObjectModel GetModelByMerging (NSManagedObjectModel[] models, NSDictionary metadata); #elif NET - NSManagedObjectModel GetModelByMerging (NSManagedObjectModel [] models, NSDictionary metadata); + NSManagedObjectModel GetModelByMerging (NSManagedObjectModel[] models, NSDictionary metadata); #else NSManagedObjectModel ModelByMergingModels (NSManagedObjectModel [] models, NSDictionary metadata); #endif @@ -1395,7 +1395,7 @@ interface NSMappingModel { [Static, Export ("mappingModelFromBundles:forSourceModel:destinationModel:")] [return: NullAllowed] #if NET - NSMappingModel GetMappingModel ([NullAllowed] NSBundle [] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); + NSMappingModel GetMappingModel ([NullAllowed] NSBundle[] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); #else NSMappingModel MappingModelFromBundles ([NullAllowed] NSBundle [] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); #endif @@ -2386,7 +2386,7 @@ interface NSAsynchronousFetchResult { [Export ("finalResult", ArgumentSemantic.Retain)] [NullAllowed] #if NET - INSFetchRequestResult [] FinalResult { get; } + INSFetchRequestResult[] FinalResult { get; } #else NSObject [] FinalResult { get; } #endif diff --git a/src/corehaptics.cs b/src/corehaptics.cs index 150be43b5014..dd6df1f4d4a5 100644 --- a/src/corehaptics.cs +++ b/src/corehaptics.cs @@ -22,7 +22,7 @@ namespace CoreHaptics { // we are not binding the API on Mac OS X yet due to an issue on Apples side: https://github.com/xamarin/maccore/issues/1951 #if MONOMAC || TV - interface AVAudioSession { } + interface AVAudioSession {} #endif [iOS (13, 0), TV (14, 0)] diff --git a/src/coreimage.cs b/src/coreimage.cs index 1a2bb50e4a2f..be8db0eee89f 100644 --- a/src/coreimage.cs +++ b/src/coreimage.cs @@ -256,16 +256,14 @@ interface CIContext { CIContext Create (); #if HAS_OPENGLES - [NoMac] - [NoMacCatalyst] + [NoMac][NoMacCatalyst] [Deprecated (PlatformName.iOS, 12, 0)] [Deprecated (PlatformName.TvOS, 12, 0)] [Static] [Export ("contextWithEAGLContext:")] CIContext FromContext (EAGLContext eaglContext); - [NoMac] - [NoMacCatalyst] + [NoMac][NoMacCatalyst] [Deprecated (PlatformName.iOS, 12, 0)] [Deprecated (PlatformName.TvOS, 12, 0)] [Static] diff --git a/src/corelocation.cs b/src/corelocation.cs index f728e652bfee..07b38a503d6e 100644 --- a/src/corelocation.cs +++ b/src/corelocation.cs @@ -58,7 +58,7 @@ public enum CLProximity : long { [ErrorDomain ("CLLocationPushServiceErrorDomain")] #if NET // Apple fixed this in Xcode 13.1 - [iOS (15, 0), NoTV, NoMacCatalyst, NoMac] + [iOS (15,0), NoTV, NoMacCatalyst, NoMac] #else [iOS (15, 0), NoTV, MacCatalyst (15, 0), NoMac] #endif @@ -1064,7 +1064,7 @@ interface CLBeaconIdentityConstraint : NSCopying, NSSecureCoding { } #if NET // Apple fixed this in Xcode 13.1 - [iOS (15, 0), NoTV, NoMacCatalyst, NoMac] + [iOS (15,0), NoTV, NoMacCatalyst, NoMac] #else [iOS (15, 0), NoTV, MacCatalyst (15, 0), NoMac] #endif diff --git a/src/corenfc.cs b/src/corenfc.cs index 49d22130a2d8..bcabf9246b31 100644 --- a/src/corenfc.cs +++ b/src/corenfc.cs @@ -870,7 +870,7 @@ enum VasErrorCode [MacCatalyst (13, 1)] #if NET [Native] - enum NFCVasMode + enum NFCVasMode #else [Native ("NFCVASMode")] enum VasMode @@ -1071,8 +1071,7 @@ interface INFCTagReaderSessionDelegate { } [iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1120,8 +1119,7 @@ interface INFCVasReaderSessionDelegate { } [iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/coretext.cs b/src/coretext.cs index 40d28ebdfb86..bb02cfff3cd8 100644 --- a/src/coretext.cs +++ b/src/coretext.cs @@ -126,8 +126,7 @@ interface CTFontManagerErrorKeys { #if NET [Internal] - [Static] - [Partial] + [Static][Partial] interface CTBaselineClassID { [Field ("kCTBaselineClassRoman")] NSString Roman { get; } @@ -149,8 +148,7 @@ interface CTBaselineClassID { } [Internal] - [Static] - [Partial] + [Static][Partial] interface CTBaselineFontID { [Field ("kCTBaselineReferenceFont")] NSString Reference { get; } @@ -276,8 +274,7 @@ interface CTFontTraitKey { } [Internal] - [Static] - [Partial] + [Static][Partial] interface CTFontNameKeyId { [Field ("kCTFontCopyrightNameKey")] NSString Copyright { get; } diff --git a/src/cryptotokenkit.cs b/src/cryptotokenkit.cs index cd5de12aa674..7da6fd74417a 100644 --- a/src/cryptotokenkit.cs +++ b/src/cryptotokenkit.cs @@ -20,7 +20,8 @@ namespace CryptoTokenKit { [Native] [ErrorDomain ("TKErrorDomain")] [iOS (9, 0), Mac (10, 10), MacCatalyst (13, 1), TV (9, 0)] - public enum TKErrorCode : long { + public enum TKErrorCode : long + { NotImplemented = -1, CommunicationError = -2, CorruptedData = -3, @@ -37,7 +38,8 @@ public enum TKErrorCode : long { #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] [Native] - public enum TKSmartCardSlotState : long { + public enum TKSmartCardSlotState : long + { Missing = 0, Empty = 1, Probing = 2, @@ -50,7 +52,8 @@ public enum TKSmartCardSlotState : long { #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINCharset")] - public enum TKSmartCardPinCharset : long { + public enum TKSmartCardPinCharset : long + { Numeric = 0, Alphanumeric = 1, UpperAlphanumeric = 2, @@ -61,7 +64,8 @@ public enum TKSmartCardPinCharset : long { #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINEncoding")] - public enum TKSmartCardPinEncoding : long { + public enum TKSmartCardPinEncoding : long + { Binary = 0, Ascii = 1, Bcd = 2, @@ -72,7 +76,8 @@ public enum TKSmartCardPinEncoding : long { #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINJustification")] - public enum TKSmartCardPinJustification : long { + public enum TKSmartCardPinJustification : long + { Left = 0, Right = 1, } @@ -83,7 +88,8 @@ public enum TKSmartCardPinJustification : long { [Flags] [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINCompletion")] - public enum TKSmartCardPinCompletion : ulong { + public enum TKSmartCardPinCompletion : ulong + { MaxLength = (1uL << 0), Key = (1uL << 1), Timeout = (1uL << 2), @@ -95,7 +101,8 @@ public enum TKSmartCardPinCompletion : ulong { [Flags] [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINConfirmation")] - public enum TKSmartCardPinConfirmation : ulong { + public enum TKSmartCardPinConfirmation : ulong + { None = 0x0, New = (1uL << 0), Current = (1uL << 1), @@ -107,7 +114,8 @@ public enum TKSmartCardPinConfirmation : ulong { [Flags] [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] [Native] - public enum TKSmartCardProtocol : ulong { + public enum TKSmartCardProtocol : ulong + { None = 0x0, T0 = (1uL << 0), T1 = (1uL << 1), @@ -120,7 +128,8 @@ public enum TKSmartCardProtocol : ulong { #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Native] - public enum TKTokenOperation : long { + public enum TKTokenOperation : long + { None = 0, ReadData = 1, SignData = 2, @@ -133,7 +142,8 @@ public enum TKTokenOperation : long { #endif [iOS (13, 0), Mac (10, 12), MacCatalyst (13, 1), TV (13, 0)] [Protocol] - interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate { + interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate + { [Abstract] [Export ("tokenDriver:createTokenForSmartCard:AID:error:")] [return: NullAllowed] @@ -143,14 +153,15 @@ interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate { #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKSmartCardTokenDriverDelegate { } + interface ITKSmartCardTokenDriverDelegate {} #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Protocol] - interface TKSmartCardUserInteractionDelegate { + interface TKSmartCardUserInteractionDelegate + { [Export ("characterEnteredInUserInteraction:")] void CharacterEntered (TKSmartCardUserInteraction interaction); @@ -176,15 +187,16 @@ interface TKSmartCardUserInteractionDelegate { #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKSmartCardUserInteractionDelegate { } + interface ITKSmartCardUserInteractionDelegate {} #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof (NSObject))] - interface TKTokenDelegate { + [BaseType (typeof(NSObject))] + interface TKTokenDelegate + { [Abstract] [Export ("token:createSessionWithError:")] [return: NullAllowed] @@ -197,16 +209,17 @@ interface TKTokenDelegate { #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenDelegate { } + interface ITKTokenDelegate {} #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof (NSObject))] - interface TKTokenDriverDelegate { - [TV (14, 0), Mac (10, 15), iOS (14, 0)] + [BaseType (typeof(NSObject))] + interface TKTokenDriverDelegate + { + [TV (14,0), Mac (10,15), iOS (14,0)] [Export ("tokenDriver:tokenForConfiguration:error:")] [return: NullAllowed] TKToken GetToken (TKTokenDriver driver, TKTokenConfiguration configuration, [NullAllowed] out NSError error); @@ -218,15 +231,16 @@ interface TKTokenDriverDelegate { #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenDriverDelegate { } + interface ITKTokenDriverDelegate {} #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof (NSObject))] - interface TKTokenSessionDelegate { + [BaseType (typeof(NSObject))] + interface TKTokenSessionDelegate + { [Export ("tokenSession:beginAuthForOperation:constraint:error:")] [return: NullAllowed] TKTokenAuthOperation BeginAuthentication (TKTokenSession session, TKTokenOperation operation, NSObject constraint, [NullAllowed] out NSError error); @@ -250,14 +264,15 @@ interface TKTokenSessionDelegate { #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenSessionDelegate { } + interface ITKTokenSessionDelegate {} #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTlvRecord), Name = "TKBERTLVRecord")] - interface TKBerTlvRecord { + [BaseType (typeof(TKTlvRecord), Name = "TKBERTLVRecord")] + interface TKBerTlvRecord + { [Static] [Export ("dataForTag:")] NSData GetData (ulong tag); @@ -266,15 +281,16 @@ interface TKBerTlvRecord { NativeHandle Constructor (ulong tag, NSData value); [Export ("initWithTag:records:")] - NativeHandle Constructor (ulong tag, TKTlvRecord [] records); + NativeHandle Constructor (ulong tag, TKTlvRecord[] records); } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTlvRecord), Name = "TKCompactTLVRecord")] - interface TKCompactTlvRecord { + [BaseType (typeof(TKTlvRecord), Name = "TKCompactTLVRecord")] + interface TKCompactTlvRecord + { [Export ("initWithTag:value:")] NativeHandle Constructor (byte tag, NSData value); } @@ -283,8 +299,9 @@ interface TKCompactTlvRecord { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTlvRecord), Name = "TKSimpleTLVRecord")] - interface TKSimpleTlvRecord { + [BaseType (typeof(TKTlvRecord), Name = "TKSimpleTLVRecord")] + interface TKSimpleTlvRecord + { [Export ("initWithTag:value:")] NativeHandle Constructor (byte tag, NSData value); } @@ -303,8 +320,9 @@ interface TKSimpleTlvRecord { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (NSObject))] - interface TKSmartCard { + [BaseType (typeof(NSObject))] + interface TKSmartCard + { [Export ("slot")] TKSmartCardSlot Slot { get; } @@ -359,11 +377,11 @@ interface TKSmartCard { [Export ("sendIns:p1:p2:data:le:reply:")] void Send (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, TKSmartCardSendCallback reply); - [Mac (10, 12)] + [Mac (10,12)] [Export ("inSessionWithError:executeBlock:")] bool ExecuteBlock ([NullAllowed] out NSError error, TKSmartCardExecuteCallback block); - [Mac (10, 12)] + [Mac (10,12)] [Export ("sendIns:p1:p2:data:le:sw:error:")] [return: NullAllowed] NSData Send (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, out ushort sw, [NullAllowed] out NSError error); @@ -373,9 +391,10 @@ interface TKSmartCard { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (NSObject), Name = "TKSmartCardATR")] + [BaseType (typeof(NSObject), Name = "TKSmartCardATR")] [DisableDefaultCtor] - interface TKSmartCardAtr { + interface TKSmartCardAtr + { [Export ("initWithBytes:")] NativeHandle Constructor (NSData bytes); @@ -386,8 +405,8 @@ interface TKSmartCardAtr { NSData Bytes { get; } [Export ("protocols")] - [BindAs (typeof (TKSmartCardProtocol []))] - NSNumber [] Protocols { get; } + [BindAs (typeof (TKSmartCardProtocol[]))] + NSNumber[] Protocols { get; } // -(TKSmartCardATRInterfaceGroup * _Nullable)interfaceGroupAtIndex:(NSInteger)index; [Export ("interfaceGroupAtIndex:")] @@ -404,15 +423,16 @@ interface TKSmartCardAtr { [Mac (10, 12)] [Export ("historicalRecords")] [NullAllowed] - TKCompactTlvRecord [] HistoricalRecords { get; } + TKCompactTlvRecord[] HistoricalRecords { get; } } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (NSObject), Name = "TKSmartCardATRInterfaceGroup")] - interface TKSmartCardAtrInterfaceGroup { + [BaseType (typeof(NSObject), Name = "TKSmartCardATRInterfaceGroup")] + interface TKSmartCardAtrInterfaceGroup + { [NullAllowed, Export ("TA")] NSNumber TA { get; } @@ -433,9 +453,10 @@ interface TKSmartCardAtrInterfaceGroup { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKTokenSession { + interface TKTokenSession + { [Export ("initWithToken:")] [DesignatedInitializer] NativeHandle Constructor (TKToken token); @@ -455,8 +476,9 @@ interface TKTokenSession { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (NSObject), Name = "TKSmartCardPINFormat")] - interface TKSmartCardPinFormat { + [BaseType (typeof(NSObject), Name = "TKSmartCardPINFormat")] + interface TKSmartCardPinFormat + { [Export ("charset", ArgumentSemantic.Assign)] TKSmartCardPinCharset Charset { get; set; } @@ -489,8 +511,9 @@ interface TKSmartCardPinFormat { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (NSObject))] - interface TKSmartCardSlot { + [BaseType (typeof(NSObject))] + interface TKSmartCardSlot + { [Export ("state")] TKSmartCardSlotState State { get; } @@ -520,21 +543,22 @@ interface TKSmartCardSlot { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKSmartCardSlotManager { + interface TKSmartCardSlotManager + { [Static] [NullAllowed, Export ("defaultManager")] TKSmartCardSlotManager DefaultManager { get; } [Export ("slotNames")] - string [] SlotNames { get; } + string[] SlotNames { get; } [Export ("getSlotWithName:reply:")] [Async] void GetSlot (string name, TKGetSlotCallback reply); - [Mac (10, 13)] + [Mac (10,13)] [Export ("slotNamed:")] [return: NullAllowed] TKSmartCardSlot GetSlot (string name); @@ -544,8 +568,9 @@ interface TKSmartCardSlotManager { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKToken))] - interface TKSmartCardToken { + [BaseType (typeof(TKToken))] + interface TKSmartCardToken + { [Export ("initWithSmartCard:AID:instanceID:tokenDriver:")] [DesignatedInitializer] NativeHandle Constructor (TKSmartCard smartCard, [NullAllowed] NSData aid, string instanceId, TKSmartCardTokenDriver tokenDriver); @@ -559,15 +584,17 @@ interface TKSmartCardToken { #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [BaseType (typeof (TKTokenDriver))] - interface TKSmartCardTokenDriver { + interface TKSmartCardTokenDriver + { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTokenSession))] - interface TKSmartCardTokenSession { + [BaseType (typeof(TKTokenSession))] + interface TKSmartCardTokenSession + { // Re-implemented from base class. [Export ("initWithToken:")] [DesignatedInitializer] @@ -581,8 +608,9 @@ interface TKSmartCardTokenSession { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (NSObject))] - interface TKSmartCardUserInteraction { + [BaseType (typeof(NSObject))] + interface TKSmartCardUserInteraction + { [Wrap ("WeakDelegate")] [NullAllowed] ITKSmartCardUserInteractionDelegate Delegate { get; set; } @@ -608,14 +636,15 @@ interface TKSmartCardUserInteraction { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (TKSmartCardUserInteraction), Name = "TKSmartCardUserInteractionForPINOperation")] - interface TKSmartCardUserInteractionForPinOperation { + [BaseType (typeof(TKSmartCardUserInteraction), Name = "TKSmartCardUserInteractionForPINOperation")] + interface TKSmartCardUserInteractionForPinOperation + { [Export ("PINCompletion", ArgumentSemantic.Assign)] TKSmartCardPinCompletion PinCompletion { get; set; } // not clear from the documentation if we can BindAs this to something or not [NullAllowed, Export ("PINMessageIndices", ArgumentSemantic.Assign)] - NSNumber [] PinMessageIndices { get; set; } + NSNumber[] PinMessageIndices { get; set; } [NullAllowed, Export ("locale", ArgumentSemantic.Assign)] NSLocale Locale { get; set; } @@ -631,8 +660,9 @@ interface TKSmartCardUserInteractionForPinOperation { [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof (TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINChange")] - interface TKSmartCardUserInteractionForSecurePinChange { + [BaseType (typeof(TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINChange")] + interface TKSmartCardUserInteractionForSecurePinChange + { [Export ("PINConfirmation", ArgumentSemantic.Assign)] TKSmartCardPinConfirmation PinConfirmation { get; set; } } @@ -642,16 +672,18 @@ interface TKSmartCardUserInteractionForSecurePinChange { #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [BaseType (typeof (TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINVerification")] - interface TKSmartCardUserInteractionForSecurePinVerification { + interface TKSmartCardUserInteractionForSecurePinVerification + { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject), Name = "TKTLVRecord")] + [BaseType (typeof(NSObject), Name = "TKTLVRecord")] [DisableDefaultCtor] - interface TKTlvRecord { + interface TKTlvRecord + { [Export ("tag")] ulong Tag { get; } @@ -669,16 +701,17 @@ interface TKTlvRecord { [Static] [Export ("sequenceOfRecordsFromData:")] [return: NullAllowed] - TKTlvRecord [] CreateSequenceOfRecords (NSData data); + TKTlvRecord[] CreateSequenceOfRecords (NSData data); } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKToken { + interface TKToken + { [Export ("initWithTokenDriver:instanceID:")] [DesignatedInitializer] NativeHandle Constructor (TKTokenDriver tokenDriver, string instanceId); @@ -705,8 +738,9 @@ interface TKToken { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] - interface TKTokenAuthOperation : NSSecureCoding { + [BaseType (typeof(NSObject))] + interface TKTokenAuthOperation : NSSecureCoding + { [Export ("finishWithError:")] bool Finish ([NullAllowed] out NSError error); } @@ -715,9 +749,10 @@ interface TKTokenAuthOperation : NSSecureCoding { [Experimental ("APL0001")] #endif [iOS (14, 0), Mac (10, 15), MacCatalyst (14, 0), TV (14, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKTokenConfiguration { + interface TKTokenConfiguration + { [Export ("instanceID")] string InstanceId { get; } @@ -725,7 +760,7 @@ interface TKTokenConfiguration { NSData ConfigurationData { get; set; } [Export ("keychainItems", ArgumentSemantic.Copy)] - TKTokenKeychainItem [] KeychainItems { get; set; } + TKTokenKeychainItem[] KeychainItems { get; set; } [Export ("keyForObjectID:error:")] [return: NullAllowed] @@ -740,8 +775,9 @@ interface TKTokenConfiguration { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] - interface TKTokenDriver { + [BaseType (typeof(NSObject))] + interface TKTokenDriver + { [Wrap ("WeakDelegate")] [NullAllowed] ITKTokenDriverDelegate Delegate { get; set; } @@ -754,9 +790,10 @@ interface TKTokenDriver { [Experimental ("APL0001")] #endif [iOS (14, 0), Mac (10, 15), MacCatalyst (14, 0), TV (14, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKTokenDriverConfiguration { + interface TKTokenDriverConfiguration + { [Static] [Export ("driverConfigurations")] NSDictionary DriverConfigurations { get; } @@ -778,9 +815,10 @@ interface TKTokenDriverConfiguration { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKTokenKeyAlgorithm { + interface TKTokenKeyAlgorithm + { [Export ("isAlgorithm:")] bool IsAlgorithm ([BindAs (typeof (SecKeyAlgorithm))] NSString algorithm); @@ -792,8 +830,9 @@ interface TKTokenKeyAlgorithm { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTokenKeychainItem))] - interface TKTokenKeychainCertificate { + [BaseType (typeof(TKTokenKeychainItem))] + interface TKTokenKeychainCertificate + { [Export ("initWithCertificate:objectID:")] [DesignatedInitializer] NativeHandle Constructor ([BindAs (typeof (SecKeyAlgorithm))] NSString certificateRef, NSObject objectId); @@ -806,14 +845,15 @@ interface TKTokenKeychainCertificate { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKTokenKeychainContents { + interface TKTokenKeychainContents + { [Export ("fillWithItems:")] - void Fill (TKTokenKeychainItem [] items); + void Fill (TKTokenKeychainItem[] items); [Export ("items", ArgumentSemantic.Copy)] - TKTokenKeychainItem [] Items { get; } + TKTokenKeychainItem[] Items { get; } [Export ("keyForObjectID:error:")] [return: NullAllowed] @@ -828,9 +868,10 @@ interface TKTokenKeychainContents { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKTokenKeychainItem { + interface TKTokenKeychainItem + { [Export ("initWithObjectID:")] [DesignatedInitializer] NativeHandle Constructor (NSObject objectId); @@ -849,8 +890,9 @@ interface TKTokenKeychainItem { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTokenKeychainItem))] - interface TKTokenKeychainKey { + [BaseType (typeof(TKTokenKeychainItem))] + interface TKTokenKeychainKey + { [Export ("initWithCertificate:objectID:")] [DesignatedInitializer] NativeHandle Constructor (IntPtr certificate, NSObject objectId); @@ -890,8 +932,9 @@ interface TKTokenKeychainKey { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] - interface TKTokenKeyExchangeParameters { + [BaseType (typeof(NSObject))] + interface TKTokenKeyExchangeParameters + { [Export ("requestedSize")] nint RequestedSize { get; } @@ -903,8 +946,9 @@ interface TKTokenKeyExchangeParameters { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTokenAuthOperation))] - interface TKTokenPasswordAuthOperation { + [BaseType (typeof(TKTokenAuthOperation))] + interface TKTokenPasswordAuthOperation + { [NullAllowed, Export ("password")] string Password { get; set; } } @@ -913,8 +957,9 @@ interface TKTokenPasswordAuthOperation { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (TKTokenAuthOperation), Name = "TKTokenSmartCardPINAuthOperation")] - interface TKTokenSmartCardPinAuthOperation { + [BaseType (typeof(TKTokenAuthOperation), Name = "TKTokenSmartCardPINAuthOperation")] + interface TKTokenSmartCardPinAuthOperation + { [Export ("PINFormat", ArgumentSemantic.Assign)] TKSmartCardPinFormat PinFormat { get; set; } @@ -935,10 +980,11 @@ interface TKTokenSmartCardPinAuthOperation { [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof (NSObject))] - interface TKTokenWatcher { + [BaseType (typeof(NSObject))] + interface TKTokenWatcher + { [Export ("tokenIDs")] - string [] TokenIds { get; } + string[] TokenIds { get; } // -(instancetype _Nonnull)initWithInsertionHandler:(void (^ _Nonnull)(NSString * _Nonnull))insertionHandler __attribute__((availability(macos, introduced=10.12, deprecated=10.13))) __attribute__((availability(ios, introduced=10.0, deprecated=11.0))); [Deprecated (PlatformName.MacOSX, 10, 13, "Use the default constructor followed by a call to the 'SetInsertionHandler' method.")] @@ -965,9 +1011,10 @@ interface TKTokenWatcher { [Experimental ("APL0001")] #endif [iOS (15, 0), Mac (12, 0), MacCatalyst (15, 0), TV (15, 0)] - [BaseType (typeof (NSObject))] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface TKTokenWatcherTokenInfo { + interface TKTokenWatcherTokenInfo + { [Export ("tokenID")] string TokenId { get; } diff --git a/src/eventkit.cs b/src/eventkit.cs index 1727818fcdbd..00c950adde57 100644 --- a/src/eventkit.cs +++ b/src/eventkit.cs @@ -455,7 +455,7 @@ interface EKRecurrenceEnd : NSCopying, NSSecureCoding { interface EKRecurrenceDayOfWeek : NSCopying, NSSecureCoding { [Export ("dayOfTheWeek")] #if NET - EKWeekday DayOfTheWeek { get; } + EKWeekday DayOfTheWeek { get; } #else nint DayOfTheWeek { get; } #endif diff --git a/src/foundation.cs b/src/foundation.cs index b6077cd924b1..258609434527 100644 --- a/src/foundation.cs +++ b/src/foundation.cs @@ -6015,9 +6015,7 @@ string SuggestedInvocationPhrase { #if HAS_APPCLIP // Inlined from NSUserActivity (AppClip) - [iOS (14, 0)] - [NoTV] - [NoMac] + [iOS (14,0)][NoTV][NoMac] [MacCatalyst (14, 0)] [Export ("appClipActivationPayload", ArgumentSemantic.Strong)] [NullAllowed] @@ -9468,7 +9466,7 @@ interface NSLinguisticAnalysis { [Wrap ("GetLinguisticTags (This, range, scheme.GetConstant ()!, options, orthography, out tokenRanges)")] #if NET - NSLinguisticTag [] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue [] tokenRanges); + NSLinguisticTag[] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue[] tokenRanges); #else NSLinguisticTagUnit [] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue [] tokenRanges); #endif @@ -9668,11 +9666,9 @@ interface NSObject2 : NSObjectProtocol { [Export ("exposedBindings")] NSString [] ExposedBindings (); #else - [NoiOS] - [NoMacCatalyst] - [NoTV] + [NoiOS][NoMacCatalyst][NoTV] [Export ("exposedBindings")] - NSString [] ExposedBindings { get; } + NSString[] ExposedBindings { get; } #endif #if !NET @@ -14925,24 +14921,20 @@ interface NSFileProviderService { #if MONOMAC partial interface NSFilePresenter { - [NoiOS] - [NoMacCatalyst] - [NoTV] + [NoiOS][NoMacCatalyst][NoTV] [NullAllowed] [Export ("primaryPresentedItemURL")] NSUrl PrimaryPresentedItemUrl { get; } } - [NoiOS] - [NoMacCatalyst] - [NoTV] - [Deprecated (PlatformName.MacOSX, 12, 0, message: "Use the Network.framework instead.")] + [NoiOS][NoMacCatalyst][NoTV] + [Deprecated (PlatformName.MacOSX, 12, 0, message : "Use the Network.framework instead.")] [BaseType (typeof (NSObject))] [DisableDefaultCtor] partial interface NSHost { [Static, Internal, Export ("currentHost")] - NSHost _Current { get; } + NSHost _Current { get;} [Static, Internal, Export ("hostWithName:")] NSHost _FromName ([NullAllowed] string name); @@ -14969,7 +14961,7 @@ partial interface NSHost { string _Address { get; } [Internal, Export ("addresses")] - string [] _Addresses { get; } + string [] _Addresses { get; } [Export ("hash"), Internal] nuint _Hash { get; } @@ -17667,8 +17659,7 @@ interface NSUrlSessionWebSocketTask { [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/frameworks.sources b/src/frameworks.sources index fbe6e6aae8dd..99c93c5ba037 100644 --- a/src/frameworks.sources +++ b/src/frameworks.sources @@ -835,7 +835,6 @@ FOUNDATION_CORE_SOURCES = \ FOUNDATION_SOURCES = \ Foundation/Additions.cs \ Foundation/Compat.cs \ - Foundation/MonoTouchException.cs \ Foundation/NSAppleEventDescriptor.cs \ Foundation/NSArray.cs \ Foundation/NSArray_1.cs \ @@ -1936,6 +1935,7 @@ SHARED_CORE_SOURCES = \ DotNetGlobals.cs \ MinimumVersions.cs \ MonoPInvokeCallbackAttribute.cs \ + ObjCBindings/BindFromAttribute.cs \ ObjCBindings/BindingTypeAttribute.cs \ ObjCBindings/BindingTypeTag.cs \ ObjCBindings/ExportAttribute.cs \ diff --git a/src/gamekit.cs b/src/gamekit.cs index 407a381b191f..8481c3ce6f1b 100644 --- a/src/gamekit.cs +++ b/src/gamekit.cs @@ -58,10 +58,10 @@ namespace GameKit { delegate void GKEntriesForPlayersHandler (GKLeaderboardEntry localPlayerEntry, GKLeaderboardEntry [] entries, NSError error); #if MONOMAC - delegate void GKImageLoadedHandler (NSImage image, NSError error); + delegate void GKImageLoadedHandler (NSImage image, NSError error); delegate void GKPlayerPhotoLoaded (NSImage photo, NSError error); delegate void GKChallengeComposeHandler (NSViewController composeController, bool issuedChallenge, string [] sentPlayerIDs); - delegate void GKChallengeComposeHandler2 (NSViewController composeController, bool issuedChallenge, GKPlayer [] sentPlayers); + delegate void GKChallengeComposeHandler2 (NSViewController composeController, bool issuedChallenge, GKPlayer[] sentPlayers); #else delegate void GKImageLoadedHandler (UIImage image, NSError error); delegate void GKPlayerPhotoLoaded (UIImage photo, NSError error); @@ -765,8 +765,8 @@ interface GKLeaderboardViewControllerDelegate { [Deprecated (PlatformName.MacOSX, 10, 10, message: "Use 'GKGameCenterViewController' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'GKGameCenterViewController' instead.")] #if MONOMAC - [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKLeaderboardViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] - interface GKLeaderboardViewController + [BaseType (typeof (GKGameCenterViewController), Events=new Type [] { typeof (GKLeaderboardViewControllerDelegate)}, Delegates=new string [] {"WeakDelegate"})] + interface GKLeaderboardViewController #else [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKLeaderboardViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] interface GKLeaderboardViewController : UIAppearance @@ -1466,7 +1466,7 @@ interface GKMatchmaker { [MacCatalyst (13, 1)] #if MONOMAC - [BaseType (typeof (NSViewController), Delegates = new string [] { "WeakMatchmakerDelegate" }, Events = new Type [] { typeof (GKMatchmakerViewControllerDelegate) })] + [BaseType (typeof (NSViewController), Delegates=new string [] { "WeakMatchmakerDelegate" }, Events=new Type [] {typeof(GKMatchmakerViewControllerDelegate)})] #else [BaseType (typeof (UINavigationController), Delegates = new string [] { "WeakMatchmakerDelegate" }, Events = new Type [] { typeof (GKMatchmakerViewControllerDelegate) })] #endif @@ -1839,8 +1839,8 @@ interface GKAchievementViewControllerDelegate { [Deprecated (PlatformName.MacOSX, 10, 10, message: "Use 'GKGameCenterViewController' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'GKGameCenterViewController' instead.")] #if MONOMAC - [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKAchievementViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] - interface GKAchievementViewController + [BaseType (typeof (GKGameCenterViewController), Events=new Type [] { typeof (GKAchievementViewControllerDelegate)}, Delegates=new string [] {"WeakDelegate"})] + interface GKAchievementViewController #else [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKAchievementViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] interface GKAchievementViewController : UIAppearance @@ -1885,7 +1885,7 @@ interface GKDialogController { [NoTV] [Deprecated (PlatformName.MacCatalyst, 13, 1)] #if MONOMAC - [BaseType (typeof (NSViewController), Events = new Type [] { typeof (GKFriendRequestComposeViewControllerDelegate) }, Delegates = new string [] { "WeakComposeViewDelegate" })] + [BaseType (typeof (NSViewController), Events=new Type [] { typeof (GKFriendRequestComposeViewControllerDelegate)}, Delegates=new string[] {"WeakComposeViewDelegate"})] interface GKFriendRequestComposeViewController : GKViewController { [Export ("initWithNibName:bundle:")] [NoiOS] diff --git a/src/healthkit.cs b/src/healthkit.cs index 52cc1a2262ec..a6acc3a0510a 100644 --- a/src/healthkit.cs +++ b/src/healthkit.cs @@ -220,7 +220,7 @@ public enum HKAudiogramSensitivityTestSide : long { #if NET /// The completion handler for . /// Completion handler for anchored object queries. - delegate void HKAnchoredObjectResultHandler (HKAnchoredObjectQuery query, HKSample [] results, nuint newAnchor, NSError error); + delegate void HKAnchoredObjectResultHandler (HKAnchoredObjectQuery query, HKSample[] results, nuint newAnchor, NSError error); #else delegate void HKAnchoredObjectResultHandler2 (HKAnchoredObjectQuery query, HKSample [] results, nuint newAnchor, NSError error); diff --git a/src/mapkit.cs b/src/mapkit.cs index 3a4245405bf5..2a5bfe34006e 100644 --- a/src/mapkit.cs +++ b/src/mapkit.cs @@ -28,11 +28,11 @@ using System; #if MONOMAC -using UIImage = AppKit.NSImage; -using UIView = AppKit.NSView; -using UIEdgeInsets = AppKit.NSEdgeInsets; -using UIColor = AppKit.NSColor; -using UIScene = AppKit.NSColor; +using UIImage=AppKit.NSImage; +using UIView=AppKit.NSView; +using UIEdgeInsets=AppKit.NSEdgeInsets; +using UIColor=AppKit.NSColor; +using UIScene=AppKit.NSColor; using UIControl = AppKit.NSControl; using UIBarButtonItem = Foundation.NSObject; using UIViewController = AppKit.NSViewController; diff --git a/src/mediaextension.cs b/src/mediaextension.cs index 8706da954203..b7a7883c2c46 100644 --- a/src/mediaextension.cs +++ b/src/mediaextension.cs @@ -11,10 +11,11 @@ using UniformTypeIdentifiers; namespace MediaExtension { - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Native] [ErrorDomain ("MediaExtensionErrorDomain")] - public enum MEError : long { + public enum MEError : long + { UnsupportedFeature = -19320, AllocationFailure = -19321, InvalidParameter = -19322, @@ -29,33 +30,37 @@ public enum MEError : long { ReferenceMissing = -19331, } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Native] - public enum MEFileInfoFragmentsStatus : long { + public enum MEFileInfoFragmentsStatus : long + { CouldNotContainFragments = 0, ContainsFragments = 1, CouldContainButDoesNotContainFragments = 2, } - [Flags, NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [Flags, NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Native] - public enum MEFormatReaderParseAdditionalFragmentsStatus : ulong { + public enum MEFormatReaderParseAdditionalFragmentsStatus : ulong + { SizeIncreased = 1uL << 0, FragmentAdded = 1uL << 1, FragmentsComplete = 1uL << 2, } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface MEFormatReaderInstantiationOptions : NSCopying { + interface MEFormatReaderInstantiationOptions : NSCopying + { [Export ("allowIncrementalFragmentParsing")] bool AllowIncrementalFragmentParsing { get; } } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEFormatReaderExtension { + interface MEFormatReaderExtension + { [Abstract] [Export ("formatReaderWithByteSource:options:error:")] [return: NullAllowed] @@ -63,13 +68,14 @@ interface MEFormatReaderExtension { } delegate void MEFormatReaderLoadFileInfoCallback ([NullAllowed] MEFileInfo fileInfo, [NullAllowed] NSError error); - delegate void MEFormatReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem [] metadata, [NullAllowed] NSError error); - delegate void MEFormatReaderLoadTrackReadersCallback ([NullAllowed] IMETrackReader [] trackReaders, [NullAllowed] NSError error); + delegate void MEFormatReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem[] metadata, [NullAllowed] NSError error); + delegate void MEFormatReaderLoadTrackReadersCallback ([NullAllowed] IMETrackReader[] trackReaders, [NullAllowed] NSError error); delegate void MEFormatReaderParseAdditionalFragmentsCallback ([NullAllowed] MEFormatReaderParseAdditionalFragmentsStatus fragmentStatus, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEFormatReader { + interface MEFormatReader + { [Abstract] [Export ("loadFileInfoWithCompletionHandler:")] void LoadFileInfo (MEFormatReaderLoadFileInfoCallback completionHandler); @@ -88,9 +94,10 @@ interface MEFormatReader { interface IMEFormatReader { } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] - interface MEFileInfo : NSCopying { + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject))] + interface MEFileInfo : NSCopying + { [Export ("duration", ArgumentSemantic.Assign)] CMTime Duration { get; set; } @@ -103,11 +110,12 @@ interface MEFileInfo : NSCopying { delegate void METrackReaderLoadUneditedDurationCallback ([NullAllowed] CMTime uneditedDuration, [NullAllowed] NSError error); delegate void METrackReaderLoadTotalSampleDataLengthCallback (long totalSampleDataLength, [NullAllowed] NSError error); delegate void METrackReaderLoadEstimatedDataRateCallback (float estimatedDataRate, [NullAllowed] NSError error); - delegate void METrackReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem [] metadata, [NullAllowed] NSError error); + delegate void METrackReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem[] metadata, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface METrackReader { + interface METrackReader + { [Abstract] [Export ("loadTrackInfoWithCompletionHandler:")] void LoadTrackInfo (METrackReaderLoadTrackInfoCallback completionHandler); @@ -139,14 +147,15 @@ interface METrackReader { interface IMETrackReader { } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface METrackInfo : NSCopying { + interface METrackInfo : NSCopying + { [Export ("initWithMediaType:trackID:formatDescriptions:")] [DesignatedInitializer] // It's not clear from the documentation which type the format descriptors are, so keep as an array of NSObject for now. - NativeHandle Constructor (CMMediaType mediaType, int trackId, [Params] NSObject [] formatDescriptions); + NativeHandle Constructor (CMMediaType mediaType, int trackId, [Params] NSObject[] formatDescriptions); [Export ("mediaType")] CMMediaType MediaType { get; } @@ -160,7 +169,7 @@ interface METrackInfo : NSCopying { // It's not clear from the documentation which type the format descriptors are, so keep as an array of NSObject for now. // However, name as 'Weak' to leave the good name open for when we know. [Export ("formatDescriptions", ArgumentSemantic.Copy)] - NSObject [] WeakFormatDescriptions { get; } + NSObject[] WeakFormatDescriptions { get; } // Inlined from the OptionalProperties (METrackInfo) category [Export ("naturalTimescale")] @@ -169,7 +178,7 @@ interface METrackInfo : NSCopying { // Inlined from the OptionalProperties (METrackInfo) category [Export ("trackEdits", ArgumentSemantic.Copy), NullAllowed] [BindAs (typeof (CMTimeMapping []))] - NSValue [] TrackEdits { get; set; } + NSValue[] TrackEdits { get; set; } // Inlined from the LanguageTagOptionalProperties (METrackInfo) category [NullAllowed, Export ("extendedLanguageTag")] @@ -197,9 +206,10 @@ interface METrackInfo : NSCopying { delegate void MESampleCursorLoadSampleBufferCallback ([NullAllowed] CMSampleBuffer newSampleBuffer, [NullAllowed] NSError error); delegate void MESampleCursorLoadPostDecodeProcessingMetadataCallback ([NullAllowed] NSDictionary postDecodeProcessingMetadata, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MESampleCursor : INSCopying { + interface MESampleCursor : INSCopying + { [Abstract] [Export ("presentationTimeStamp")] CMTime PresentationTimeStamp { get; } @@ -289,10 +299,11 @@ interface MESampleCursor : INSCopying { interface IMESampleCursor { } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface MESampleCursorChunk : NSCopying { + interface MESampleCursorChunk : NSCopying + { [Export ("initWithByteSource:chunkStorageRange:chunkInfo:sampleIndexWithinChunk:")] [DesignatedInitializer] #if XAMCORE_5_0 @@ -327,10 +338,11 @@ interface MESampleCursorChunk : NSCopying { nint SampleIndexWithinChunk { get; } } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface MESampleLocation : NSCopying { + interface MESampleLocation : NSCopying + { [Export ("initWithByteSource:sampleLocation:")] [DesignatedInitializer] NativeHandle Constructor (MEByteSource byteSource, AVSampleCursorStorageRange sampleLocation); @@ -342,10 +354,11 @@ interface MESampleLocation : NSCopying { MEByteSource ByteSource { get; } } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject))] [DisableDefaultCtor] - interface MEEstimatedSampleLocation : INSCopying { + interface MEEstimatedSampleLocation : INSCopying + { [Export ("initWithByteSource:estimatedSampleLocation:refinementDataLocation:")] [DesignatedInitializer] NativeHandle Constructor (MEByteSource byteSource, AVSampleCursorStorageRange estimatedSampleLocation, AVSampleCursorStorageRange refinementDataLocation); @@ -360,9 +373,10 @@ interface MEEstimatedSampleLocation : INSCopying { MEByteSource ByteSource { get; } } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject), Name = "MEHEVCDependencyInfo")] - interface MEHevcDependencyInfo : INSCopying { + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject), Name = "MEHEVCDependencyInfo")] + interface MEHevcDependencyInfo : INSCopying + { [Export ("temporalSubLayerAccess")] bool TemporalSubLayerAccess { [Bind ("hasTemporalSubLayerAccess")] get; set; } @@ -404,10 +418,11 @@ interface MEHevcDependencyInfo : INSCopying { delegate void MEByteSourceReadBytesCallback (nuint bytesRead, [NullAllowed] NSError error); delegate void MEByteSourceReadDataCallback ([NullAllowed] NSData data, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MEByteSource { + interface MEByteSource + { [Export ("fileName")] string FileName { get; } @@ -418,7 +433,7 @@ interface MEByteSource { long FileLength { get; } [Export ("relatedFileNamesInSameDirectory")] - string [] RelatedFileNamesInSameDirectory { get; } + string[] RelatedFileNamesInSameDirectory { get; } [Export ("readDataOfLength:fromOffset:toDestination:completionHandler:")] unsafe void ReadData (nuint length, long offset, byte* dest, MEByteSourceReadBytesCallback completionHandler); @@ -440,16 +455,18 @@ interface MEByteSource { [Flags] [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] - public enum MEDecodeFrameStatus : ulong { + public enum MEDecodeFrameStatus : ulong + { NoStatus = 0, FrameDropped = 1uL << 0, } delegate void MEVideoDecoderDecodeFrameCallback ([NullAllowed] CVImageBuffer imageBuffer, MEDecodeFrameStatus decodeStatus, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEVideoDecoder { + interface MEVideoDecoder + { [Export ("producesRAWOutput")] bool ProducesRawOutput { get; } @@ -467,7 +484,7 @@ interface MEVideoDecoder { // of (and not call themselves), in which case the manual code would be // useless. Thus there's no strongly typed binding for this property. [Export ("supportedPixelFormatsOrderedByQuality")] - NSNumber [] SupportedPixelFormatsOrderedByQuality { get; } + NSNumber[] SupportedPixelFormatsOrderedByQuality { get; } [Export ("reducedResolution", ArgumentSemantic.Assign)] CGSize ReducedResolution { get; set; } @@ -477,7 +494,7 @@ interface MEVideoDecoder { // of (and not call themselves), in which case the manual code would be // useless. Thus there's no strongly typed binding for this property. [Export ("pixelFormatsWithReducedResolutionDecodeSupport")] - NSNumber [] PixelFormatsWithReducedResolutionDecodeSupport { get; } + NSNumber[] PixelFormatsWithReducedResolutionDecodeSupport { get; } [Abstract] [Export ("readyForMoreMediaData")] @@ -491,9 +508,9 @@ interface MEVideoDecoder { bool CanAcceptFormatDescription (CMFormatDescription formatDescription); } - interface IMEVideoDecoder { } + interface IMEVideoDecoder {} - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Static] interface MEVideoDecoderFields { [Notification] @@ -501,9 +518,10 @@ interface MEVideoDecoderFields { NSString ReadyForMoreMediaDataDidChangeNotification { get; } } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false, Name = "MERAWProcessorExtension")] - interface MERawProcessorExtension { + interface MERawProcessorExtension + { [Abstract] [Export ("init")] NativeHandle Constructor (); @@ -514,9 +532,10 @@ interface MERawProcessorExtension { IMERawProcessor CreateProcessor (CMVideoFormatDescription formatDescription, MERawProcessorPixelBufferManager extensionPixelBufferManager, [NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject), Name = "MERAWProcessorPixelBufferManager")] - interface MERawProcessorPixelBufferManager { + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject), Name = "MERAWProcessorPixelBufferManager")] + interface MERawProcessorPixelBufferManager + { [Export ("pixelBufferAttributes", ArgumentSemantic.Copy)] NSDictionary PixelBufferAttributes { get; set; } @@ -525,9 +544,10 @@ interface MERawProcessorPixelBufferManager { CVPixelBuffer CreatePixelBuffer ([NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject), Name = "MERAWProcessingParameter")] - interface MERawProcessingParameter { + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject), Name = "MERAWProcessingParameter")] + interface MERawProcessingParameter + { [Export ("name")] string Name { get; } @@ -541,9 +561,10 @@ interface MERawProcessingParameter { bool Enabled { get; set; } } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingListElementParameter")] - interface MERawProcessingListElementParameter { + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingListElementParameter")] + interface MERawProcessingListElementParameter + { [Export ("initWithName:description:elementID:")] NativeHandle Constructor (string name, string description, nint elementId); @@ -551,10 +572,11 @@ interface MERawProcessingListElementParameter { nint ListElementId { get; } } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingBooleanParameter")] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingBooleanParameter")] [DisableDefaultCtor] - interface MERawProcessingBooleanParameter { + interface MERawProcessingBooleanParameter + { [Export ("initWithName:key:description:initialValue:")] NativeHandle Constructor (string name, string key, string description, bool initialValue); @@ -583,10 +605,11 @@ interface MERawProcessingBooleanParameter { bool HasCameraValue ([NullAllowed] out bool cameraValue); } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingIntegerParameter")] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingIntegerParameter")] [DisableDefaultCtor] - interface MERawProcessingIntegerParameter { + interface MERawProcessingIntegerParameter + { [Export ("initWithName:key:description:initialValue:maximum:minimum:")] NativeHandle Constructor (string name, string key, string description, nint initialValue, nint maximum, nint minimum); @@ -621,10 +644,11 @@ interface MERawProcessingIntegerParameter { bool HasCameraValue ([NullAllowed] out nint cameraValue); } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingFloatParameter")] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingFloatParameter")] [DisableDefaultCtor] - interface MERawProcessingFloatParameter { + interface MERawProcessingFloatParameter + { [Export ("initWithName:key:description:initialValue:maximum:minimum:")] NativeHandle Constructor (string name, string key, string description, float initialValue, float maximum, float minimum); @@ -659,27 +683,28 @@ interface MERawProcessingFloatParameter { bool HasCameraValue ([NullAllowed] out float cameraValue); } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingListParameter")] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingListParameter")] [DisableDefaultCtor] - interface MERawProcessingListParameter { + interface MERawProcessingListParameter + { [Export ("initWithName:key:description:list:initialValue:")] - NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue); + NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue); [Internal] [Export ("initWithName:key:description:list:initialValue:neutralValue:")] - NativeHandle _InitWithNeutralValue (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralValue); + NativeHandle _InitWithNeutralValue (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralValue); [Internal] [Export ("initWithName:key:description:list:initialValue:cameraValue:")] - NativeHandle _InitWithCameraValue (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint cameraValue); + NativeHandle _InitWithCameraValue (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint cameraValue); [Export ("initWithName:key:description:list:initialValue:neutralValue:cameraValue:")] [DesignatedInitializer] - NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralValue, nint cameraValue); + NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralValue, nint cameraValue); [Export ("listElements")] - MERawProcessingListElementParameter [] ListElements { get; } + MERawProcessingListElementParameter[] ListElements { get; } [Export ("initialValue")] nint InitialValue { get; } @@ -694,22 +719,24 @@ interface MERawProcessingListParameter { bool HasCameraValue ([NullAllowed] out nint cameraValue); } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingSubGroupParameter")] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingSubGroupParameter")] [DisableDefaultCtor] - interface MERawProcessingSubGroupParameter { + interface MERawProcessingSubGroupParameter + { [Export ("initWithName:description:parameters:")] - NativeHandle Constructor (string name, string description, MERawProcessingParameter [] parameters); + NativeHandle Constructor (string name, string description, MERawProcessingParameter[] parameters); [Export ("subGroupParameters")] - MERawProcessingParameter [] SubGroupParameters { get; } + MERawProcessingParameter[] SubGroupParameters { get; } } delegate void MERawProcessorProcessFrameCallback ([NullAllowed] CVPixelBuffer pixelBuffer, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15, 0), MacCatalyst (18, 0)] + [NoTV, NoiOS, Mac (15,0), MacCatalyst (18, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false, Name = "MERAWProcessor")] - interface MERawProcessor { + interface MERawProcessor + { [Export ("metalDeviceRegistryID")] ulong MetalDeviceRegistryId { get; set; } @@ -718,7 +745,7 @@ interface MERawProcessor { [Abstract] [Export ("processingParameters")] - MERawProcessingParameter [] ProcessingParameters { get; } + MERawProcessingParameter[] ProcessingParameters { get; } [Abstract] [Export ("readyForMoreMediaData")] @@ -729,9 +756,10 @@ interface MERawProcessor { void ProcessFrame (CVPixelBuffer inputFrame, MERawProcessorProcessFrameCallback completionHandler); } - [NoTV, NoiOS, Mac (15, 0), MacCatalyst (18, 0)] + [NoTV, NoiOS, Mac (15,0), MacCatalyst (18, 0)] [Static] - interface MERawProcessorFields { + interface MERawProcessorFields + { [Notification] [Field ("MERAWProcessorValuesDidChangeNotification")] NSString ValuesDidChangeNotification { get; } @@ -741,11 +769,12 @@ interface MERawProcessorFields { NSString ReadyForMoreMediaDataDidChangeNotification { get; } } - interface IMERawProcessor { } + interface IMERawProcessor {} - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEVideoDecoderExtension { + interface MEVideoDecoderExtension + { [Abstract] [Export ("init")] NativeHandle Constructor (); @@ -756,9 +785,10 @@ interface MEVideoDecoderExtension { IMEVideoDecoder CreateVideoDecoder (CMVideoCodecType codecType, CMVideoFormatDescription videoFormatDescription, NSDictionary videoDecoderSpecifications, MEVideoDecoderPixelBufferManager extensionDecoderPixelBufferManager, [NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] - interface MEVideoDecoderPixelBufferManager { + [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [BaseType (typeof(NSObject))] + interface MEVideoDecoderPixelBufferManager + { [Export ("pixelBufferAttributes", ArgumentSemantic.Copy)] NSDictionary PixelBufferAttributes { get; set; } @@ -771,8 +801,9 @@ interface MEVideoDecoderPixelBufferManager { } [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof (NSObject))] - interface MEDecodeFrameOptions { + [BaseType (typeof(NSObject))] + interface MEDecodeFrameOptions + { [Export ("doNotOutputFrame")] bool DoNotOutputFrame { get; set; } diff --git a/src/mediaplayer.cs b/src/mediaplayer.cs index 602bc96109ae..8826acbb7651 100644 --- a/src/mediaplayer.cs +++ b/src/mediaplayer.cs @@ -371,7 +371,7 @@ interface MPMediaLibrary : NSSecureCoding { [Export ("addItemWithProductID:completionHandler:")] [Async] #if IOS - void AddItem (string productID, [NullAllowed] Action completionHandler); + void AddItem (string productID, [NullAllowed] Action completionHandler); #else void AddItem (string productID, [NullAllowed] Action completionHandler); #endif @@ -824,7 +824,7 @@ interface MPMoviePlayerTimedMetadataEventArgs { [NoMac] #if NET - [TV (16, 0)] + [TV (16,0)] [MacCatalyst (13, 1)] #else [Obsoleted (PlatformName.TvOS, 14, 0, message: "Removed in Xcode 12.")] @@ -1250,7 +1250,7 @@ interface MPTimedMetadata { [Export ("value")] #if NET - NSObject Value { get; } + NSObject Value { get; } #else NSObject value { get; } #endif diff --git a/src/metal.cs b/src/metal.cs index 74be7fab19d8..34e4abd28161 100644 --- a/src/metal.cs +++ b/src/metal.cs @@ -1584,7 +1584,7 @@ partial interface MTLDevice { [MacCatalyst (14, 0)] [NullAllowed, Export ("counterSets")] #if NET - IMTLCounterSet [] CounterSets { get; } + IMTLCounterSet[] CounterSets { get; } #else [Obsolete ("Use 'GetIMTLCounterSets' instead.")] MTLCounterSet [] CounterSets { get; } diff --git a/src/metrickit.cs b/src/metrickit.cs index f1ecfa2488c8..2c75b672a4c2 100644 --- a/src/metrickit.cs +++ b/src/metrickit.cs @@ -163,7 +163,7 @@ interface MXMetaData : NSSecureCoding { [MacCatalyst (14, 0)] [Export ("dictionaryRepresentation")] #if MONOMAC - NSDictionary DictionaryRepresentation { get; } + NSDictionary DictionaryRepresentation { get; } #else [Internal] NSDictionary _DictionaryRepresentation14 { get; } diff --git a/src/networkextension.cs b/src/networkextension.cs index 4bf350d5a2e6..698c2462256d 100644 --- a/src/networkextension.cs +++ b/src/networkextension.cs @@ -1322,9 +1322,9 @@ interface NETunnelProviderManager { // CopyAppRules was incorrectly bound to AppRules and it is only available on macOS #if NET || MONOMAC || __MACCATALYST__ - [NoTV, NoiOS, MacCatalyst (15, 0)] + [NoTV, NoiOS, MacCatalyst (15,0)] [Export ("appRules", ArgumentSemantic.Copy)] - NEAppRule [] AppRules { get; set; } + NEAppRule[] AppRules { get; set; } #else [NoTV] [Obsolete ("Use 'CopyAppRules' instead, this property will be removed in the future.")] diff --git a/src/quicklook.cs b/src/quicklook.cs index 4d5a08c3abde..7b841c61b331 100644 --- a/src/quicklook.cs +++ b/src/quicklook.cs @@ -33,7 +33,7 @@ using CoreGraphics; #if MONOMAC using AppKit; -using UIWindowSceneActivationConfiguration = Foundation.NSObject; +using UIWindowSceneActivationConfiguration=Foundation.NSObject; #else using UIKit; #endif @@ -315,9 +315,7 @@ interface QLPreviewingController { } #else [Static] - [NoiOS] - [NoMacCatalyst] - [NoTV] + [NoiOS][NoMacCatalyst][NoTV] interface QLThumbnailImage { [Internal, Field ("kQLThumbnailOptionScaleFactorKey")] NSString OptionScaleFactorKey { get; } diff --git a/src/rgen/.gitignore b/src/rgen/.gitignore new file mode 100644 index 000000000000..a0857bf6b0cc --- /dev/null +++ b/src/rgen/.gitignore @@ -0,0 +1 @@ +Generated \ No newline at end of file diff --git a/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj b/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj index 5a77c43cfbfb..d6b58e2f9bae 100644 --- a/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj +++ b/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj @@ -39,6 +39,9 @@ Generator/DictionaryComparer.cs + + Generator/Attributes/BindFromData.cs + Generator/Attributes/FieldData.cs @@ -60,11 +63,20 @@ Generator/Attributes/UnsupportedOSPlatformData.cs + + Generator/Extensions/ApplePlatformExtensions.cs + Generator/Extensions/CompilationExtensions.cs - - Generator/Extensions/TypeSymbolExtensions.cs + + Generator/Extensions/Delegates.cs + + + Generator/Extensions/TypeSymbolExtensions.Core.cs + + + Generator/Extensions/TypeSymbolExtensions.Generator.cs Generator/Extensions/TypedConstantExtensions.cs @@ -72,17 +84,8 @@ Generator/Extensions/StringExtensions.cs - - Generator/Availability/PlatformAvailability.cs - - - Generator/Availability/PlatformAvailabilityBuilder.cs - - - Generator/Availability/SymbolAvailability.cs - - - Generator/Availability/SymbolAvailabilityBuilder.cs + + Generator/Availability/*.cs True diff --git a/src/rgen/Microsoft.Macios.Generator/Attributes/BindFromData.cs b/src/rgen/Microsoft.Macios.Generator/Attributes/BindFromData.cs new file mode 100644 index 000000000000..9e456d77206e --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Attributes/BindFromData.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Generator.Attributes; + +readonly struct BindFromData : IEquatable { + + public string Type { get; } + public string? OriginalType { get; } + + public BindFromData (string type) + { + Type = type; + } + + public BindFromData (string type, string? originalType) + { + Type = type; + OriginalType = originalType; + } + + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out BindFromData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string? type; + string? originalType = null; + + switch (count) { + case 1: + type = ((INamedTypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + break; + default: + // no other constructors are available + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (type); + return true; + } + + foreach (var (name, value) in attributeData.NamedArguments) { + switch (name) { + case "Type": + type = ((INamedTypeSymbol) value.Value!).ToDisplayString (); + break; + case "OriginalType": + originalType = ((INamedTypeSymbol) value.Value!).ToDisplayString (); + break; + default: + data = null; + return false; + } + } + data = new (type, originalType); + return true; + } + + /// + public bool Equals (BindFromData other) + { + return Type == other.Type && OriginalType == other.OriginalType; + } + + /// + public override bool Equals (object? obj) + { + return obj is BindFromData other && Equals (other); + } + + /// + public override int GetHashCode () + { + return HashCode.Combine (Type, OriginalType); + } + + public static bool operator == (BindFromData x, BindFromData y) + { + return x.Equals (y); + } + + public static bool operator != (BindFromData x, BindFromData y) + { + return !(x == y); + } + + public override string ToString () + { + return $"{{ Type: '{Type}', OriginalType: '{OriginalType ?? "null"}' }}"; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/Attributes/BindingTypeData.cs b/src/rgen/Microsoft.Macios.Generator/Attributes/BindingTypeData.cs index d9258f5620be..00e149f57456 100644 --- a/src/rgen/Microsoft.Macios.Generator/Attributes/BindingTypeData.cs +++ b/src/rgen/Microsoft.Macios.Generator/Attributes/BindingTypeData.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; using System.Diagnostics.CodeAnalysis; +using System.Reflection; using Microsoft.CodeAnalysis; namespace Microsoft.Macios.Generator.Attributes; @@ -106,6 +107,21 @@ public override string ToString () /// public T? Flags { get; } = default; + /// + /// The visibility of the default constructor for a core image filter. + /// + public MethodAttributes DefaultCtorVisibility { get; init; } = MethodAttributes.Public; + + /// + /// The visibility of the IntPtr constructor for a core image filter. + /// + public MethodAttributes IntPtrCtorVisibility { get; init; } = MethodAttributes.PrivateScope; + + /// + /// The visibility of the string constructor for a core image filter. + /// + public MethodAttributes StringCtorVisibility { get; init; } = MethodAttributes.PrivateScope; + public BindingTypeData (string? name) { Name = name; @@ -134,8 +150,12 @@ public static bool TryParse (AttributeData attributeData, { data = null; var count = attributeData.ConstructorArguments.Length; - string? name; + string? name = null; T? flags = default; + var defaultCtorVisibility = MethodAttributes.Public; + var intPtrCtorVisibility = MethodAttributes.PrivateScope; + var stringCtorVisibility = MethodAttributes.PrivateScope; + switch (count) { case 0: // use the defaults @@ -143,7 +163,11 @@ public static bool TryParse (AttributeData attributeData, flags = default; break; case 1: - name = (string?) attributeData.ConstructorArguments [0].Value!; + if (attributeData.ConstructorArguments [0].Value is string) { + name = (string?) attributeData.ConstructorArguments [0].Value!; + } else { + flags = (T) attributeData.ConstructorArguments [0].Value!; + } break; case 2: // we have the name and the config flags present @@ -168,14 +192,28 @@ public static bool TryParse (AttributeData attributeData, case "Flags": flags = (T) value.Value!; break; + case "DefaultCtorVisibility": + defaultCtorVisibility = (MethodAttributes) Convert.ToSingle ((int) value.Value!); + break; + case "IntPtrCtorVisibility": + intPtrCtorVisibility = (MethodAttributes) Convert.ToSingle ((int) value.Value!); + break; + case "StringCtorVisibility": + stringCtorVisibility = (MethodAttributes) Convert.ToSingle ((int) value.Value!); + break; default: data = null; return false; } } - data = flags is not null ? - new (name, flags) : new (name); + data = flags is not null + ? new (name, flags) + : new (name) { + DefaultCtorVisibility = defaultCtorVisibility, + IntPtrCtorVisibility = intPtrCtorVisibility, + StringCtorVisibility = stringCtorVisibility, + }; return true; } diff --git a/src/rgen/Microsoft.Macios.Generator/Attributes/ExportData.cs b/src/rgen/Microsoft.Macios.Generator/Attributes/ExportData.cs index 786d4de85902..90854938ec78 100644 --- a/src/rgen/Microsoft.Macios.Generator/Attributes/ExportData.cs +++ b/src/rgen/Microsoft.Macios.Generator/Attributes/ExportData.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; using System.Diagnostics.CodeAnalysis; +using System.Text; using Microsoft.CodeAnalysis; using ObjCRuntime; @@ -28,6 +29,27 @@ namespace Microsoft.Macios.Generator.Attributes; /// public ArgumentSemantic ArgumentSemantic { get; } = ArgumentSemantic.None; + /// + /// Get the native prefix to be used in the custom marshal directive. + /// + /// Should only be present with the CustomeMarshalDirective flag. + /// + public string? NativePrefix { get; init; } + + /// + /// Get the native sufix to be used in the custom marshal directive. + /// + /// Should only be present with the CustomeMarshalDirective flag. + /// + public string? NativeSuffix { get; init; } + + /// + /// Get the library to be used in the custom marshal directive. + /// + /// Should only be present with the CustomeMarshalDirective flag. + /// + public string? Library { get; init; } + public ExportData () { } public ExportData (string? selector) @@ -62,6 +84,12 @@ public static bool TryParse (AttributeData attributeData, string? selector = null; ArgumentSemantic argumentSemantic = ArgumentSemantic.None; T? flags = default; + + // custom marshal directive values + string? nativePrefix = null; + string? nativeSuffix = null; + string? library = null; + switch (count) { case 1: selector = (string?) attributeData.ConstructorArguments [0].Value!; @@ -106,14 +134,35 @@ public static bool TryParse (AttributeData attributeData, case "Flags": flags = (T) value.Value!; break; + case "NativePrefix": + nativePrefix = (string?) value.Value!; + break; + case "NativeSuffix": + nativeSuffix = (string?) value.Value!; + break; + case "Library": + library = (string?) value.Value!; + break; default: data = null; return false; } } - data = flags is not null ? - new (selector, argumentSemantic, flags) : new (selector, argumentSemantic); + if (flags is not null) { + data = new (selector, argumentSemantic, flags) { + NativePrefix = nativePrefix, + NativeSuffix = nativeSuffix, + Library = library + }; + return true; + } + + data = new (selector, argumentSemantic) { + NativePrefix = nativePrefix, + NativeSuffix = nativeSuffix, + Library = library + }; return true; } @@ -124,10 +173,18 @@ public bool Equals (ExportData other) return false; if (ArgumentSemantic != other.ArgumentSemantic) return false; - if (Flags is not null && other.Flags is not null) { - return Flags.Equals (other.Flags); - } - return false; + if (NativePrefix != other.NativePrefix) + return false; + if (NativeSuffix != other.NativeSuffix) + return false; + if (Library != other.Library) + return false; + return (Flags, other.Flags) switch { + (null, null) => true, + (null, _) => false, + (_, null) => false, + (_, _) => Flags!.Equals (other.Flags) + }; } /// @@ -155,6 +212,21 @@ public override int GetHashCode () /// public override string ToString () { - return $"{{ Type: '{typeof (T).FullName}', Selector: '{Selector ?? "null"}', ArgumentSemantic: '{ArgumentSemantic}', Flags: '{Flags}' }}"; + var sb = new StringBuilder ("{ Type: '"); + sb.Append (typeof (T).FullName); + sb.Append ("', Selector: '"); + sb.Append (Selector ?? "null"); + sb.Append ("', ArgumentSemantic: '"); + sb.Append (ArgumentSemantic); + sb.Append ("', Flags: '"); + sb.Append (Flags); + sb.Append ("', NativePrefix: '"); + sb.Append (NativePrefix ?? "null"); + sb.Append ("', NativeSuffix: '"); + sb.Append (NativeSuffix ?? "null"); + sb.Append ("', Library: '"); + sb.Append (Library ?? "null"); + sb.Append ("' }"); + return sb.ToString (); } } diff --git a/src/rgen/Microsoft.Macios.Generator/Attributes/FieldData.cs b/src/rgen/Microsoft.Macios.Generator/Attributes/FieldData.cs index d9200c7e8ee8..7b5b10fe116c 100644 --- a/src/rgen/Microsoft.Macios.Generator/Attributes/FieldData.cs +++ b/src/rgen/Microsoft.Macios.Generator/Attributes/FieldData.cs @@ -137,6 +137,6 @@ public override int GetHashCode () /// public override string ToString () { - return $"{{ SymbolName: '{SymbolName}' LibraryName: '{LibraryName ?? "null"}', Flags: '{Flags}' }}"; + return $"{{ SymbolName: '{SymbolName}', LibraryName: '{LibraryName ?? "null"}', Flags: '{Flags}' }}"; } } diff --git a/src/rgen/Microsoft.Macios.Generator/Attributes/MarshalDirective.cs b/src/rgen/Microsoft.Macios.Generator/Attributes/MarshalDirective.cs new file mode 100644 index 000000000000..a4dbfdbc47f7 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Attributes/MarshalDirective.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace Microsoft.Macios.Generator.Attributes; + +record CustomMarshalDirective (string? NativePrefix, string? NativeSuffix, string? Library); + +static class ExportDataExtensions { + + public static bool ShouldMarshalNativeExceptions (this ExportData self) where T : Enum + => self switch { + ExportData property => property.Flags.HasFlag (ObjCBindings.Property + .CustomMarshalDirective), + ExportData method => method.Flags.HasFlag ( + ObjCBindings.Property.CustomMarshalDirective), + _ => false, + }; + + public static CustomMarshalDirective? ToCustomMarshalDirective (this ExportData self) where T : Enum + { + var present = self switch { + ExportData property => property.Flags.HasFlag (ObjCBindings.Property + .CustomMarshalDirective), + ExportData method => method.Flags.HasFlag ( + ObjCBindings.Property.CustomMarshalDirective), + _ => false, + }; + if (present) { + return new (self.NativePrefix, self.NativeSuffix, self.Library); + } + + return null; + } + +} diff --git a/src/rgen/Microsoft.Macios.Generator/Attributes/SupportedOSPlatformData.cs b/src/rgen/Microsoft.Macios.Generator/Attributes/SupportedOSPlatformData.cs index 35d0a168b6e2..df1897f04a3c 100644 --- a/src/rgen/Microsoft.Macios.Generator/Attributes/SupportedOSPlatformData.cs +++ b/src/rgen/Microsoft.Macios.Generator/Attributes/SupportedOSPlatformData.cs @@ -28,6 +28,12 @@ internal SupportedOSPlatformData (string platformName) (Platform, Version) = platformName.GetPlatformAndVersion (); } + internal SupportedOSPlatformData (ApplePlatform platform, Version version) + { + Platform = platform; + Version = version; + } + /// /// Try to parse the attribute data to retrieve the information of an SupportedOSPlatformAttribute. /// diff --git a/src/rgen/Microsoft.Macios.Generator/Attributes/UnsupportedOSPlatformData.cs b/src/rgen/Microsoft.Macios.Generator/Attributes/UnsupportedOSPlatformData.cs index cdf39b7b59a8..72b2ca9ea549 100644 --- a/src/rgen/Microsoft.Macios.Generator/Attributes/UnsupportedOSPlatformData.cs +++ b/src/rgen/Microsoft.Macios.Generator/Attributes/UnsupportedOSPlatformData.cs @@ -34,6 +34,12 @@ internal UnsupportedOSPlatformData (string platformName) (Platform, Version) = platformName.GetPlatformAndVersion (); } + internal UnsupportedOSPlatformData (ApplePlatform platform) + { + Platform = platform; + Version = new Version (); + } + internal UnsupportedOSPlatformData (string platformName, string? message = null) : this (platformName) { Message = message; diff --git a/src/rgen/Microsoft.Macios.Generator/AttributesNames.cs b/src/rgen/Microsoft.Macios.Generator/AttributesNames.cs index f7c9f4bc3dc2..a5d3f01935ed 100644 --- a/src/rgen/Microsoft.Macios.Generator/AttributesNames.cs +++ b/src/rgen/Microsoft.Macios.Generator/AttributesNames.cs @@ -12,6 +12,8 @@ static class AttributesNames { public const string BindingAttribute = "ObjCBindings.BindingTypeAttribute"; public const string BindingCategoryAttribute = "ObjCBindings.BindingTypeAttribute"; public const string BindingClassAttribute = "ObjCBindings.BindingTypeAttribute"; + public const string BindingCoreImageFilterAttribute = "ObjCBindings.BindingTypeAttribute"; + public const string BindFromAttribute = "ObjCBindings.BindFromAttribute"; public const string BindingProtocolAttribute = "ObjCBindings.BindingTypeAttribute"; public const string BindingStrongDictionaryAttribute = "ObjCBindings.BindingTypeAttribute"; public const string FieldAttribute = "ObjCBindings.FieldAttribute"; @@ -22,6 +24,7 @@ static class AttributesNames { public const string SupportedOSPlatformAttribute = "System.Runtime.Versioning.SupportedOSPlatformAttribute"; public const string UnsupportedOSPlatformAttribute = "System.Runtime.Versioning.UnsupportedOSPlatformAttribute"; public const string ObsoletedOSPlatformAttribute = "System.Runtime.Versioning.ObsoletedOSPlatformAttribute"; + public const string NativeEnumAttribute = "ObjCRuntime.NativeAttribute"; public static readonly string [] BindingTypes = [ BindingAttribute, @@ -29,6 +32,7 @@ static class AttributesNames { BindingClassAttribute, BindingProtocolAttribute, BindingStrongDictionaryAttribute, + BindingCoreImageFilterAttribute, ]; diff --git a/src/rgen/Microsoft.Macios.Generator/Availability/AvailabilityTrivia.cs b/src/rgen/Microsoft.Macios.Generator/Availability/AvailabilityTrivia.cs new file mode 100644 index 000000000000..ce8c43729e33 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Availability/AvailabilityTrivia.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using Microsoft.Macios.Generator.Extensions; +using Xamarin.Utils; + +namespace Microsoft.Macios.Generator.Availability; + +readonly struct AvailabilityTrivia { + + /// + /// Retrieve the trivia to add before the symbol declaration. + /// + public string? Start { get; } + + /// + /// Retrieve the trivia to add after the symbol declaration. + /// + public string? End { get; } + + public AvailabilityTrivia (SymbolAvailability availability) + { + // trivia is calculated based on the availability of the symbol in each platform + // we will check each of the platforms and decide for the shorts #if possible + var supportedPlatforms = new HashSet (); + var unsupportedPlatforms = new HashSet (); + foreach (var platformAvailability in availability.PlatformAvailabilities) { + var platformDefine = platformAvailability.Platform.ToPlatformDefine (); + if (platformDefine is null) + continue; + + if (platformAvailability.IsSupported) + supportedPlatforms.Add (platformDefine); + else + unsupportedPlatforms.Add (platformDefine); + } + + // if all platforms are supported, we don't need any trivia + if (unsupportedPlatforms.Count == 0) { + // all platforms are supported + Start = null; + End = null; + return; + } + + if (supportedPlatforms.Count > unsupportedPlatforms.Count) { + // we have more supported platforms than unsupported ones + // we will use #if to exclude the unsupported platforms + Start = $"#if !{string.Join (" && !", unsupportedPlatforms)}"; + End = "#endif"; + } else { + // we have more unsupported platforms than supported ones + // we will use #if to include the supported platforms + Start = $"#if {string.Join (" || ", supportedPlatforms)}"; + End = "#endif"; + } + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/Availability/PlatformAvailability.cs b/src/rgen/Microsoft.Macios.Generator/Availability/PlatformAvailability.cs index ba83bb51bed1..798d932436c5 100644 --- a/src/rgen/Microsoft.Macios.Generator/Availability/PlatformAvailability.cs +++ b/src/rgen/Microsoft.Macios.Generator/Availability/PlatformAvailability.cs @@ -36,14 +36,26 @@ namespace Microsoft.Macios.Generator.Availability; /// /// Dictionary that contains all the obsoleted versions and their optional data. /// - public readonly IReadOnlyDictionary UnsupportedVersions => unsupported; + public IReadOnlyDictionary UnsupportedVersions => unsupported; readonly SortedDictionary obsoleted = new (); /// /// The Dictionary which contains all the unsupported versions and their optional data. /// - public readonly IReadOnlyDictionary ObsoletedVersions => obsoleted; + public IReadOnlyDictionary ObsoletedVersions => obsoleted; + + /// + /// Return if the platform is supported. + /// + public bool IsSupported { + get { + // a platform is supported if: + // 1. The supported version is not null, either the default version or a specific one + // 2. The default version is not in the unsupported list + return SupportedVersion is not null && !unsupported.ContainsKey (defaultVersion); + } + } /// @@ -53,6 +65,7 @@ namespace Microsoft.Macios.Generator.Availability; /// True if the version is default. public static bool IsDefaultVersion (Version version) => version == defaultVersion; + PlatformAvailability (ApplePlatform platform, Version? supportedVersion, SortedDictionary unsupportedVersions, SortedDictionary obsoletedVersions) @@ -137,6 +150,7 @@ public bool Equals (PlatformAvailability other) var obsoleteComparer = new DictionaryComparer (); var unsupportedComparer = new DictionaryComparer (); + var x = Equals (SupportedVersion, other.SupportedVersion); return Platform == other.Platform && Equals (SupportedVersion, other.SupportedVersion) && unsupportedComparer.Equals (unsupported, other.unsupported) && diff --git a/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailability.cs b/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailability.cs index 29c3ab988327..da7983a06f52 100644 --- a/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailability.cs +++ b/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailability.cs @@ -33,6 +33,19 @@ public SymbolAvailability () { } } } + /// + /// Return the symbol trivia if it has any. + /// + public AvailabilityTrivia? Trivia { + get { + // just returns the trivia if it has any, null otherwise + var trivia = new AvailabilityTrivia (this); + if (trivia.Start is not null || trivia.End is not null) + return trivia; + return null; + } + } + /// /// Copy constructor. /// diff --git a/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailabilityBuilder.cs b/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailabilityBuilder.cs index c606e858c0e2..bc73eaba8a95 100644 --- a/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailabilityBuilder.cs +++ b/src/rgen/Microsoft.Macios.Generator/Availability/SymbolAvailabilityBuilder.cs @@ -22,6 +22,18 @@ public sealed class Builder { internal Builder () { } + /// + /// Return the immutable version of the current data in the builder. + /// + public IEnumerable PlatformAvailabilities { + get { + // return the immutable version of the builder data + foreach (var availability in platforms.Values) { + yield return availability.ToImmutable (); + } + } + } + /// /// Returns the PlatformAvailability for the given platform. If we did not have a builder for the /// platform, a new one is created and added to the dictionary. diff --git a/src/rgen/Microsoft.Macios.Generator/BindingSourceGeneratorGenerator.cs b/src/rgen/Microsoft.Macios.Generator/BindingSourceGeneratorGenerator.cs index eb0d8fd66892..bea3298057a1 100644 --- a/src/rgen/Microsoft.Macios.Generator/BindingSourceGeneratorGenerator.cs +++ b/src/rgen/Microsoft.Macios.Generator/BindingSourceGeneratorGenerator.cs @@ -13,6 +13,7 @@ using Microsoft.Macios.Generator.DataModel; using Microsoft.Macios.Generator.Emitters; using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Generator.IO; namespace Microsoft.Macios.Generator; @@ -24,7 +25,7 @@ namespace Microsoft.Macios.Generator; /// [Generator] public class BindingSourceGeneratorGenerator : IIncrementalGenerator { - static readonly CodeChangesEqualityComparer equalityComparer = new (); + static readonly BindingEqualityComparer equalityComparer = new (); /// public void Initialize (IncrementalGeneratorInitializationContext context) @@ -45,16 +46,16 @@ public void Initialize (IncrementalGeneratorInitializationContext context) static (ctx, _) => GetChangesForSourceGen (ctx)) .Where (tuple => tuple.BindingAttributeFound); - var codeChanges = provider - .Select (static (tuple, _) => tuple.Changes) + var bindings = provider + .Select (static (tuple, _) => tuple.Bindings) .WithComparer (equalityComparer); // ideally we could do a distinct, because each code change can return the same libs, this makes the library // generation more common than what we would like, but it is the smallest code generation. var libraryProvider = provider - .Select ((tuple, _) => (tuple.RootBindingContext, tuple.Changes.LibraryPaths)); + .Select ((tuple, _) => (tuple.RootBindingContext, tuple.Bindings.LibraryPaths)); - context.RegisterSourceOutput (context.CompilationProvider.Combine (codeChanges.Collect ()), + context.RegisterSourceOutput (context.CompilationProvider.Combine (bindings.Collect ()), ((ctx, t) => GenerateCode (ctx, t.Right))); context.RegisterSourceOutput (context.CompilationProvider.Combine (libraryProvider.Collect ()), @@ -71,9 +72,9 @@ public void Initialize (IncrementalGeneratorInitializationContext context) _ => false, }; - static (RootBindingContext RootBindingContext, CodeChanges Changes, bool BindingAttributeFound) GetChangesForSourceGen (GeneratorSyntaxContext context) + static (RootContext RootBindingContext, Binding Bindings, bool BindingAttributeFound) GetChangesForSourceGen (GeneratorSyntaxContext context) { - var bindingContext = new RootBindingContext (context.SemanticModel); + var bindingContext = new RootContext (context.SemanticModel); // we do know that the context node has to be one of the base type declarations var declarationSyntax = Unsafe.As (context.Node); @@ -85,14 +86,14 @@ public void Initialize (IncrementalGeneratorInitializationContext context) return (bindingContext, default, false); } - var codeChanges = CodeChanges.FromDeclaration (declarationSyntax, bindingContext); + var binding = Binding.FromDeclaration (declarationSyntax, bindingContext); // if code changes are null, return the default value and a false to later ignore the change - return codeChanges is not null - ? (bindingContext, codeChanges.Value, isBindingType) + return binding is not null + ? (bindingContext, binding.Value, isBindingType) : (bindingContext, default, false); } - static void GenerateCode (SourceProductionContext context, in ImmutableArray changesList) + static void GenerateCode (SourceProductionContext context, in ImmutableArray bindingsList) { // The process is as follows, get all the changes we have received from the incremental generator, // loop over them, and based on the CodeChange.BindingType we are going to build the symbol context @@ -101,20 +102,20 @@ static void GenerateCode (SourceProductionContext context, in ImmutableArraySource production context. /// The root context of the current generation. static void GenerateLibraryCode (SourceProductionContext context, - ImmutableArray<(RootBindingContext RootBindingContext, IEnumerable<(string LibraryName, string? LibraryPath)> LibraryPaths)> libraryChanges) + ImmutableArray<(RootContext RootBindingContext, IEnumerable<(string LibraryName, string? LibraryPath)> LibraryPaths)> libraryChanges) { if (libraryChanges.Length == 0) return; @@ -161,7 +162,7 @@ static void GenerateLibraryCode (SourceProductionContext context, if (emitter.TryEmit (distinctLibraryPaths, out var diagnostics)) { // only add a file when we do generate code - var code = sb.ToString (); + var code = sb.ToCode (); context.AddSource ($"{Path.Combine (emitter.SymbolNamespace, emitter.SymbolName)}.g.cs", SourceText.From (code, Encoding.UTF8)); } else { @@ -175,14 +176,14 @@ static void GenerateLibraryCode (SourceProductionContext context, /// that will be used to generate the code. This way we ensure that we have all the namespaces needed by the /// generated code. /// - /// The code changes for a given named type. + /// The code changes for a given named type. /// String builder that will be used for the generated code. /// The emitter that will generate the code. Provides any extra needed namespace. - static void CollectUsingStatements (in CodeChanges codeChanges, TabbedStringBuilder sb, ICodeEmitter emitter) + static void CollectUsingStatements (in Binding binding, TabbedStringBuilder sb, ICodeEmitter emitter) { // collect all using from the syntax tree, add them to a hash to make sure that we don't have duplicates // and add those usings that we do know we need for bindings. - var usingDirectivesToKeep = new SortedSet (codeChanges.UsingDirectives) { + var usingDirectivesToKeep = new SortedSet (binding.UsingDirectives) { // add the using statements that we know we need and print them to the sb }; @@ -195,7 +196,7 @@ static void CollectUsingStatements (in CodeChanges codeChanges, TabbedStringBuil foreach (var ns in usingDirectivesToKeep) { if (string.IsNullOrEmpty (ns)) continue; - sb.AppendLine ($"using {ns};"); + sb.WriteLine ($"using {ns};"); } } } diff --git a/src/rgen/Microsoft.Macios.Generator/Context/BindingContext.cs b/src/rgen/Microsoft.Macios.Generator/Context/BindingContext.cs index 5b5c03c1e378..c23601fff4aa 100644 --- a/src/rgen/Microsoft.Macios.Generator/Context/BindingContext.cs +++ b/src/rgen/Microsoft.Macios.Generator/Context/BindingContext.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Generator.IO; namespace Microsoft.Macios.Generator.Context; @@ -14,9 +15,9 @@ readonly struct BindingContext { /// /// Current code changes for the binding context. /// - public CodeChanges Changes { get; } + public Binding Changes { get; } - public BindingContext (TabbedStringBuilder builder, CodeChanges changes) + public BindingContext (TabbedStringBuilder builder, Binding changes) { Builder = builder; Changes = changes; diff --git a/src/rgen/Microsoft.Macios.Generator/Context/RootBindingContext.cs b/src/rgen/Microsoft.Macios.Generator/Context/RootContext.cs similarity index 87% rename from src/rgen/Microsoft.Macios.Generator/Context/RootBindingContext.cs rename to src/rgen/Microsoft.Macios.Generator/Context/RootContext.cs index 788b06f42b5f..bee0555df16c 100644 --- a/src/rgen/Microsoft.Macios.Generator/Context/RootBindingContext.cs +++ b/src/rgen/Microsoft.Macios.Generator/Context/RootContext.cs @@ -17,14 +17,29 @@ namespace Microsoft.Macios.Generator.Context; /// The class also provides a number or properties that will allow to determine the platform we are binding and access /// to the current compilation. /// -class RootBindingContext { +class RootContext { + + /// + /// The platform of the current compilation. + /// public PlatformName CurrentPlatform { get; set; } + + /// + /// Current compilation. + /// public Compilation Compilation => this.SemanticModel.Compilation; + + /// + /// Current semantic model. + /// public SemanticModel SemanticModel { get; set; } + /// + /// A dictionary that contains the libraries that are being used in the current binding. + /// public Dictionary Libraries { get; } = new (); - public RootBindingContext (SemanticModel semanticModel) + public RootContext (SemanticModel semanticModel) { SemanticModel = semanticModel; CurrentPlatform = Compilation.GetCurrentPlatform (); @@ -91,6 +106,10 @@ static bool IsLibraryName (string libraryName, string variableName) => // has to end with the word library && libraryName.EndsWith ("Library", StringComparison.Ordinal); + /// + /// Return the Constants type from the ObjCRuntime namespace. + /// + /// INamedTypeSymbol GetObjCConstants () => Compilation.GetTypeByMetadataName ("ObjCRuntime.Constants")!; /// @@ -107,5 +126,5 @@ public bool IsSystemLibrary (string name) .Any (s => IsLibraryName (s, name)); } - public static implicit operator RootBindingContext (SemanticModel semanticModel) => new (semanticModel); + public static implicit operator RootContext (SemanticModel semanticModel) => new (semanticModel); } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.Generator.cs new file mode 100644 index 000000000000..4e3002f50ae0 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.Generator.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Accessor { + + /// + /// The data of the field attribute used to mark the value as a property binding. + /// + public ExportData? ExportPropertyData { get; init; } + + /// + /// State if we should marshal native exceptions when generating the accessor. + /// + public bool MarshalNativeExceptions + => ExportPropertyData is not null && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.MarshalNativeExceptions); + + /// + /// Create a new code change in a property accessor. + /// + /// The kind of accessor. + /// The os availability of the symbol. + /// The data of the export attribute found in the accessor. + /// The list of attributes attached to the accessor. + /// The list of visibility modifiers of the accessor. + public Accessor (AccessorKind accessorKind, + SymbolAvailability symbolAvailability, + ExportData? exportPropertyData, + ImmutableArray attributes, + ImmutableArray modifiers) + { + Kind = accessorKind; + SymbolAvailability = symbolAvailability; + ExportPropertyData = exportPropertyData; + Attributes = attributes; + Modifiers = modifiers; + } + + /// + /// Retrieve the selector to be used with the associated property. + /// + /// The property associated with the accessor. + /// The selector to use for the accessor. + public string? GetSelector (in Property associatedProperty) + { + // this is not a property but a field, we cannot retrieve a selector. + if (!associatedProperty.IsProperty) + return null; + + // There are two possible cases, the current accessor has an export attribute, if that + // is the case, we will use the selector in that attribute. Otherwise, we have: + // + // * getter: return the property selector. + // * setter: use the registrar code (it has the right logic) to get the setter. + if (ExportPropertyData is null) { + return Kind == AccessorKind.Getter + ? associatedProperty.ExportPropertyData.Value.Selector + : Registrar.Registrar.CreateSetterSelector (associatedProperty.ExportPropertyData.Value.Selector); + } + + return ExportPropertyData.Value.Selector; + } + + /// + /// Returns if the accessor should marshal native exceptions with the associated property. + /// + /// The property associated with the accessor. + /// True if either the accessor or the property were marked with the MarshalNativeExceptions flag. + public bool ShouldMarshalNativeExceptions (in Property property) + => MarshalNativeExceptions || property.MarshalNativeExceptions; + + /// + public override string ToString () + { + var sb = new StringBuilder ($"{{ Kind: {Kind}, "); + sb.Append ($"Supported Platforms: {SymbolAvailability}, "); + sb.Append ($"ExportData: {ExportPropertyData?.ToString () ?? "null"} Modifiers: ["); + sb.AppendJoin (",", Modifiers.Select (x => x.Text)); + sb.Append ("], Attributes: ["); + sb.AppendJoin (", ", Attributes); + sb.Append ("] }"); + return sb.ToString (); + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.cs index 989f33a23562..2fb8e0154a22 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Accessor.cs @@ -3,14 +3,15 @@ using System; using System.Collections.Immutable; using System.Linq; +using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; -using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; namespace Microsoft.Macios.Generator.DataModel; -readonly struct Accessor : IEquatable { +[StructLayout (LayoutKind.Auto)] +readonly partial struct Accessor : IEquatable { /// /// The kind of accessor. /// @@ -21,42 +22,16 @@ namespace Microsoft.Macios.Generator.DataModel; /// public SymbolAvailability SymbolAvailability { get; } - /// - /// The data of the field attribute used to mark the value as a property binding. - /// - public ExportData? ExportPropertyData { get; init; } - /// /// List of attribute code changes of the accessor. /// - public ImmutableArray Attributes { get; } + public ImmutableArray Attributes { get; } = []; /// /// List of modifiers of the accessor. /// public ImmutableArray Modifiers { get; } - /// - /// Create a new code change in a property accessor. - /// - /// The kind of accessor. - /// The os availability of the symbol. - /// The data of the export attribute found in the accessor. - /// The list of attributes attached to the accessor. - /// The list of visibility modifiers of the accessor. - public Accessor (AccessorKind accessorKind, - SymbolAvailability symbolAvailability, - ExportData? exportPropertyData, - ImmutableArray attributes, - ImmutableArray modifiers) - { - Kind = accessorKind; - SymbolAvailability = symbolAvailability; - ExportPropertyData = exportPropertyData; - Attributes = attributes; - Modifiers = modifiers; - } - /// public bool Equals (Accessor other) { @@ -95,15 +70,4 @@ public override int GetHashCode () { return !left.Equals (right); } - - /// - public override string ToString () - { - var sb = new StringBuilder ($"{{ Kind: {Kind}, Supported Platforms: {SymbolAvailability}, ExportData: {ExportPropertyData?.ToString () ?? "null"} Modifiers: ["); - sb.AppendJoin (",", Modifiers.Select (x => x.Text)); - sb.Append ("], Attributes: ["); - sb.AppendJoin (", ", Attributes); - sb.Append ("] }"); - return sb.ToString (); - } } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/AttributeCodeChange.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/AttributeCodeChange.cs index b58abbf18bf4..356177be96b8 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/AttributeCodeChange.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/AttributeCodeChange.cs @@ -93,6 +93,7 @@ public static ImmutableArray From (SyntaxList (); foreach (AttributeListSyntax attributeListSyntax in attributes) { foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) { + var x = semanticModel.GetSymbolInfo (attributeSyntax); if (semanticModel.GetSymbolInfo (attributeSyntax).Symbol is not IMethodSymbol attributeSymbol) continue; // if we can't get the symbol, ignore it var name = attributeSymbol.ContainingType.ToDisplayString (); diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/CodeChanges.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.Generator.cs similarity index 65% rename from src/rgen/Microsoft.Macios.Generator/DataModel/CodeChanges.cs rename to src/rgen/Microsoft.Macios.Generator/DataModel/Binding.Generator.cs index c5a52c1fad2a..5f7de2c40ec4 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/CodeChanges.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.Generator.cs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -14,11 +14,8 @@ namespace Microsoft.Macios.Generator.DataModel; -/// -/// Structure that represents a set of changes that were made by the user that need to be applied to the -/// generated code. -/// -readonly struct CodeChanges { +readonly partial struct Binding { + /// /// Represents the type of binding that the code changes are for. /// @@ -30,142 +27,10 @@ readonly struct CodeChanges { /// public BindingInfo BindingInfo => bindingInfo; - readonly string name = string.Empty; - /// - /// The name of the named type that generated the code change. - /// - public string Name => name; - - readonly ImmutableArray namespaces = ImmutableArray.Empty; - /// - /// The namespace that contains the named type that generated the code change. - /// - public ImmutableArray Namespace => namespaces; - - readonly ImmutableArray interfaces = ImmutableArray.Empty; - /// - /// The list of interfaces implemented by the class/interface. - /// - public ImmutableArray Interfaces { - get => interfaces; - init => interfaces = value; - } - - /// - /// Fully qualified name of the symbol that the code changes are for. - /// - public string FullyQualifiedSymbol { get; } - - readonly string? baseClass = null; - - /// - /// The fully qualified name of an interface/class base. - /// - public string? Base { - get => baseClass; - init => baseClass = value; - - } - - readonly SymbolAvailability availability = new (); - /// - /// The platform availability of the named type. - /// - public SymbolAvailability SymbolAvailability => availability; - - /// - /// Changes to the attributes of the symbol. - /// - public ImmutableArray Attributes { get; init; } = []; - - readonly IReadOnlySet usingDirectives = ImmutableHashSet.Empty; - - /// - /// The using directive added in the named type declaration. - /// - public IReadOnlySet UsingDirectives { - get => usingDirectives; - init => usingDirectives = value; - } - /// - /// True if the code changes are for a static symbol. + /// Returns if the binding has been declared to be thread safe. /// - public bool IsStatic { get; private init; } - - /// - /// True if the code changes are for a partial symbol. - /// - public bool IsPartial { get; private init; } - - /// - /// True if the code changes are for an abstract symbol. - /// - public bool IsAbstract { get; private init; } - - readonly ImmutableArray modifiers = []; - /// - /// Modifiers list. - /// - public ImmutableArray Modifiers { - get => modifiers; - init { - modifiers = value; - IsStatic = value.Any (m => m.IsKind (SyntaxKind.StaticKeyword)); - IsPartial = value.Any (m => m.IsKind (SyntaxKind.PartialKeyword)); - IsAbstract = value.Any (m => m.IsKind (SyntaxKind.AbstractKeyword)); - } - } - - readonly ImmutableArray enumMembers = []; - - /// - /// Changes to the enum members of the symbol. - /// - public ImmutableArray EnumMembers { - get => enumMembers; - init => enumMembers = value; - } - - readonly ImmutableArray properties = []; - - /// - /// Changes to the properties of the symbol. - /// - public ImmutableArray Properties { - get => properties; - init => properties = value; - } - - readonly ImmutableArray constructors = []; - - /// - /// Changes to the constructors of the symbol. - /// - public ImmutableArray Constructors { - get => constructors; - init => constructors = value; - } - - readonly ImmutableArray events = []; - - /// - /// Changes to the events of the symbol. - /// - public ImmutableArray Events { - get => events; - init => events = value; - } - - readonly ImmutableArray methods = []; - - /// - /// Changes to the methods of a symbol. - /// - public ImmutableArray Methods { - get => methods; - init => methods = value; - } + public bool IsThreadSafe => bindingInfo.IsThreadSafe; /// /// Returns all the library names and paths that are needed by the native code represented by the code change. @@ -256,12 +121,12 @@ internal static bool Skip (MethodDeclarationSyntax methodDeclarationSyntax, Sema delegate bool SkipDelegate (T declarationSyntax, SemanticModel semanticModel); - delegate bool TryCreateDelegate (T declaration, RootBindingContext context, + delegate bool TryCreateDelegate (T declaration, RootContext context, [NotNullWhen (true)] out TR? change) where T : MemberDeclarationSyntax where TR : struct; - static void GetMembers (TypeDeclarationSyntax baseDeclarationSyntax, RootBindingContext context, + static void GetMembers (TypeDeclarationSyntax baseDeclarationSyntax, RootContext context, SkipDelegate skip, TryCreateDelegate tryCreate, out ImmutableArray members) where T : MemberDeclarationSyntax where TR : struct @@ -286,7 +151,7 @@ static void GetMembers (TypeDeclarationSyntax baseDeclarationSyntax, Root /// The namespace that contains the named type. /// The fully qualified name of the symbol. /// The platform availability of the named symbol. - internal CodeChanges (BindingInfo bindingInfo, string name, ImmutableArray @namespace, + internal Binding (BindingInfo bindingInfo, string name, ImmutableArray @namespace, string fullyQualifiedSymbol, SymbolAvailability symbolAvailability) { this.bindingInfo = bindingInfo; @@ -297,11 +162,11 @@ internal CodeChanges (BindingInfo bindingInfo, string name, ImmutableArray - /// Creates a new instance of the struct for a given enum declaration. + /// Creates a new instance of the struct for a given enum declaration. /// /// The enum declaration that triggered the change. /// The root binding context of the current compilation. - CodeChanges (EnumDeclarationSyntax enumDeclaration, RootBindingContext context) + Binding (EnumDeclarationSyntax enumDeclaration, RootContext context) { context.SemanticModel.GetSymbolData ( declaration: enumDeclaration, @@ -347,11 +212,11 @@ internal CodeChanges (BindingInfo bindingInfo, string name, ImmutableArray - /// Creates a new instance of the struct for a given class declaration. + /// Creates a new instance of the struct for a given class declaration. /// /// The class declaration that triggered the change. /// The root binding context of the current compilation. - CodeChanges (ClassDeclarationSyntax classDeclaration, RootBindingContext context) + Binding (ClassDeclarationSyntax classDeclaration, RootContext context) { context.SemanticModel.GetSymbolData ( declaration: classDeclaration, @@ -379,11 +244,11 @@ internal CodeChanges (BindingInfo bindingInfo, string name, ImmutableArray - /// Creates a new instance of the struct for a given interface declaration. + /// Creates a new instance of the struct for a given interface declaration. /// /// The interface declaration that triggered the change. /// The root binding context of the current compilation. - CodeChanges (InterfaceDeclarationSyntax interfaceDeclaration, RootBindingContext context) + Binding (InterfaceDeclarationSyntax interfaceDeclaration, RootContext context) { context.SemanticModel.GetSymbolData ( declaration: interfaceDeclaration, @@ -415,42 +280,13 @@ internal CodeChanges (BindingInfo bindingInfo, string name, ImmutableArrayThe declaration syntax whose change we want to calculate. /// The root binding context of the current compilation. /// A code change or null if it could not be calculated. - public static CodeChanges? FromDeclaration (BaseTypeDeclarationSyntax baseTypeDeclarationSyntax, - RootBindingContext context) + public static Binding? FromDeclaration (BaseTypeDeclarationSyntax baseTypeDeclarationSyntax, + RootContext context) => baseTypeDeclarationSyntax switch { - EnumDeclarationSyntax enumDeclarationSyntax => new CodeChanges (enumDeclarationSyntax, context), - InterfaceDeclarationSyntax interfaceDeclarationSyntax => new CodeChanges (interfaceDeclarationSyntax, + EnumDeclarationSyntax enumDeclarationSyntax => new Binding (enumDeclarationSyntax, context), + InterfaceDeclarationSyntax interfaceDeclarationSyntax => new Binding (interfaceDeclarationSyntax, context), - ClassDeclarationSyntax classDeclarationSyntax => new CodeChanges (classDeclarationSyntax, context), + ClassDeclarationSyntax classDeclarationSyntax => new Binding (classDeclarationSyntax, context), _ => null }; - - /// - public override string ToString () - { - var sb = new StringBuilder ("Changes: {"); - sb.Append ($"BindingData: '{BindingInfo}', Name: '{Name}', Namespace: ["); - sb.AppendJoin (", ", Namespace); - sb.Append ($"], FullyQualifiedSymbol: '{FullyQualifiedSymbol}', Base: '{Base ?? "null"}', SymbolAvailability: {SymbolAvailability}, "); - sb.Append ("Interfaces: ["); - sb.AppendJoin (", ", Interfaces); - sb.Append ("], Attributes: ["); - sb.AppendJoin (", ", Attributes); - sb.Append ("], UsingDirectives: ["); - sb.AppendJoin (", ", UsingDirectives); - sb.Append ("], Modifiers: ["); - sb.AppendJoin (", ", Modifiers); - sb.Append ("], EnumMembers: ["); - sb.AppendJoin (", ", EnumMembers); - sb.Append ("], Constructors: ["); - sb.AppendJoin (", ", Constructors); - sb.Append ("], Properties: ["); - sb.AppendJoin (", ", Properties); - sb.Append ("], Methods: ["); - sb.AppendJoin (", ", Methods); - sb.Append ("], Events: ["); - sb.AppendJoin (", ", Events); - sb.Append ("] }"); - return sb.ToString (); - } } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs new file mode 100644 index 000000000000..a9004343b224 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.Macios.Generator.Availability; + +namespace Microsoft.Macios.Generator.DataModel; + +/// +/// Structure that represents a set of changes that were made by the user that need to be applied to the +/// generated code. +/// +[StructLayout (LayoutKind.Auto)] +readonly partial struct Binding { + + readonly string name = string.Empty; + /// + /// The name of the named type that generated the code change. + /// + public string Name => name; + + readonly ImmutableArray namespaces = ImmutableArray.Empty; + /// + /// The namespace that contains the named type that generated the code change. + /// + public ImmutableArray Namespace => namespaces; + + readonly ImmutableArray interfaces = ImmutableArray.Empty; + /// + /// The list of interfaces implemented by the class/interface. + /// + public ImmutableArray Interfaces { + get => interfaces; + init => interfaces = value; + } + + /// + /// Fully qualified name of the symbol that the code changes are for. + /// + public string FullyQualifiedSymbol { get; } + + readonly string? baseClass = null; + + /// + /// The fully qualified name of an interface/class base. + /// + public string? Base { + get => baseClass; + init => baseClass = value; + + } + + readonly SymbolAvailability availability = new (); + /// + /// The platform availability of the named type. + /// + public SymbolAvailability SymbolAvailability => availability; + + /// + /// Changes to the attributes of the symbol. + /// + public ImmutableArray Attributes { get; init; } = []; + + readonly IReadOnlySet usingDirectives = ImmutableHashSet.Empty; + + /// + /// The using directive added in the named type declaration. + /// + public IReadOnlySet UsingDirectives { + get => usingDirectives; + init => usingDirectives = value; + } + + /// + /// True if the code changes are for a static symbol. + /// + public bool IsStatic { get; private init; } + + /// + /// True if the code changes are for a partial symbol. + /// + public bool IsPartial { get; private init; } + + /// + /// True if the code changes are for an abstract symbol. + /// + public bool IsAbstract { get; private init; } + + readonly ImmutableArray modifiers = []; + /// + /// Modifiers list. + /// + public ImmutableArray Modifiers { + get => modifiers; + init { + modifiers = value; + IsStatic = value.Any (m => m.IsKind (SyntaxKind.StaticKeyword)); + IsPartial = value.Any (m => m.IsKind (SyntaxKind.PartialKeyword)); + IsAbstract = value.Any (m => m.IsKind (SyntaxKind.AbstractKeyword)); + } + } + + readonly ImmutableArray enumMembers = []; + + /// + /// Changes to the enum members of the symbol. + /// + public ImmutableArray EnumMembers { + get => enumMembers; + init => enumMembers = value; + } + + readonly ImmutableArray properties = []; + + /// + /// Changes to the properties of the symbol. + /// + public ImmutableArray Properties { + get => properties; + init => properties = value; + } + + readonly ImmutableArray constructors = []; + + /// + /// Changes to the constructors of the symbol. + /// + public ImmutableArray Constructors { + get => constructors; + init => constructors = value; + } + + readonly ImmutableArray events = []; + + /// + /// Changes to the events of the symbol. + /// + public ImmutableArray Events { + get => events; + init => events = value; + } + + readonly ImmutableArray methods = []; + + /// + /// Changes to the methods of a symbol. + /// + public ImmutableArray Methods { + get => methods; + init => methods = value; + } + + /// + public override string ToString () + { + var sb = new StringBuilder ("Changes: {"); + sb.Append ($"BindingData: '{BindingInfo}', Name: '{Name}', Namespace: ["); + sb.AppendJoin (", ", Namespace); + sb.Append ($"], FullyQualifiedSymbol: '{FullyQualifiedSymbol}', Base: '{Base ?? "null"}', SymbolAvailability: {SymbolAvailability}, "); + sb.Append ("Interfaces: ["); + sb.AppendJoin (", ", Interfaces); + sb.Append ("], Attributes: ["); + sb.AppendJoin (", ", Attributes); + sb.Append ("], UsingDirectives: ["); + sb.AppendJoin (", ", UsingDirectives); + sb.Append ("], Modifiers: ["); + sb.AppendJoin (", ", Modifiers); + sb.Append ("], EnumMembers: ["); + sb.AppendJoin (", ", EnumMembers); + sb.Append ("], Constructors: ["); + sb.AppendJoin (", ", Constructors); + sb.Append ("], Properties: ["); + sb.AppendJoin (", ", Properties); + sb.Append ("], Methods: ["); + sb.AppendJoin (", ", Methods); + sb.Append ("], Events: ["); + sb.AppendJoin (", ", Events); + sb.Append ("] }"); + return sb.ToString (); + } + +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/CodeChangesEqualityComparer.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/BindingEqualityComparer.cs similarity index 94% rename from src/rgen/Microsoft.Macios.Generator/DataModel/CodeChangesEqualityComparer.cs rename to src/rgen/Microsoft.Macios.Generator/DataModel/BindingEqualityComparer.cs index 8231c2c2436a..7e2cd6522c46 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/CodeChangesEqualityComparer.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/BindingEqualityComparer.cs @@ -8,9 +8,9 @@ namespace Microsoft.Macios.Generator.DataModel; /// /// Custom code changes comparer used for the Roslyn code generation to invalidate caching. /// -class CodeChangesEqualityComparer : EqualityComparer { +class BindingEqualityComparer : EqualityComparer { /// - public override bool Equals (CodeChanges x, CodeChanges y) + public override bool Equals (Binding x, Binding y) { // order does not matter in the using directives, use a comparer that sorts them @@ -82,7 +82,7 @@ public override bool Equals (CodeChanges x, CodeChanges y) } /// - public override int GetHashCode (CodeChanges obj) + public override int GetHashCode (Binding obj) { return HashCode.Combine (obj.FullyQualifiedSymbol, obj.EnumMembers); } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/BindingInfo.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/BindingInfo.cs index 7b82d096698c..d7f845a1a6a9 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/BindingInfo.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/BindingInfo.cs @@ -3,6 +3,7 @@ using System; using System.Runtime.InteropServices; using Microsoft.Macios.Generator.Attributes; +using ObjCBindings; namespace Microsoft.Macios.Generator.DataModel; @@ -20,6 +21,20 @@ namespace Microsoft.Macios.Generator.DataModel; public BindingType BindingType => bindingType; + /// + /// Returns if the binding has been declared to be thread safe. + /// + public bool IsThreadSafe { + get { + return bindingType switch { + BindingType.Category => categoryData.Flags.HasFlag (Category.IsThreadSafe), + BindingType.Class => classData.Flags.HasFlag (Class.IsThreadSafe), + BindingType.Protocol => protocolData.Flags.HasFlag (Protocol.IsThreadSafe), + _ => false + }; + } + } + public BindingInfo (BindingType type, BindingTypeData data) { bindingType = type; diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/BindingType.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/BindingType.cs index 200142a22090..a203f921e74b 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/BindingType.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/BindingType.cs @@ -12,9 +12,9 @@ enum BindingType : ulong { /// Unknown = 0, /// - /// Binding type for a enum with backing fields. + /// Binding type for an objc category. /// - SmartEnum, + Category, /// /// Binding type for an objc class. /// @@ -24,7 +24,12 @@ enum BindingType : ulong { /// Protocol, /// - /// Binding type for an objc category. + /// Binding type for a enum with backing fields. /// - Category, + SmartEnum, + /// + /// Binding type for a core image filter. + /// + CoreImageFilter, } + diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs new file mode 100644 index 000000000000..2ccc0206b43a --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.Extensions; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Constructor { + + public static bool TryCreate (ConstructorDeclarationSyntax declaration, RootContext context, + [NotNullWhen (true)] out Constructor? change) + { + if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IMethodSymbol constructor) { + change = null; + return false; + } + + var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); + var parametersBucket = ImmutableArray.CreateBuilder (); + // loop over the parameters of the construct since changes on those implies a change in the generated code + foreach (var parameter in constructor.Parameters) { + var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal]; + if (!Parameter.TryCreate (parameter, parameterDeclaration, context.SemanticModel, out var parameterChange)) + continue; + parametersBucket.Add (parameterChange.Value); + } + + change = new ( + type: constructor.ContainingSymbol.Name, // we DO NOT want the full name + symbolAvailability: constructor.GetSupportedPlatforms (), + attributes: attributes, + modifiers: [.. declaration.Modifiers], + parameters: parametersBucket.ToImmutable ()); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.cs index 57e9f19cb5e7..4124730f4d00 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.cs @@ -2,18 +2,16 @@ // Licensed under the MIT License. using System; using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.Availability; -using Microsoft.Macios.Generator.Context; -using Microsoft.Macios.Generator.Extensions; namespace Microsoft.Macios.Generator.DataModel; -readonly struct Constructor : IEquatable { +[StructLayout (LayoutKind.Auto)] +readonly partial struct Constructor : IEquatable { /// /// Type name that owns the constructor. /// @@ -52,33 +50,6 @@ public Constructor (string type, Parameters = parameters; } - public static bool TryCreate (ConstructorDeclarationSyntax declaration, RootBindingContext context, - [NotNullWhen (true)] out Constructor? change) - { - if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IMethodSymbol constructor) { - change = null; - return false; - } - - var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); - var parametersBucket = ImmutableArray.CreateBuilder (); - // loop over the parameters of the construct since changes on those implies a change in the generated code - foreach (var parameter in constructor.Parameters) { - var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal]; - if (!Parameter.TryCreate (parameter, parameterDeclaration, context.SemanticModel, out var parameterChange)) - continue; - parametersBucket.Add (parameterChange.Value); - } - - change = new ( - type: constructor.ContainingSymbol.Name, // we DO NOT want the full name - symbolAvailability: constructor.GetSupportedPlatforms (), - attributes: attributes, - modifiers: [.. declaration.Modifiers], - parameters: parametersBucket.ToImmutable ()); - return true; - } - /// public bool Equals (Constructor other) { diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.Generator.cs new file mode 100644 index 000000000000..7eff75208bf6 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.Generator.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using ObjCBindings; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct EnumMember { + + /// + /// The data of the field attribute used to mark the value as a binding. + /// + public FieldInfo? FieldInfo { get; } + + /// + /// Create a new change that happened on a member. + /// + /// The name of the changed member. + /// The library name of the smart enum. + /// The library path to the library, null if it is a known frameworl. + /// The binding data attached to this enum value. + /// The symbol availability of the member. + /// The list of attribute changes in the member. + public EnumMember (string name, + string libraryName, + string? libraryPath, + FieldData? fieldData, + SymbolAvailability symbolAvailability, + ImmutableArray attributes) + { + Name = name; + FieldInfo = fieldData is null ? null : new (fieldData.Value, libraryName, libraryPath); + SymbolAvailability = symbolAvailability; + Attributes = attributes; + } + + /// + /// Create a new change that happened on a member. + /// + /// The name of the changed member. + /// The library name of the smart enum. + /// The library path to the library, null if it is a known frameworl. + public EnumMember (string name, string libraryName, string? libraryPath) + : this ( + name: name, + libraryName: libraryName, + libraryPath: libraryPath, + fieldData: null, + symbolAvailability: new SymbolAvailability (), + attributes: ImmutableArray.Empty) + { + } + +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.cs index 003ac01b4a99..dc6f53c54bb0 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/EnumMember.cs @@ -2,6 +2,8 @@ // Licensed under the MIT License. using System; using System.Collections.Immutable; +using System.Reflection; +using System.Runtime.InteropServices; using System.Text; using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; @@ -13,7 +15,8 @@ namespace Microsoft.Macios.Generator.DataModel; /// Structure that represents a change that was made by the user on enum members that has to be /// reflected in the generated code. /// -readonly struct EnumMember : IEquatable { +[StructLayout (LayoutKind.Auto)] +readonly partial struct EnumMember : IEquatable { /// /// Get the name of the member. /// @@ -24,54 +27,10 @@ namespace Microsoft.Macios.Generator.DataModel; /// public SymbolAvailability SymbolAvailability { get; } - /// - /// The data of the field attribute used to mark the value as a binding. - /// - public FieldInfo? FieldInfo { get; } - /// /// Get the attributes added to the member. /// - public ImmutableArray Attributes { get; } - - /// - /// Create a new change that happened on a member. - /// - /// The name of the changed member. - /// The library name of the smart enum. - /// The library path to the library, null if it is a known frameworl. - /// The binding data attached to this enum value. - /// The symbol availability of the member. - /// The list of attribute changes in the member. - public EnumMember (string name, - string libraryName, - string? libraryPath, - FieldData? fieldData, - SymbolAvailability symbolAvailability, - ImmutableArray attributes) - { - Name = name; - FieldInfo = fieldData is null ? null : new (fieldData.Value, libraryName, libraryPath); - SymbolAvailability = symbolAvailability; - Attributes = attributes; - } - - /// - /// Create a new change that happened on a member. - /// - /// The name of the changed member. - /// The library name of the smart enum. - /// The library path to the library, null if it is a known frameworl. - public EnumMember (string name, string libraryName, string? libraryPath) - : this ( - name: name, - libraryName: libraryName, - libraryPath: libraryPath, - fieldData: null, - symbolAvailability: new SymbolAvailability (), - attributes: ImmutableArray.Empty) - { - } + public ImmutableArray Attributes { get; } = []; /// public bool Equals (EnumMember other) diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Event.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Event.Generator.cs new file mode 100644 index 000000000000..d7376c4fd769 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Event.Generator.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.Extensions; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Event { + + public static bool TryCreate (EventDeclarationSyntax declaration, RootContext context, + [NotNullWhen (true)] out Event? change) + { + var memberName = declaration.Identifier.ToFullString ().Trim (); + // get the symbol from the property declaration + if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IEventSymbol eventSymbol) { + change = null; + return false; + } + + var type = eventSymbol.Type.ToDisplayString ().Trim (); + var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); + ImmutableArray accessorCodeChanges = []; + if (declaration.AccessorList is not null && declaration.AccessorList.Accessors.Count > 0) { + // calculate any possible changes in the accessors of the property + var accessorsBucket = ImmutableArray.CreateBuilder (); + foreach (var accessorDeclaration in declaration.AccessorList.Accessors) { + if (context.SemanticModel.GetDeclaredSymbol (accessorDeclaration) is not ISymbol accessorSymbol) + continue; + var kind = accessorDeclaration.Kind ().ToAccessorKind (); + var accessorAttributeChanges = accessorDeclaration.GetAttributeCodeChanges (context.SemanticModel); + accessorsBucket.Add (new ( + accessorKind: kind, + symbolAvailability: accessorSymbol.GetSupportedPlatforms (), + exportPropertyData: null, + attributes: accessorAttributeChanges, + modifiers: [.. accessorDeclaration.Modifiers])); + } + + accessorCodeChanges = accessorsBucket.ToImmutable (); + } + + change = new (memberName, type, eventSymbol.GetSupportedPlatforms (), attributes, + [.. declaration.Modifiers], accessorCodeChanges); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Event.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Event.cs index 38f7e5e10b85..3b53660c7a35 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Event.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Event.cs @@ -2,18 +2,14 @@ // Licensed under the MIT License. using System; using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.Availability; -using Microsoft.Macios.Generator.Context; -using Microsoft.Macios.Generator.Extensions; namespace Microsoft.Macios.Generator.DataModel; -readonly struct Event : IEquatable { +readonly partial struct Event : IEquatable { /// /// Name of the property. /// @@ -101,43 +97,6 @@ public override int GetHashCode () return !left.Equals (right); } - public static bool TryCreate (EventDeclarationSyntax declaration, RootBindingContext context, - [NotNullWhen (true)] out Event? change) - { - var memberName = declaration.Identifier.ToFullString ().Trim (); - // get the symbol from the property declaration - if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IEventSymbol eventSymbol) { - change = null; - return false; - } - - var type = eventSymbol.Type.ToDisplayString ().Trim (); - var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); - ImmutableArray accessorCodeChanges = []; - if (declaration.AccessorList is not null && declaration.AccessorList.Accessors.Count > 0) { - // calculate any possible changes in the accessors of the property - var accessorsBucket = ImmutableArray.CreateBuilder (); - foreach (var accessorDeclaration in declaration.AccessorList.Accessors) { - if (context.SemanticModel.GetDeclaredSymbol (accessorDeclaration) is not ISymbol accessorSymbol) - continue; - var kind = accessorDeclaration.Kind ().ToAccessorKind (); - var accessorAttributeChanges = accessorDeclaration.GetAttributeCodeChanges (context.SemanticModel); - accessorsBucket.Add (new ( - accessorKind: kind, - symbolAvailability: accessorSymbol.GetSupportedPlatforms (), - exportPropertyData: null, - attributes: accessorAttributeChanges, - modifiers: [.. accessorDeclaration.Modifiers])); - } - - accessorCodeChanges = accessorsBucket.ToImmutable (); - } - - change = new (memberName, type, eventSymbol.GetSupportedPlatforms (), attributes, - [.. declaration.Modifiers], accessorCodeChanges); - return true; - } - /// public override string ToString () { diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs new file mode 100644 index 000000000000..b4294e925fe3 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.Extensions; +using ObjCRuntime; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Method { + + /// + /// The data of the export attribute used to mark the value as a property binding. + /// + public ExportData ExportMethodData { get; } + + /// + /// Returns the bind from data if present in the binding. + /// + public BindFromData? BindAs { get; init; } + + /// + /// Returns if the method was marked as thread safe. + /// + public bool IsThreadSafe => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.IsThreadSafe); + + /// + /// Return if the method invocation should be wrapped by a NSAutoReleasePool. + /// + public bool AutoRelease => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.AutoRelease); + + /// + /// True if the method was exported with the MarshalNativeExceptions flag allowing it to support native exceptions. + /// + public bool MarshalNativeExceptions => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.MarshalNativeExceptions); + + /// + /// True if the generator should not use a NSString for marshalling. + /// + public bool UsePlainString + => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.PlainString); + + public Method (string type, string name, TypeInfo returnType, + SymbolAvailability symbolAvailability, + ExportData exportMethodData, + ImmutableArray attributes, + ImmutableArray modifiers, + ImmutableArray parameters) + { + Type = type; + Name = name; + ReturnType = returnType; + SymbolAvailability = symbolAvailability; + ExportMethodData = exportMethodData; + Attributes = attributes; + Modifiers = modifiers; + Parameters = parameters; + } + + public static bool TryCreate (MethodDeclarationSyntax declaration, RootContext context, + [NotNullWhen (true)] out Method? change) + { + if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IMethodSymbol method) { + change = null; + return false; + } + + var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); + var parametersBucket = ImmutableArray.CreateBuilder (); + // loop over the parameters of the construct since changes on those implies a change in the generated code + foreach (var parameter in method.Parameters) { + var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal]; + if (!Parameter.TryCreate (parameter, parameterDeclaration, context.SemanticModel, out var parameterChange)) + continue; + parametersBucket.Add (parameterChange.Value); + } + + // DO NOT USE default if null, the reason is that it will set the ArgumentSemantics to be value 0, when + // none is value 1. The reason for that is that the default of an enum is 0, that was a mistake + // in the old binding code. + var exportData = method.GetExportData () + ?? new (null, ArgumentSemantic.None, ObjCBindings.Method.Default); + + change = new ( + type: method.ContainingSymbol.ToDisplayString ().Trim (), // we want the full name + name: method.Name, + returnType: new TypeInfo (method.ReturnType), + symbolAvailability: method.GetSupportedPlatforms (), + exportMethodData: exportData, + attributes: attributes, + modifiers: [.. declaration.Modifiers], + parameters: parametersBucket.ToImmutableArray ()) { + BindAs = method.GetBindFromData (), + }; + + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Method.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Method.cs index 5404685ae92f..17a9af9ca32d 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Method.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Method.cs @@ -2,20 +2,16 @@ // Licensed under the MIT License. using System; using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; -using Microsoft.Macios.Generator.Context; -using Microsoft.Macios.Generator.Extensions; -using ObjCRuntime; namespace Microsoft.Macios.Generator.DataModel; -readonly struct Method : IEquatable { +[StructLayout (LayoutKind.Auto)] +readonly partial struct Method : IEquatable { /// /// Type name that owns the method. @@ -37,11 +33,6 @@ namespace Microsoft.Macios.Generator.DataModel; /// public SymbolAvailability SymbolAvailability { get; } - /// - /// The data of the export attribute used to mark the value as a property binding. - /// - public ExportData ExportMethodData { get; } - /// /// Get the attributes added to the constructor. /// @@ -50,65 +41,13 @@ namespace Microsoft.Macios.Generator.DataModel; /// /// Modifiers list. /// - public ImmutableArray Modifiers { get; } = []; + public ImmutableArray Modifiers { get; init; } = []; /// /// Parameters list. /// public ImmutableArray Parameters { get; } = []; - public Method (string type, string name, TypeInfo returnType, - SymbolAvailability symbolAvailability, - ExportData exportMethodData, - ImmutableArray attributes, - ImmutableArray modifiers, - ImmutableArray parameters) - { - Type = type; - Name = name; - ReturnType = returnType; - SymbolAvailability = symbolAvailability; - ExportMethodData = exportMethodData; - Attributes = attributes; - Modifiers = modifiers; - Parameters = parameters; - } - - public static bool TryCreate (MethodDeclarationSyntax declaration, RootBindingContext context, - [NotNullWhen (true)] out Method? change) - { - if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IMethodSymbol method) { - change = null; - return false; - } - - var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); - var parametersBucket = ImmutableArray.CreateBuilder (); - // loop over the parameters of the construct since changes on those implies a change in the generated code - foreach (var parameter in method.Parameters) { - var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal]; - if (!Parameter.TryCreate (parameter, parameterDeclaration, context.SemanticModel, out var parameterChange)) - continue; - parametersBucket.Add (parameterChange.Value); - } - - // DO NOT USE default if null, the reason is that it will set the ArgumentSemantics to be value 0, when - // none is value 1. The reason for that is that the default of an enum is 0, that was a mistake - // in the old binding code. - var exportData = method.GetExportData () - ?? new (null, ArgumentSemantic.None, ObjCBindings.Method.Default); - change = new ( - type: method.ContainingSymbol.ToDisplayString ().Trim (), // we want the full name - name: method.Name, - returnType: new (method.ReturnType), - symbolAvailability: method.GetSupportedPlatforms (), - exportMethodData: exportData, - attributes: attributes, - modifiers: [.. declaration.Modifiers], - parameters: parametersBucket.ToImmutableArray ()); - return true; - } - /// public bool Equals (Method other) { @@ -122,6 +61,8 @@ public bool Equals (Method other) return false; if (ExportMethodData != other.ExportMethodData) return false; + if (BindAs != other.BindAs) + return false; var attrsComparer = new AttributesEqualityComparer (); if (!attrsComparer.Equals (Attributes, other.Attributes)) @@ -147,6 +88,7 @@ public override int GetHashCode () hashCode.Add (Type); hashCode.Add (Name); hashCode.Add (ReturnType); + hashCode.Add (BindAs); foreach (var modifier in Modifiers) { hashCode.Add (modifier); } @@ -180,6 +122,7 @@ public override string ToString () sb.Append ($"ReturnType: {ReturnType}, "); sb.Append ($"SymbolAvailability: {SymbolAvailability}, "); sb.Append ($"ExportMethodData: {ExportMethodData}, "); + sb.Append ($"BindAs: {BindAs}, "); sb.Append ("Attributes: ["); sb.AppendJoin (", ", Attributes); sb.Append ("], Modifiers: ["); diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs new file mode 100644 index 000000000000..92c6dd302b66 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Extensions; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Parameter { + + public enum VariableType { + BlockLiteral, + Handle, + NSArray, + NSString, + NSStringStruct, + PrimitivePointer, + StringPointer, + BindFrom, + } + + /// + /// Returns the bind from data if present in the binding. + /// + public BindFromData? BindAs { get; init; } + + /// + /// Returns if the parameter needs a null check when the code is generated. + /// + public bool NeedsNullCheck { + get { + if (ReferenceKind != ReferenceKind.None) + return false; + if (Type.IsNullable) + return false; + return Type.IsWrapped || Type.IsReferenceType; + } + } + + public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declaration, SemanticModel semanticModel, + [NotNullWhen (true)] out Parameter? parameter) + { + DelegateInfo? delegateInfo = null; + if (symbol.Type is INamedTypeSymbol namedTypeSymbol + && namedTypeSymbol.DelegateInvokeMethod is not null) { + DelegateInfo.TryCreate (namedTypeSymbol.DelegateInvokeMethod, out delegateInfo); + } + + parameter = new (symbol.Ordinal, new (symbol.Type), symbol.Name) { + BindAs = symbol.GetBindFromData (), + IsOptional = symbol.IsOptional, + IsParams = symbol.IsParams, + IsThis = symbol.IsThis, + DefaultValue = (symbol.HasExplicitDefaultValue) ? symbol.ExplicitDefaultValue?.ToString () : null, + ReferenceKind = symbol.RefKind.ToReferenceKind (), + Delegate = delegateInfo, + Attributes = declaration.GetAttributeCodeChanges (semanticModel), + }; + return true; + } + + /// + /// Returns the name of the aux variable that would have needed for the given parameter. Use the + /// variable type to name it. + /// + /// The type of aux variable. + /// The name of the aux variable to use. + public string? GetNameForVariableType (VariableType variableType) + { + var cleanedName = Name.Replace ("@", ""); + return variableType switch { + VariableType.BlockLiteral => $"block_ptr_{cleanedName}", + VariableType.Handle => $"{cleanedName}__handle__", + VariableType.NSArray => $"nsa_{cleanedName}", + VariableType.NSString => $"ns{cleanedName}", + VariableType.NSStringStruct => $"_s{cleanedName}", + VariableType.PrimitivePointer => $"converted_{cleanedName}", + VariableType.StringPointer => $"_p{cleanedName}", + VariableType.BindFrom => $"nsb_{cleanedName}", + _ => null + }; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.cs index ab3f25b149b1..9b86a2660934 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -13,7 +14,8 @@ namespace Microsoft.Macios.Generator.DataModel; /// /// Readonly structure that represents a change in a parameter. /// -readonly struct Parameter : IEquatable { +[StructLayout (LayoutKind.Auto)] +readonly partial struct Parameter : IEquatable { /// /// Parameter position in the method. /// @@ -22,7 +24,7 @@ namespace Microsoft.Macios.Generator.DataModel; /// /// Type of the parameter. /// - public string Type { get; } + public TypeInfo Type { get; } /// /// Parameter name @@ -44,26 +46,6 @@ namespace Microsoft.Macios.Generator.DataModel; /// public bool IsThis { get; init; } - /// - /// True if the parameter is nullable.:w - /// - public bool IsNullable { get; init; } - - /// - /// True if the parameter type is blittable. - /// - public bool IsBlittable { get; } - - /// - /// Returns if the parameter type is a smart enum. - /// - public bool IsSmartEnum { get; init; } - - /// - /// Returns if the parameter is an array type. - /// - public bool IsArray { get; init; } - /// /// Optional default value. /// @@ -90,39 +72,11 @@ namespace Microsoft.Macios.Generator.DataModel; /// public ImmutableArray Attributes { get; init; } = []; - public Parameter (int position, string type, string name, bool isBlittable) + public Parameter (int position, TypeInfo type, string name) { Position = position; Type = type; Name = name; - IsBlittable = isBlittable; - } - - public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declaration, SemanticModel semanticModel, - [NotNullWhen (true)] out Parameter? parameter) - { - var type = symbol.Type is IArrayTypeSymbol arrayTypeSymbol - ? arrayTypeSymbol.ElementType.ToDisplayString () - : symbol.Type.ToDisplayString ().Trim ('?', '[', ']'); - DelegateInfo? delegateInfo = null; - if (symbol.Type is INamedTypeSymbol namedTypeSymbol - && namedTypeSymbol.DelegateInvokeMethod is not null) { - DelegateInfo.TryCreate (namedTypeSymbol.DelegateInvokeMethod, out delegateInfo); - } - - parameter = new (symbol.Ordinal, type, symbol.Name, symbol.Type.IsBlittable ()) { - IsOptional = symbol.IsOptional, - IsParams = symbol.IsParams, - IsThis = symbol.IsThis, - IsNullable = symbol.NullableAnnotation == NullableAnnotation.Annotated, - IsSmartEnum = symbol.Type.IsSmartEnum (), - IsArray = symbol.Type is IArrayTypeSymbol, - DefaultValue = (symbol.HasExplicitDefaultValue) ? symbol.ExplicitDefaultValue?.ToString () : null, - ReferenceKind = symbol.RefKind.ToReferenceKind (), - Delegate = delegateInfo, - Attributes = declaration.GetAttributeCodeChanges (semanticModel), - }; - return true; } /// @@ -140,18 +94,12 @@ public bool Equals (Parameter other) return false; if (IsThis != other.IsThis) return false; - if (IsNullable != other.IsNullable) - return false; - if (IsBlittable != other.IsBlittable) - return false; - if (IsSmartEnum != other.IsSmartEnum) - return false; - if (IsArray != other.IsArray) - return false; if (DefaultValue != other.DefaultValue) return false; if (ReferenceKind != other.ReferenceKind) return false; + if (BindAs != other.BindAs) + return false; if (Delegate != other.Delegate) return false; @@ -175,12 +123,10 @@ public override int GetHashCode () hashCode.Add (IsOptional); hashCode.Add (IsParams); hashCode.Add (IsThis); - hashCode.Add (IsNullable); - hashCode.Add (IsSmartEnum); - hashCode.Add (IsArray); hashCode.Add (DefaultValue); hashCode.Add ((int) ReferenceKind); hashCode.Add (Delegate); + hashCode.Add (BindAs); return hashCode.ToHashCode (); } @@ -201,17 +147,14 @@ public override string ToString () sb.Append ($"Position: {Position}, "); sb.Append ($"Type: {Type}, "); sb.Append ($"Name: {Name}, "); - sb.Append ("Attributes: "); + sb.Append ("Attributes: ["); sb.AppendJoin (", ", Attributes); - sb.Append ($" IsOptional: {IsOptional}, "); + sb.Append ($"] IsOptional: {IsOptional}, "); sb.Append ($"IsParams: {IsParams}, "); sb.Append ($"IsThis: {IsThis}, "); - sb.Append ($"IsNullable: {IsNullable}, "); - sb.Append ($"IsBlittable: {IsBlittable}, "); - sb.Append ($"IsSmartEnum: {IsSmartEnum}, "); - sb.Append ($"IsArray: {IsArray}, "); sb.Append ($"DefaultValue: {DefaultValue}, "); sb.Append ($"ReferenceKind: {ReferenceKind}, "); + sb.Append ($"BindAs: {BindAs?.ToString () ?? "null"}, "); sb.Append ($"Delegate: {Delegate?.ToString () ?? "null"} }}"); return sb.ToString (); } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/ParameterComparer.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/ParameterComparer.cs index d3b02979e688..ba1f9763e2b9 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/ParameterComparer.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/ParameterComparer.cs @@ -11,14 +11,15 @@ public int Compare (Parameter x, Parameter y) var value = x.Position.CompareTo (y.Position); if (value != 0) return value; - value = String.Compare (x.Type, y.Type, StringComparison.Ordinal); + var comparer = new TypeInfoComparer (); + value = comparer.Compare (x.Type, y.Type); if (value != 0) return value; value = String.Compare (x.Name, y.Name, StringComparison.Ordinal); if (value != 0) return value; - var xValues = new [] { x.IsOptional, x.IsParams, x.IsThis, x.IsNullable }; - var yValues = new [] { y.IsOptional, y.IsParams, y.IsThis, y.IsNullable }; + var xValues = new [] { x.IsOptional, x.IsParams, x.IsThis }; + var yValues = new [] { y.IsOptional, y.IsParams, y.IsThis }; for (int i = 0; i < xValues.Length; ++i) { value = xValues [i].CompareTo (yValues [i]); if (value != 0) diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs new file mode 100644 index 000000000000..261492127b8d --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.Extensions; +using ObjCRuntime; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Property { + + /// + /// The data of the field attribute used to mark the value as a field binding. + /// + public FieldInfo? ExportFieldData { get; init; } + + /// + /// True if the property represents a Objc field. + /// + [MemberNotNullWhen (true, nameof (ExportFieldData))] + public bool IsField => ExportFieldData is not null; + + /// + /// Returns if the field was marked as a notification. + /// + public bool IsNotification + => IsField && ExportFieldData.Value.FieldData.Flags.HasFlag (ObjCBindings.Property.Notification); + + /// + /// The data of the field attribute used to mark the value as a property binding. + /// + public ExportData? ExportPropertyData { get; init; } + + /// + /// True if the property represents a Objc property. + /// + [MemberNotNullWhen (true, nameof (ExportPropertyData))] + public bool IsProperty => ExportPropertyData is not null; + + /// + /// Returns if the property was marked as thread safe. + /// + public bool IsThreadSafe => + IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.IsThreadSafe); + + /// + /// True if the method was exported with the MarshalNativeExceptions flag allowing it to support native exceptions. + /// + public bool MarshalNativeExceptions + => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.MarshalNativeExceptions); + + /// + /// Returns the bind from data if present in the binding. + /// + public BindFromData? BindAs { get; init; } + + /// + /// True if the property should be generated without a backing field. + /// + public bool IsTransient => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.Transient); + + /// + /// True if the property was marked to DisableZeroCopy. + /// + public bool DisableZeroCopy + => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.DisableZeroCopy); + + /// + /// True if the generator should not use a NSString for marshalling. + /// + public bool UsePlainString + => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.PlainString); + + /// + /// Return if the method invocation should be wrapped by a NSAutoReleasePool. + /// + public bool AutoRelease => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Method.AutoRelease); + + readonly bool? needsBackingField = null; + /// + /// States if the property, when generated, needs a backing field. + /// + public bool NeedsBackingField { + get { + if (needsBackingField is not null) + return needsBackingField.Value; + var isWrapped = ReturnType.IsWrapped || + ReturnType is { IsArray: true, ArrayElementTypeIsWrapped: true }; + return isWrapped && !IsTransient; + } + // Added to allow testing. This way we can set the correct expectation in the test factory + init => needsBackingField = value; + } + + readonly bool? requiresDirtyCheck = null; + /// + /// States if the property, when generated, should have a dirty check. + /// + public bool RequiresDirtyCheck { + get { + if (requiresDirtyCheck is not null) + return requiresDirtyCheck.Value; + if (!IsProperty) + return false; + switch (ExportPropertyData.Value.ArgumentSemantic) { + case ArgumentSemantic.Copy: + case ArgumentSemantic.Retain: + case ArgumentSemantic.None: + return NeedsBackingField; + default: + return false; + } + } + // Added to allow testing. This way we can set the correct expectation in the test factory + init => requiresDirtyCheck = value; + } + + static FieldInfo? GetFieldInfo (RootContext context, IPropertySymbol propertySymbol) + { + // grab the last port of the namespace + var ns = propertySymbol.ContainingNamespace.Name.Split ('.') [^1]; + var fieldData = propertySymbol.GetFieldData (); + FieldInfo? fieldInfo = null; + if (fieldData is not null && context.TryComputeLibraryName (fieldData.Value.LibraryName, ns, + out string? libraryName, out string? libraryPath)) { + fieldInfo = new FieldInfo (fieldData.Value, libraryName, libraryPath); + } + + return fieldInfo; + } + + internal Property (string name, TypeInfo returnType, + SymbolAvailability symbolAvailability, + ImmutableArray attributes, + ImmutableArray modifiers, + ImmutableArray accessors) + { + Name = name; + BackingField = $"_{Name}"; + ReturnType = returnType; + SymbolAvailability = symbolAvailability; + Attributes = attributes; + Modifiers = modifiers; + Accessors = accessors; + } + + public static bool TryCreate (PropertyDeclarationSyntax declaration, RootContext context, + [NotNullWhen (true)] out Property? change) + { + var memberName = declaration.Identifier.ToFullString ().Trim (); + // get the symbol from the property declaration + if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IPropertySymbol propertySymbol) { + change = null; + return false; + } + + var propertySupportedPlatforms = propertySymbol.GetSupportedPlatforms (); + var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); + + ImmutableArray accessorCodeChanges = []; + if (declaration.AccessorList is not null && declaration.AccessorList.Accessors.Count > 0) { + // calculate any possible changes in the accessors of the property + var accessorsBucket = ImmutableArray.CreateBuilder (); + foreach (var accessorDeclaration in declaration.AccessorList.Accessors) { + if (context.SemanticModel.GetDeclaredSymbol (accessorDeclaration) is not ISymbol accessorSymbol) + continue; + var kind = accessorDeclaration.Kind ().ToAccessorKind (); + var accessorAttributeChanges = + accessorDeclaration.GetAttributeCodeChanges (context.SemanticModel); + accessorsBucket.Add (new ( + accessorKind: kind, + exportPropertyData: accessorSymbol.GetExportData (), + symbolAvailability: accessorSymbol.GetSupportedPlatforms (), + attributes: accessorAttributeChanges, + modifiers: [.. accessorDeclaration.Modifiers])); + } + + accessorCodeChanges = accessorsBucket.ToImmutable (); + } + + if (declaration.ExpressionBody is not null) { + // an expression body == a getter with no attrs or modifiers; that means that the accessor does not have + // extra availability, but the ones form the property + accessorCodeChanges = [new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: propertySupportedPlatforms, + exportPropertyData: null, + attributes: [], + modifiers: []) + ]; + } + + change = new ( + name: memberName, + returnType: new (propertySymbol.Type), + symbolAvailability: propertySupportedPlatforms, + attributes: attributes, + modifiers: [.. declaration.Modifiers], + accessors: accessorCodeChanges) { + BindAs = propertySymbol.GetBindFromData (), + ExportFieldData = GetFieldInfo (context, propertySymbol), + ExportPropertyData = propertySymbol.GetExportData (), + }; + return true; + } + + /// + public bool Equals (Property other) + { + if (!CoreEquals (other)) + return false; + if (IsTransient != other.IsTransient) + return false; + if (NeedsBackingField != other.NeedsBackingField) + return false; + return RequiresDirtyCheck == other.RequiresDirtyCheck; + } + + /// + public override string ToString () + { + var sb = new StringBuilder ( + $"Name: '{Name}', Type: {ReturnType}, Supported Platforms: {SymbolAvailability}, ExportFieldData: '{ExportFieldData?.ToString () ?? "null"}', ExportPropertyData: '{ExportPropertyData?.ToString () ?? "null"}', "); + sb.Append ($"IsTransient: '{IsTransient}', "); + sb.Append ($"NeedsBackingField: '{NeedsBackingField}', "); + sb.Append ($"RequiresDirtyCheck: '{RequiresDirtyCheck}', "); + sb.Append ($"BindAs: '{BindAs}', "); + sb.Append ("Attributes: ["); + sb.AppendJoin (",", Attributes); + sb.Append ("], Modifiers: ["); + sb.AppendJoin (",", Modifiers.Select (x => x.Text)); + sb.Append ("], Accessors: ["); + sb.AppendJoin (",", Accessors); + sb.Append (']'); + return sb.ToString (); + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Property.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.cs index aaf9c3ff9c52..bf8811f51c60 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Property.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.cs @@ -2,22 +2,17 @@ // Licensed under the MIT License. using System; using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text; +using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; -using Microsoft.Macios.Generator.Context; -using Microsoft.Macios.Generator.Extensions; namespace Microsoft.Macios.Generator.DataModel; /// /// Readonly struct that represent the changes that a user has made in a property. /// -readonly struct Property : IEquatable { +[StructLayout (LayoutKind.Auto)] +readonly partial struct Property : IEquatable { /// /// Name of the property. /// @@ -25,10 +20,18 @@ namespace Microsoft.Macios.Generator.DataModel; public string BackingField { get; private init; } + readonly TypeInfo returnType; + /// /// Representation of the property type. /// - public TypeInfo ReturnType { get; } = default; + public TypeInfo ReturnType { + get => returnType; + private init { + returnType = value; + ValueParameter = new Parameter (0, returnType, "value"); + } + } /// /// Returns if the property type is bittable. @@ -50,31 +53,6 @@ namespace Microsoft.Macios.Generator.DataModel; /// public SymbolAvailability SymbolAvailability { get; } - /// - /// The data of the field attribute used to mark the value as a field binding. - /// - public FieldInfo? ExportFieldData { get; init; } - - /// - /// True if the property represents a Objc field. - /// - [MemberNotNullWhen (true, nameof (ExportFieldData))] - public bool IsField => ExportFieldData is not null; - - public bool IsNotification - => IsField && ExportFieldData.Value.FieldData.Flags.HasFlag (ObjCBindings.Property.Notification); - - /// - /// The data of the field attribute used to mark the value as a property binding. - /// - public ExportData? ExportPropertyData { get; init; } - - /// - /// True if the property represents a Objc property. - /// - [MemberNotNullWhen (true, nameof (ExportPropertyData))] - public bool IsProperty => ExportPropertyData is not null; - /// /// Get the attributes added to the member. /// @@ -83,29 +61,26 @@ public bool IsNotification /// /// Get the modifiers of the property. /// - public ImmutableArray Modifiers { get; } = []; + public ImmutableArray Modifiers { get; init; } = []; /// /// Get the list of accessor changes of the property. /// public ImmutableArray Accessors { get; } = []; - internal Property (string name, TypeInfo returnType, - SymbolAvailability symbolAvailability, - ImmutableArray attributes, - ImmutableArray modifiers, ImmutableArray accessors) + public Parameter ValueParameter { get; private init; } + + public Accessor? GetAccessor (AccessorKind accessorKind) { - Name = name; - BackingField = $"_{Name}"; - ReturnType = returnType; - SymbolAvailability = symbolAvailability; - Attributes = attributes; - Modifiers = modifiers; - Accessors = accessors; + // careful, do not use FirstOrDefault from LINQ because we are using structs! + foreach (var accessor in Accessors) { + if (accessor.Kind == accessorKind) + return accessor; + } + return null; } - /// - public bool Equals (Property other) + bool CoreEquals (Property other) { // this could be a large && but ifs are more readable if (Name != other.Name) @@ -124,6 +99,8 @@ public bool Equals (Property other) return false; if (ExportPropertyData != other.ExportPropertyData) return false; + if (BindAs != other.BindAs) + return false; var attrsComparer = new AttributesEqualityComparer (); if (!attrsComparer.Equals (Attributes, other.Attributes)) @@ -159,90 +136,4 @@ public override int GetHashCode () return !left.Equals (right); } - static FieldInfo? GetFieldInfo (RootBindingContext context, IPropertySymbol propertySymbol) - { - // grab the last port of the namespace - var ns = propertySymbol.ContainingNamespace.Name.Split ('.') [^1]; - var fieldData = propertySymbol.GetFieldData (); - FieldInfo? fieldInfo = null; - if (fieldData is not null && context.TryComputeLibraryName (fieldData.Value.LibraryName, ns, - out string? libraryName, out string? libraryPath)) { - fieldInfo = new FieldInfo (fieldData.Value, libraryName, libraryPath); - } - - return fieldInfo; - } - - public static bool TryCreate (PropertyDeclarationSyntax declaration, RootBindingContext context, - [NotNullWhen (true)] out Property? change) - { - var memberName = declaration.Identifier.ToFullString ().Trim (); - // get the symbol from the property declaration - if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IPropertySymbol propertySymbol) { - change = null; - return false; - } - - var propertySupportedPlatforms = propertySymbol.GetSupportedPlatforms (); - var attributes = declaration.GetAttributeCodeChanges (context.SemanticModel); - - ImmutableArray accessorCodeChanges = []; - if (declaration.AccessorList is not null && declaration.AccessorList.Accessors.Count > 0) { - // calculate any possible changes in the accessors of the property - var accessorsBucket = ImmutableArray.CreateBuilder (); - foreach (var accessorDeclaration in declaration.AccessorList.Accessors) { - if (context.SemanticModel.GetDeclaredSymbol (accessorDeclaration) is not ISymbol accessorSymbol) - continue; - var kind = accessorDeclaration.Kind ().ToAccessorKind (); - var accessorAttributeChanges = - accessorDeclaration.GetAttributeCodeChanges (context.SemanticModel); - accessorsBucket.Add (new ( - accessorKind: kind, - exportPropertyData: accessorSymbol.GetExportData (), - symbolAvailability: accessorSymbol.GetSupportedPlatforms (), - attributes: accessorAttributeChanges, - modifiers: [.. accessorDeclaration.Modifiers])); - } - - accessorCodeChanges = accessorsBucket.ToImmutable (); - } - - if (declaration.ExpressionBody is not null) { - // an expression body == a getter with no attrs or modifiers; that means that the accessor does not have - // extra availability, but the ones form the property - accessorCodeChanges = [new ( - accessorKind: AccessorKind.Getter, - symbolAvailability: propertySupportedPlatforms, - exportPropertyData: null, - attributes: [], - modifiers: []) - ]; - } - - change = new ( - name: memberName, - returnType: new (propertySymbol.Type), - symbolAvailability: propertySupportedPlatforms, - attributes: attributes, - modifiers: [.. declaration.Modifiers], - accessors: accessorCodeChanges) { - ExportFieldData = GetFieldInfo (context, propertySymbol), - ExportPropertyData = propertySymbol.GetExportData (), - }; - return true; - } - - /// - public override string ToString () - { - var sb = new StringBuilder ( - $"Name: '{Name}', Type: {ReturnType}, Supported Platforms: {SymbolAvailability}, ExportFieldData: '{ExportFieldData?.ToString () ?? "null"}', ExportPropertyData: '{ExportPropertyData?.ToString () ?? "null"}' Attributes: ["); - sb.AppendJoin (",", Attributes); - sb.Append ("], Modifiers: ["); - sb.AppendJoin (",", Modifiers.Select (x => x.Text)); - sb.Append ("], Accessors: ["); - sb.AppendJoin (",", Accessors); - sb.Append (']'); - return sb.ToString (); - } } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs new file mode 100644 index 000000000000..6d6bd94348f4 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Extensions; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct TypeInfo { + + /// + /// Return if the type represents a wrapped object from the objc world. + /// + public bool IsWrapped { get; init; } + + /// + /// Returns, if the type is an array, if its elements are a wrapped object from the objc world. + /// + public bool ArrayElementTypeIsWrapped { get; init; } + + internal TypeInfo (ITypeSymbol symbol) : + this ( + symbol is IArrayTypeSymbol arrayTypeSymbol + ? arrayTypeSymbol.ElementType.ToDisplayString () + : symbol.ToDisplayString ().Trim ('?', '[', ']'), + symbol.SpecialType) + { + IsNullable = symbol.NullableAnnotation == NullableAnnotation.Annotated; + IsBlittable = symbol.IsBlittable (); + IsSmartEnum = symbol.IsSmartEnum (); + IsReferenceType = symbol.IsReferenceType; + IsStruct = symbol.TypeKind == TypeKind.Struct; + IsInterface = symbol.TypeKind == TypeKind.Interface; + IsNativeIntegerType = symbol.IsNativeIntegerType; + IsNativeEnum = symbol.HasAttribute (AttributesNames.NativeEnumAttribute); + + // data that we can get from the symbol without being INamedType + symbol.GetInheritance ( + isNSObject: out isNSObject, + isNativeObject: out isINativeObject, + isDictionaryContainer: out isDictionaryContainer, + parents: out parents, + interfaces: out interfaces); + + IsWrapped = symbol.IsWrapped (isNSObject); + if (symbol is IArrayTypeSymbol arraySymbol) { + IsArray = true; + ArrayElementTypeIsWrapped = arraySymbol.ElementType.IsWrapped (); + } + + // try to get the named type symbol to have more educated decisions + var namedTypeSymbol = symbol as INamedTypeSymbol; + + // store the enum special type, useful when generate code that needs to cast + EnumUnderlyingType = namedTypeSymbol?.EnumUnderlyingType?.SpecialType; + + if (!IsReferenceType && IsNullable && namedTypeSymbol is not null) { + // get the type argument for nullable, which we know is the data that was boxed and use it to + // overwrite the SpecialType + var typeArgument = namedTypeSymbol.TypeArguments [0]; + SpecialType = typeArgument.SpecialType; + MetadataName = SpecialType is SpecialType.None or SpecialType.System_Void + ? null : typeArgument.MetadataName; + } else { + MetadataName = SpecialType is SpecialType.None or SpecialType.System_Void + ? null : symbol.MetadataName; + } + + } + +} diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.cs index 09f35d640f79..b4b0b82903c6 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.cs @@ -3,8 +3,10 @@ using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Extensions; namespace Microsoft.Macios.Generator.DataModel; @@ -12,12 +14,27 @@ namespace Microsoft.Macios.Generator.DataModel; /// /// Readonly structure that represents a change in a method return type. /// -readonly struct TypeInfo : IEquatable { +[StructLayout (LayoutKind.Auto)] +readonly partial struct TypeInfo : IEquatable { + public static TypeInfo Void = new ("void", SpecialType.System_Void) { Parents = ["System.ValueType", "object"], }; + + readonly string fullyQualifiedName = string.Empty; /// - /// Type of the parameter. + /// The fully qualified name of the type. /// - public string Name { get; } + public string FullyQualifiedName { + get => fullyQualifiedName; + init { + fullyQualifiedName = value; + var index = fullyQualifiedName.LastIndexOf ('.'); + Name = index != -1 + ? fullyQualifiedName.Substring (index + 1) + : fullyQualifiedName; + } + } + + public string Name { get; private init; } = string.Empty; /// /// The metadata name of the type. This is normally the same as name except @@ -66,11 +83,33 @@ namespace Microsoft.Macios.Generator.DataModel; /// public bool IsReferenceType { get; } + /// + /// Returns if the type is a struct. + /// + public bool IsStruct { get; } + /// /// Returns if the return type is void. /// public bool IsVoid => SpecialType == SpecialType.System_Void; + /// + /// True if the type is for an interface. + /// + public bool IsInterface { get; init; } + + /// + /// True if the type represents an integer that was built using one of the keywords, like byte, int, nint etc. + /// + /// This can be used to decide if we should use the name of the metadata name to cast the value. + /// + public bool IsNativeIntegerType { get; init; } + + /// + /// True if an enumerator was marked with the NativeAttribute. + /// + public bool IsNativeEnum { get; init; } + readonly bool isNSObject = false; public bool IsNSObject { @@ -85,6 +124,13 @@ public bool IsINativeObject { init => isINativeObject = value; } + readonly bool isDictionaryContainer = false; + + public bool IsDictionaryContainer { + get => isDictionaryContainer; + init => isDictionaryContainer = value; + } + readonly ImmutableArray parents = []; public ImmutableArray Parents { get => parents; @@ -100,7 +146,7 @@ public ImmutableArray Interfaces { internal TypeInfo (string name, SpecialType specialType) { - Name = name; + FullyQualifiedName = name; SpecialType = specialType; } @@ -110,59 +156,21 @@ internal TypeInfo (string name, bool isBlittable = false, bool isSmartEnum = false, bool isArray = false, - bool isReferenceType = false) : this (name, specialType) + bool isReferenceType = false, + bool isStruct = false) : this (name, specialType) { IsNullable = isNullable; IsBlittable = isBlittable; IsSmartEnum = isSmartEnum; IsArray = isArray; IsReferenceType = isReferenceType; - } - - internal TypeInfo (ITypeSymbol symbol) : - this ( - symbol is IArrayTypeSymbol arrayTypeSymbol - ? arrayTypeSymbol.ElementType.ToDisplayString () - : symbol.ToDisplayString ().Trim ('?', '[', ']'), - symbol.SpecialType) - { - IsNullable = symbol.NullableAnnotation == NullableAnnotation.Annotated; - IsBlittable = symbol.IsBlittable (); - IsSmartEnum = symbol.IsSmartEnum (); - IsArray = symbol is IArrayTypeSymbol; - IsReferenceType = symbol.IsReferenceType; - - // data that we can get from the symbol without being INamedType - symbol.GetInheritance ( - isNSObject: out isNSObject, - isNativeObject: out isINativeObject, - parents: out parents, - interfaces: out interfaces); - - // try to get the named type symbol to have more educated decisions - var namedTypeSymbol = symbol as INamedTypeSymbol; - - // store the enum special type, useful when generate code that needs to cast - EnumUnderlyingType = namedTypeSymbol?.EnumUnderlyingType?.SpecialType; - - if (!IsReferenceType && IsNullable && namedTypeSymbol is not null) { - // get the type argument for nullable, which we know is the data that was boxed and use it to - // overwrite the SpecialType - var typeArgument = namedTypeSymbol.TypeArguments [0]; - SpecialType = typeArgument.SpecialType; - MetadataName = SpecialType is SpecialType.None or SpecialType.System_Void - ? null : typeArgument.MetadataName; - } else { - MetadataName = SpecialType is SpecialType.None or SpecialType.System_Void - ? null : symbol.MetadataName; - } - + IsStruct = isStruct; } /// public bool Equals (TypeInfo other) { - if (Name != other.Name) + if (FullyQualifiedName != other.FullyQualifiedName) return false; if (SpecialType != other.SpecialType) return false; @@ -178,10 +186,18 @@ public bool Equals (TypeInfo other) return false; if (IsReferenceType != other.IsReferenceType) return false; + if (IsStruct != other.IsStruct) + return false; if (IsVoid != other.IsVoid) return false; if (EnumUnderlyingType != other.EnumUnderlyingType) return false; + if (IsInterface != other.IsInterface) + return false; + if (IsNativeIntegerType != other.IsNativeIntegerType) + return false; + if (IsNativeEnum != other.IsNativeEnum) + return false; // compare base classes and interfaces, order does not matter at all var listComparer = new CollectionComparer (); @@ -202,7 +218,7 @@ public override bool Equals (object? obj) /// public override int GetHashCode () { - return HashCode.Combine (Name, IsNullable, IsBlittable, IsSmartEnum, IsArray, IsReferenceType, IsVoid); + return HashCode.Combine (FullyQualifiedName, IsNullable, IsBlittable, IsSmartEnum, IsArray, IsReferenceType, IsVoid); } public static bool operator == (TypeInfo left, TypeInfo right) @@ -215,11 +231,56 @@ public override int GetHashCode () return !left.Equals (right); } + const string NativeHandle = "NativeHandle"; + const string IntPtr = "IntPtr"; + const string UIntPtr = "UIntPtr"; + + public string? ToMarshallType () + { +#pragma warning disable format + var type = this switch { + // special cases based on name + { Name: "nfloat" or "NFloat" } => "nfloat", + { Name: "nint" or "nuint" } => MetadataName, + // special string case + { SpecialType: SpecialType.System_String } => NativeHandle, // use a NSString when we get a string + + // NSObject should use the native handle + { IsNSObject: true } => NativeHandle, + { IsINativeObject: true } => NativeHandle, + + // structs will use their name + { IsStruct: true, SpecialType: SpecialType.System_Double } => "Double", + { IsStruct: true } => Name, + + // enums: + // IsSmartEnum: We are using a nsstring, so it should be a native handle. + // IsNativeEnum: Depends on the enum backing field kind. + // GeneralEnum: Depends on the EnumUnderlyingType + + { IsSmartEnum: true } => NativeHandle, + { IsNativeEnum: true, EnumUnderlyingType: SpecialType.System_Int64 } => IntPtr, + { IsNativeEnum: true, EnumUnderlyingType: SpecialType.System_UInt64 } => UIntPtr, + { IsEnum: true, EnumUnderlyingType: not null } => EnumUnderlyingType.GetKeyword (), + + // special type that is a keyword (none would be a ref type) + { SpecialType: SpecialType.System_Void } => SpecialType.GetKeyword (), + + // This should not happen in bindings because all of the types should either be native objects + // nsobjects, or structs + { IsReferenceType: false } => Name, + + _ => null, + }; +#pragma warning restore format + return type; + } + /// public override string ToString () { var sb = new StringBuilder ("{"); - sb.Append ($"Name: '{Name}', "); + sb.Append ($"Name: '{FullyQualifiedName}', "); sb.Append ($"MetadataName: '{MetadataName}', "); sb.Append ($"SpecialType: '{SpecialType}', "); sb.Append ($"IsNullable: {IsNullable}, "); @@ -227,9 +288,14 @@ public override string ToString () sb.Append ($"IsSmartEnum: {IsSmartEnum}, "); sb.Append ($"IsArray: {IsArray}, "); sb.Append ($"IsReferenceType: {IsReferenceType}, "); + sb.Append ($"IsStruct: {IsStruct}, "); sb.Append ($"IsVoid : {IsVoid}, "); sb.Append ($"IsNSObject : {IsNSObject}, "); + sb.Append ($"IsDictionaryContainer: {IsDictionaryContainer}, "); sb.Append ($"IsNativeObject: {IsINativeObject}, "); + sb.Append ($"IsInterface: {IsInterface}, "); + sb.Append ($"IsNativeIntegerType: {IsNativeIntegerType}, "); + sb.Append ($"IsNativeEnum: {IsNativeEnum}, "); sb.Append ($"EnumUnderlyingType: '{EnumUnderlyingType?.ToString () ?? "null"}', "); sb.Append ("Parents: ["); sb.AppendJoin (", ", parents); diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfoComparer.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfoComparer.cs index c657477eb461..863ab7332c20 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfoComparer.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfoComparer.cs @@ -10,7 +10,7 @@ class TypeInfoComparer : IComparer { /// public int Compare (TypeInfo x, TypeInfo y) { - var returnTypeComparison = String.Compare (x.Name, y.Name, StringComparison.Ordinal); + var returnTypeComparison = String.Compare (x.FullyQualifiedName, y.FullyQualifiedName, StringComparison.Ordinal); if (returnTypeComparison != 0) return returnTypeComparison; var isNullableComparison = x.IsNullable.CompareTo (y.IsNullable); diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.Dlfcn.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.Dlfcn.cs index f030e67bec83..747d5ad8dc49 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.Dlfcn.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.Dlfcn.cs @@ -2,10 +2,12 @@ // Licensed under the MIT License. using System; +using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Generator.Extensions; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.Macios.Generator.Emitters; @@ -48,16 +50,42 @@ public static CompilationUnitSyntax CachePointer (string libraryName, string fie /// /// Generic method that returns the syntax for the Get* methods. /// - /// The method name for the invocation. /// The name of the library that contains the field. /// The field name literal. - /// - static CompilationUnitSyntax GetConstant (string methodName, string libraryName, string fieldName) + /// If the ! operator should be used. + /// The method name for the invocation. + /// The syntax needed to get a constant. + static CompilationUnitSyntax GetConstant (string libraryName, string fieldName, bool suppressNullableWarning = false, + [CallerMemberName] string methodName = "") { var arguments = new SyntaxNodeOrToken [] { GetLibraryArgument (libraryName), Token (SyntaxKind.CommaToken), GetLiteralExpressionArgument (SyntaxKind.StringLiteralExpression, fieldName), }; + return StaticInvocationExpression (Dlfcn, methodName, arguments, suppressNullableWarning: suppressNullableWarning); + } + + /// + /// Generic method that returns the syntax for the Set methods. + /// + /// The name of the library that contains the field. + /// The field name literal. + /// The name of the variable to use for the value. This is NOT a literal value. + /// The method name for the invocation. + /// An optional type to cast to. + /// The sytax needed to set a constant. + static CompilationUnitSyntax SetConstant (string libraryName, string fieldName, + string variableName, [CallerMemberName] string methodName = "", string? castTarget = null) + { + var arguments = new SyntaxNodeOrToken [] { + GetLibraryArgument (libraryName), + Token (SyntaxKind.CommaToken), + GetLiteralExpressionArgument (SyntaxKind.StringLiteralExpression, fieldName), + Token (SyntaxKind.CommaToken), + Argument (castTarget is null + ? IdentifierName (variableName) + : CastExpression (IdentifierName (castTarget), IdentifierName (variableName))), + }; return StaticInvocationExpression (Dlfcn, methodName, arguments); } @@ -79,7 +107,7 @@ static CompilationUnitSyntax GetGenericConstant (string methodName, string gener /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetStringConstant (string libraryName, string fieldName) - => GetConstant ("GetStringConstant", libraryName, fieldName); + => GetConstant (libraryName, fieldName, suppressNullableWarning: true); /// @@ -89,7 +117,7 @@ public static CompilationUnitSyntax GetStringConstant (string libraryName, strin /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetIndirect (string libraryName, string fieldName) - => GetConstant ("GetIndirect", libraryName, fieldName); + => GetConstant (libraryName, fieldName); /// /// Generates a call for "Dlfcn.GetStruct;lt&type;gt& (libraryName, fieldName);"]; @@ -108,10 +136,28 @@ public static CompilationUnitSyntax GetStruct (string type, string libraryName, /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetSByte (string libraryName, string fieldName) - => GetConstant ("GetSByte", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetSByte (string libraryName, string symbol, sbyte value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetSByte (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetSByte (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); + + /// + /// Generates a call for "Dlfcn.SetSByte (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetSByte (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); /// /// Generates a call for "Dlfcn.GetByte (libraryName, fieldName);"]; @@ -120,11 +166,28 @@ public static CompilationUnitSyntax SetSByte (string libraryName, string symbol, /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetByte (string libraryName, string fieldName) - => GetConstant ("GetByte", libraryName, fieldName); + => GetConstant (libraryName, fieldName); + /// + /// Generates a call for "Dlfcn.SetByte (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetByte (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax SetByte (string libraryName, string symbol, byte value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetByte (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetByte (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); /// /// Generates a call for "Dlfcn.GetInt16 (libraryName, fieldName);"]; @@ -133,10 +196,28 @@ public static CompilationUnitSyntax SetByte (string libraryName, string symbol, /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetInt16 (string libraryName, string fieldName) - => GetConstant ("GetInt16", libraryName, fieldName); + => GetConstant (libraryName, fieldName); + + /// + /// Generates a call for "Dlfcn.SetInt16 (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetInt16 (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax SetInt16 (string libraryName, string symbol, short value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetInt16 (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetInt16 (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); /// /// Generates a call for "Dlfcn.GetUInt16 (libraryName, fieldName);"]; @@ -145,10 +226,28 @@ public static CompilationUnitSyntax SetInt16 (string libraryName, string symbol, /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetUInt16 (string libraryName, string fieldName) - => GetConstant ("GetUInt16", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetUInt16 (IntPtr handle, string symbol, ushort value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetUInt16 (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetUInt16 (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); + + /// + /// Generates a call for "Dlfcn.SetUInt16 (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetUInt16 (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); /// /// Generates a call for "Dlfcn.GetInt32 (libraryName, fieldName);"]; @@ -157,10 +256,28 @@ public static CompilationUnitSyntax SetUInt16 (IntPtr handle, string symbol, ush /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetInt32 (string libraryName, string fieldName) - => GetConstant ("GetInt32", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetInt32 (IntPtr handle, string symbol, int value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetInt32 (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetInt32 (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); + + /// + /// Generates a call for "Dlfcn.SetInt32 (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetInt32 (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); /// /// Generates a call for "Dlfcn.GetUInt32 (libraryName, fieldName);"]; @@ -169,10 +286,28 @@ public static CompilationUnitSyntax SetInt32 (IntPtr handle, string symbol, int /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetUInt32 (string libraryName, string fieldName) - => GetConstant ("GetUInt32", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetUInt32 (IntPtr handle, string symbol, uint value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetUInt32 (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetUInt32 (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); + + /// + /// Generates a call for "Dlfcn.SetUInt32 (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetUInt32 (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); /// /// Generates a call for "Dlfcn.GetInt64 (libraryName, fieldName);"]; @@ -181,10 +316,28 @@ public static CompilationUnitSyntax SetUInt32 (IntPtr handle, string symbol, uin /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetInt64 (string libraryName, string fieldName) - => GetConstant ("GetInt64", libraryName, fieldName); + => GetConstant (libraryName, fieldName); + + /// + /// Generates a call for "Dlfcn.SetUInt32 (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetInt64 (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax SetInt64 (IntPtr handle, string symbol, long value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetUInt32 (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetInt64 (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); /// /// Generates a call for "Dlfcn.GetUInt64 (libraryName, fieldName);"]; @@ -193,31 +346,58 @@ public static CompilationUnitSyntax SetInt64 (IntPtr handle, string symbol, long /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetUInt64 (string libraryName, string fieldName) - => GetConstant ("GetUInt64", libraryName, fieldName); - - public static CompilationUnitSyntax SetUInt64 (string libraryName, string symbol, ulong value) - => throw new NotImplementedException (); - - public static CompilationUnitSyntax SetString (string libraryName, string symbol, string? value) - => throw new NotImplementedException (); - - public static CompilationUnitSyntax SetArray (string libraryName, string symbol, /*NSArray?*/ string array) - => throw new NotImplementedException (); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetObject (string libraryName, string symbol, /*NSObject?*/ string value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetUInt64 (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetUInt64 (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax GetNInt (string libraryName, string symbol) - => GetConstant ("GetNInt", libraryName, symbol); + /// + /// Generates a call for "Dlfcn.SetUInt64 (libraryName, fieldName, (cast)value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// An optional type to cast too. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetUInt64 (string libraryName, string fieldName, string variableName, string? castTarget) + => SetConstant (libraryName, fieldName, variableName, castTarget: castTarget); - public static CompilationUnitSyntax SetNInt (IntPtr handle, string symbol, nint value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetString (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetString (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax GetNUInt (string libraryName, string symbol) - => GetConstant ("GetNInt", libraryName, symbol); + /// + /// Generates a call for "Dlfcn.SetArray (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetArray (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax SetNUInt (string libraryName, string symbol, nuint value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetObject (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetObject (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); /// /// Generates a call for "Dlfcn.GetNFloat (libraryName, fieldName);"]; @@ -226,10 +406,17 @@ public static CompilationUnitSyntax SetNUInt (string libraryName, string symbol, /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetNFloat (string libraryName, string fieldName) - => GetConstant ("GetNFloat", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetNFloat (string libraryName, string symbol, /*nfloat*/ string value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetNFloat (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetNFloat (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); /// /// Generates a call for "Dlfcn.GetIntPtr (libraryName, fieldName);"]; @@ -238,7 +425,7 @@ public static CompilationUnitSyntax SetNFloat (string libraryName, string symbol /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetIntPtr (string libraryName, string fieldName) - => GetConstant ("GetIntPtr", libraryName, fieldName); + => GetConstant (libraryName, fieldName); /// /// Generates a call for "Dlfcn.GetUIntPtr (libraryName, fieldName);"]; @@ -247,16 +434,36 @@ public static CompilationUnitSyntax GetIntPtr (string libraryName, string fieldN /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetUIntPtr (string libraryName, string fieldName) - => GetConstant ("GetUIntPtr", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetUIntPtr (string libraryName, string symbol, UIntPtr value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetUIntPtr (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetUIntPtr (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax SetIntPtr (string libraryName, string symbol, IntPtr value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetIntPtr (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetIntPtr (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); - public static CompilationUnitSyntax GetCGRect (string libraryName, string symbol) - => GetConstant ("GetCGRect", libraryName, symbol); + /// + /// Generates a call for "Dlfcn.GetCGRect (libraryName, fieldName);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax GetCGRect (string libraryName, string fieldName) + => GetConstant (libraryName, fieldName); /// /// Generates a call for "Dlfcn.GetCGSize (libraryName, fieldName);"]; @@ -265,10 +472,17 @@ public static CompilationUnitSyntax GetCGRect (string libraryName, string symbol /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetCGSize (string libraryName, string fieldName) - => GetConstant ("GetCGSize", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetCGSize (string libraryName, string symbol, /*CGSize*/ string value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetCGSize (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetCGSize (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); /// /// Generates a call for "Dlfcn.GetDouble (libraryName, fieldName);"]; @@ -277,10 +491,17 @@ public static CompilationUnitSyntax SetCGSize (string libraryName, string symbol /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetDouble (string libraryName, string fieldName) - => GetConstant ("GetDouble", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetDouble (string libraryName, string symbol, double value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetDouble (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetDouble (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); /// /// Generates a call for "Dlfcn.GetFloat (libraryName, fieldName);"]; @@ -289,10 +510,17 @@ public static CompilationUnitSyntax SetDouble (string libraryName, string symbol /// The field name. /// A compilation unit with the desired Dlfcn call. public static CompilationUnitSyntax GetFloat (string libraryName, string fieldName) - => GetConstant ("GetFloat", libraryName, fieldName); + => GetConstant (libraryName, fieldName); - public static CompilationUnitSyntax SetFloat (IntPtr handle, string symbol, float value) - => throw new NotImplementedException (); + /// + /// Generates a call for "Dlfcn.SetFloat (libraryName, fieldName, value);"]; + /// + /// The library from where the field will be loaded. + /// The field name. + /// The name of the variable to get the value from. + /// A compilation unit with the desired Dlfcn call. + public static CompilationUnitSyntax SetFloat (string libraryName, string fieldName, string variableName) + => SetConstant (libraryName, fieldName, variableName); /// /// Generates a call for "Runtime.GetNSObject<nsobjectType> (Dlfcn.GetIndirect (libraryName, fieldName))!;"]; @@ -320,10 +548,6 @@ public static CompilationUnitSyntax GetNSObjectField (string nsObjectType, strin return GetNSObject (nsObjectType, getNSObjectArguments, suppressNullableWarning: true); } - public static CompilationUnitSyntax SetNSObject (string nsObjectType, string libraryName, string symbol, - string value) - => throw new NotImplementedException (); - public static CompilationUnitSyntax GetBlittableField (string blittableType, string libraryName, string fieldName) { var arguments = new SyntaxNodeOrToken [] { @@ -358,77 +582,139 @@ public static CompilationUnitSyntax GetBlittableField (string blittableType, str return compilationUnit; } - - public static CompilationUnitSyntax SetBlittableField (string nsObjectType, string libraryName, string fieldName, - string value) - => throw new NotImplementedException (); - /// - /// Returns the getter needed to access the native value exposed by a field property. The method will return the - /// Dflcn calls needed. + /// Returns a tuple with the getter and setter for a given field property. /// - /// A field property under code generation. - /// The appropriate Dlfcn call to retrieve the native value of a field property. - /// When the caller tries to generate the call for a no field property. - /// When the property type is not supported for a field property. - public static CompilationUnitSyntax FieldConstantGetter (in Property property) + /// The property whose getter and setter we want to generate. + /// A tuple with the syntax factory methods for the getters and setters. + /// When the property is not a field property. + /// When the return type of the property is not supported. + public static (Func Getter, + Func Setter) FieldConstantGetterSetter ( + in Property property) { // check if this is a field, if it is not, we have an issue with the code generator if (!property.IsField) throw new NotSupportedException ("Cannot retrieve getter for non field property."); - // retrieve all the necessary data from the info field of the property - var libraryName = property.ExportFieldData.Value.LibraryName; - var symbolName = property.ExportFieldData.Value.FieldData.SymbolName; + var fieldType = property.ReturnType.FullyQualifiedName; + var underlyingEnumType = property.ReturnType.EnumUnderlyingType.GetKeyword (); - if (property.ReturnType.IsNSObject) { - return property.ReturnType.Name == "Foundation.NSString" - ? GetStringConstant (libraryName, symbolName) - // all nsobjects are retrieved using the same generic getter - : GetNSObjectField (property.ReturnType.Name, libraryName, symbolName); + Func WrapGenericCall (string genericType, + Func genericCall) + { + return (libraryName, fieldName) => genericCall (genericType, libraryName, fieldName); + } + + Func WrapThrow () + { + return (_, _, _) => ThrowNotSupportedException ($"Setting fields of type '{fieldType}' is not supported."); + } + + Func WithCast (Func setterCall) + { + return (libraryName, fieldName, variableName) => + setterCall (libraryName, fieldName, variableName, underlyingEnumType); } // keep the formatting to make it more readable #pragma warning disable format + if (property.ReturnType.IsNSObject) { + return property.ReturnType switch { + { FullyQualifiedName: "Foundation.NSString" } => (Getter: GetStringConstant, Setter: SetString), + { FullyQualifiedName: "Foundation.NSArray" } => ( + Getter: WrapGenericCall (property.ReturnType.FullyQualifiedName, GetNSObjectField), + Setter: SetArray), + _ => ( + Getter: WrapGenericCall (property.ReturnType.FullyQualifiedName, GetNSObjectField), + Setter: SetObject) + }; + } + // use the return type and the special type of the property to decide what getter we are going to us return property.ReturnType switch { // special types - { Name: "CoreGraphics.CGSize" } => GetCGSize (libraryName, symbolName), - { Name: "CoreMedia.CMTag" } => GetStruct ("CoreMedia.CMTag", libraryName, symbolName), - { Name: "nfloat" } => GetNFloat (libraryName, symbolName), + { FullyQualifiedName: "CoreGraphics.CGSize" } => (Getter: GetCGSize, Setter: SetCGSize), + { FullyQualifiedName: "CoreMedia.CMTag" } => ( + Getter: WrapGenericCall ("CoreMedia.CMTag", GetStruct), + Setter: WrapThrow ()), + { FullyQualifiedName: "nfloat" } => (Getter: GetNFloat, Setter: SetNFloat), // Blittable types - { Name: "CoreMedia.CMTime" or "AVFoundation.AVCaptureWhiteBalanceGains" } - => GetBlittableField (property.ReturnType.Name, libraryName, symbolName), + { FullyQualifiedName: "CoreMedia.CMTime" or "AVFoundation.AVCaptureWhiteBalanceGains" } + => (Getter: WrapGenericCall (property.ReturnType.FullyQualifiedName, GetBlittableField), + Setter: WrapThrow ()), // enum types, decide based on its enum backing field, smart enums have to be done in the binding // manually - { IsEnum: true, EnumUnderlyingType: SpecialType.System_SByte } => GetSByte (libraryName, symbolName), - { IsEnum: true, EnumUnderlyingType: SpecialType.System_Byte } => GetByte (libraryName, symbolName), - { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int16 } => GetInt16 (libraryName, symbolName), - { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt16 } => GetUInt16 (libraryName, symbolName), - { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int32 } => GetInt32 (libraryName, symbolName), - { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt32 } => GetUInt32 (libraryName, symbolName), - { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int64 } => GetInt64 (libraryName, symbolName), - { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt64 } => GetUInt64 (libraryName, symbolName), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_SByte } => (Getter: GetSByte, Setter: WithCast (SetSByte)), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Byte } => (Getter: GetByte, Setter: WithCast (SetByte)), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int16 } => (Getter: GetInt16, Setter: WithCast (SetInt16)), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt16 } => (Getter: GetUInt16, Setter: WithCast (SetUInt16)), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int32 } => (Getter: GetInt32, Setter: WithCast (SetInt32)), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt32 } => (Getter: GetUInt32, Setter: WithCast (SetUInt32)), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int64 } => (Getter: GetInt64, Setter: WithCast (SetInt64)), + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt64 } => (Getter: GetUInt64, Setter: WithCast (SetUInt64)), // General special types - { SpecialType: SpecialType.System_SByte } => GetSByte (libraryName, symbolName), - { SpecialType: SpecialType.System_Byte } => GetByte (libraryName, symbolName), - { SpecialType: SpecialType.System_Int16 } => GetInt16 (libraryName, symbolName), - { SpecialType: SpecialType.System_UInt16 } => GetUInt16 (libraryName, symbolName), - { SpecialType: SpecialType.System_IntPtr } => GetIntPtr (libraryName, symbolName), - { SpecialType: SpecialType.System_Int32 } => GetInt32 (libraryName, symbolName), - { SpecialType: SpecialType.System_UIntPtr } => GetUIntPtr (libraryName, symbolName), - { SpecialType: SpecialType.System_UInt32 } => GetUInt32 (libraryName, symbolName), - { SpecialType: SpecialType.System_Int64 } => GetInt64 (libraryName, symbolName), - { SpecialType: SpecialType.System_UInt64 } => GetUInt64 (libraryName, symbolName), - { SpecialType: SpecialType.System_Double } => GetDouble (libraryName, symbolName), - { SpecialType: SpecialType.System_Single } => GetFloat (libraryName, symbolName), + { SpecialType: SpecialType.System_SByte } => (Getter: GetSByte, Setter: SetSByte), + { SpecialType: SpecialType.System_Byte } => (Getter: GetByte, Setter: SetByte), + { SpecialType: SpecialType.System_Int16 } => (Getter: GetInt16, Setter: SetInt16), + { SpecialType: SpecialType.System_UInt16 } => (Getter: GetUInt16, Setter: SetUInt16), + { SpecialType: SpecialType.System_IntPtr } => (Getter: GetIntPtr, Setter: SetIntPtr), + { SpecialType: SpecialType.System_Int32 } => (Getter: GetInt32, Setter: SetInt32), + { SpecialType: SpecialType.System_UIntPtr } => (Getter: GetUIntPtr, Setter: SetUIntPtr), + { SpecialType: SpecialType.System_UInt32 } => (Getter: GetUInt32, Setter: SetUInt32), + { SpecialType: SpecialType.System_Int64 } => (Getter: GetInt64, Setter: SetInt64), + { SpecialType: SpecialType.System_UInt64 } => (Getter: GetUInt64, Setter: SetUInt64), + { SpecialType: SpecialType.System_Double } => (Getter: GetDouble, Setter: SetDouble), + { SpecialType: SpecialType.System_Single } => (Getter: GetFloat, Setter: SetFloat), // We do not support the property _ => throw new NotImplementedException ($"Return type {property.ReturnType} is not implemented."), }; #pragma warning restore format } + + /// + /// Returns the getter needed to access the native value exposed by a field property. The method will return the + /// Dflcn calls needed. + /// + /// A field property under code generation. + /// The appropriate Dlfcn call to retrieve the native value of a field property. + /// When the caller tries to generate the call for a no field property. + /// When the property type is not supported for a field property. + public static CompilationUnitSyntax FieldConstantGetter (in Property property) + { + // check if this is a field, if it is not, we have an issue with the code generator + if (!property.IsField) + throw new NotSupportedException ("Cannot retrieve getter for non field property."); + + // retrieve all the necessary data from the info field of the property + var libraryName = property.ExportFieldData.Value.LibraryName; + var symbolName = property.ExportFieldData.Value.FieldData.SymbolName; + return FieldConstantGetterSetter (property).Getter (libraryName, symbolName); + } + + /// + /// Returns the setter needed to access the native value exposed by a field property. The method will return the + /// Dflcn calls needed. + /// + /// A field property under code generation. + /// The name of the variable that contains the value to set. + /// The appropriate Dlfcn call to retrieve the native value of a field property. + /// When the caller tries to generate the call for a no field property. + /// When the property type is not supported for a field property. + public static CompilationUnitSyntax FieldConstantSetter (in Property property, string variableName) + { + if (variableName is null) throw new ArgumentNullException (nameof (variableName)); + // check if this is a field, if it is not, we have an issue with the code generator + if (!property.IsField) + throw new NotSupportedException ("Cannot retrieve getter for non field property."); + + // retrieve all the necessary data from the info field of the property + var libraryName = property.ExportFieldData.Value.LibraryName; + var symbolName = property.ExportFieldData.Value.FieldData.SymbolName; + return FieldConstantGetterSetter (property).Setter (libraryName, symbolName, variableName); + } } diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs new file mode 100644 index 000000000000..bde51fd9c459 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs @@ -0,0 +1,766 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Generator.Extensions; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using TypeInfo = Microsoft.Macios.Generator.DataModel.TypeInfo; +using Parameter = Microsoft.Macios.Generator.DataModel.Parameter; + +namespace Microsoft.Macios.Generator.Emitters; + +static partial class BindingSyntaxFactory { + readonly static string objc_msgSend = "objc_msgSend"; + readonly static string objc_msgSendSuper = "objc_msgSendSuper"; + + /// + /// Returns the expression needed to cast a parameter to its native type. + /// + /// The parameter whose casting we need to generate. The type info has to be + /// and enum and be marked as native. If it is not, the method returns null + /// The cast C# expression. + internal static CastExpressionSyntax? CastToNative (in Parameter parameter) + { + // not an enum and not a native value. we cannot calculate the casting expression. + if (!parameter.Type.IsEnum || !parameter.Type.IsNativeEnum) + return null; + + // build a casting expression based on the marshall type of the typeinfo + var marshalType = parameter.Type.ToMarshallType (); + if (marshalType is null) + // cannot calculate the marshal, return null + return null; + + var enumBackingValue = parameter.Type.EnumUnderlyingType.Value.GetKeyword (); + var castExpression = CastExpression (IdentifierName (marshalType), // (IntPtr/UIntPtr) cast + CastExpression ( + IdentifierName (enumBackingValue), + IdentifierName (parameter.Name) + .WithLeadingTrivia (Space)) + .WithLeadingTrivia (Space)); // (backingfield) (variable) cast + return castExpression; + } + + /// + /// Returns the expression needed to cast an enum parameter to its primitive type to be used in marshaling. + /// + /// The parameter for which we need to generate the casting. The type info has to be + /// an enumerator. If it is not, the method returns null. + /// The cast C# expression. + internal static CastExpressionSyntax? CastToPrimitive (in Parameter parameter) + { + if (!parameter.Type.IsEnum) { + return null; + } + + if (parameter.Type.IsNativeEnum) { + // return the native casting + return CastToNative (parameter); + } + + // returns the enum primitive to be used + var marshalType = parameter.Type.ToMarshallType (); + if (marshalType is null) + return null; + + // (byte) parameter + var castExpression = CastExpression ( + type: IdentifierName (marshalType), + expression: IdentifierName (parameter.Name).WithLeadingTrivia (Space)); + return castExpression; + } + + /// + /// Returns the expression needed to cast a bool to a byte to be used in a native call. + /// + /// The parameter to cast. + /// A conditional expression that casts a bool to a byte. + internal static ConditionalExpressionSyntax? CastToByte (in Parameter parameter) + { + if (parameter.Type.SpecialType != SpecialType.System_Boolean) + return null; + // (byte) 1 + var castOne = CastExpression ( + PredefinedType (Token (SyntaxKind.ByteKeyword)), + LiteralExpression (SyntaxKind.NumericLiteralExpression, Literal (1)).WithLeadingTrivia (Space) + .WithTrailingTrivia (Space) + ); + // (byte) 0 + var castZero = CastExpression ( + PredefinedType (Token (SyntaxKind.ByteKeyword)), + LiteralExpression (SyntaxKind.NumericLiteralExpression, Literal (0)).WithLeadingTrivia (Space) + ).WithLeadingTrivia (Space); + + // with this exact space count + // foo ? (byte) 1 : (byte) 0 + return ConditionalExpression ( + condition: IdentifierName (parameter.Name).WithTrailingTrivia (Space), + whenTrue: castOne.WithLeadingTrivia (Space), + whenFalse: castZero); + } + + /// + /// Returns the aux nsarray variable for an array object. This method will do the following: + /// 1. Check if the object is nullable or not. + /// 2. Use the correct NSArray method depending on the content of the array. + /// + /// The parameter whose aux variable we want to generate. + /// If the using clause should be added to the declaration. + /// The variable declaration for the NSArray aux variable of the parameter. + internal static LocalDeclarationStatementSyntax? GetNSArrayAuxVariable (in Parameter parameter, + bool withUsing = false) + { + if (!parameter.Type.IsArray) + return null; + var nsArrayFactoryMethod = parameter.Type.Name switch { + "string" => "FromStrings", + _ => "FromNSObjects" // the general assumption is that we are working with nsobjects unless we have a bind form + }; + // syntax that calls the NSArray factory method using the parameter: NSArray.FromNSObjects (targetTensors); + var factoryInvocation = InvocationExpression (MemberAccessExpression (SyntaxKind.SimpleMemberAccessExpression, + IdentifierName ("NSArray"), IdentifierName (nsArrayFactoryMethod).WithTrailingTrivia (Space))) + .WithArgumentList ( + ArgumentList (SingletonSeparatedList ( + Argument (IdentifierName (parameter.Name))))); + + // variable name + var variableName = parameter.GetNameForVariableType (Parameter.VariableType.NSArray); + if (variableName is null) + return null; + var declarator = VariableDeclarator (Identifier (variableName)); + // we have the basic constructs, now depending on if the variable is nullable or not, we need to write the initializer + if (parameter.Type.IsNullable) { + // writes the param ? null : NSArray expression + var nullCheck = ConditionalExpression ( + IsPatternExpression ( + IdentifierName (parameter.Name).WithLeadingTrivia (Space).WithTrailingTrivia (Space), + ConstantPattern (LiteralExpression (SyntaxKind.NullLiteralExpression).WithLeadingTrivia (Space) + .WithTrailingTrivia (Space))), + LiteralExpression ( + SyntaxKind.NullLiteralExpression).WithLeadingTrivia (Space).WithTrailingTrivia (Space), + factoryInvocation.WithLeadingTrivia (Space)); + + // translates to = x ? null : NSArray.FromNSObject (parameterName), notice we added the '=' here + declarator = declarator.WithInitializer (EqualsValueClause (nullCheck).WithLeadingTrivia (Space)); + } else { + // translates to = NSArray.FromNSObject (parameterName); + declarator = declarator.WithInitializer (EqualsValueClause (factoryInvocation.WithLeadingTrivia (Space)) + .WithLeadingTrivia (Space)); + } + + // complicated way to write 'var auxVariableName = ' + var variableDeclaration = VariableDeclaration (IdentifierName ( + Identifier (TriviaList (), SyntaxKind.VarKeyword, "var", "var", TriviaList ()))) + .WithTrailingTrivia (Space) + .WithVariables (SingletonSeparatedList (declarator)); + var statement = LocalDeclarationStatement (variableDeclaration); + // add using if requested + return withUsing + ? statement.WithUsingKeyword (Token (SyntaxKind.UsingKeyword).WithTrailingTrivia (Space)) + : statement; + } + + /// + /// Returns the aux variable for a handle object. This method will do the following: + /// 1. Check if the object is nullable or not. + /// 2. Use the correct GetHandle method depending on the content of the object. + /// + internal static LocalDeclarationStatementSyntax? GetHandleAuxVariable (in Parameter parameter, + bool withNullAllowed = false) + { + if (!parameter.Type.IsNSObject && !parameter.Type.IsINativeObject) + return null; + + var variableName = parameter.GetNameForVariableType (Parameter.VariableType.Handle); + if (variableName is null) + return null; + // decide about the factory based on the need of a null check + InvocationExpressionSyntax factoryInvocation; + if (withNullAllowed) { + // generates: zone!.GetNonNullHandle (nameof (zone)); + factoryInvocation = InvocationExpression ( + MemberAccessExpression (SyntaxKind.SimpleMemberAccessExpression, + PostfixUnaryExpression ( + SyntaxKind.SuppressNullableWarningExpression, + IdentifierName (parameter.Name)), + IdentifierName ("GetNonNullHandle").WithTrailingTrivia (Space))) + .WithArgumentList (ArgumentList ( + SingletonSeparatedList (Argument ( + InvocationExpression ( + IdentifierName (Identifier (TriviaList (Space), SyntaxKind.NameOfKeyword, "nameof", + "nameof", + TriviaList (Space)))) + .WithArgumentList (ArgumentList ( + SingletonSeparatedList ( + Argument (IdentifierName (parameter.Name))))))))); + } else { + // generates: zone.GetHandle (); + factoryInvocation = InvocationExpression ( + MemberAccessExpression (SyntaxKind.SimpleMemberAccessExpression, + IdentifierName (parameter.Name), + IdentifierName ("GetHandle").WithTrailingTrivia (Space))); + } + + // generates: variable = {FactoryCall} + var declarator = VariableDeclarator (Identifier (variableName)) + .WithInitializer (EqualsValueClause (factoryInvocation.WithLeadingTrivia (Space)) + .WithLeadingTrivia (Space)); + // generates the final statement: + // var x = zone.GetHandle (); + // or + // var x = zone!.GetNonNullHandle (nameof (constantValues)); + return LocalDeclarationStatement ( + VariableDeclaration ( + IdentifierName ( + Identifier ( + TriviaList (), + SyntaxKind.VarKeyword, + "var", + "var", + TriviaList ()))).WithVariables ( + SingletonSeparatedList (declarator.WithLeadingTrivia (Space)) + )); + } + + internal static LocalDeclarationStatementSyntax? GetStringAuxVariable (in Parameter parameter) + { + if (parameter.Type.Name != "string") + return null; + + var variableName = parameter.GetNameForVariableType (Parameter.VariableType.NSString); + if (variableName is null) + return null; + + // generates: CFString.CreateNative ({parameter.Name}); + var cfstringFactoryInvocation = InvocationExpression ( + MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName ("CFString"), + IdentifierName ("CreateNative").WithTrailingTrivia (Space)) + ) + .WithArgumentList (ArgumentList (SingletonSeparatedList ( + Argument (IdentifierName (parameter.Name))))); + + // generates {var} = CFString.CreateNative ({parameter.Name}); + var declarator = + VariableDeclarator (Identifier (variableName).WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithInitializer (EqualsValueClause (cfstringFactoryInvocation.WithLeadingTrivia (Space))); + + + // put everythign together + var declaration = VariableDeclaration (IdentifierName (Identifier ( + TriviaList (), SyntaxKind.VarKeyword, "var", "var", TriviaList ()))) + .WithVariables (SingletonSeparatedList (declarator)); + + return LocalDeclarationStatement (declaration); + } + + internal static LocalDeclarationStatementSyntax? GetNSNumberAuxVariable (in Parameter parameter) + { + // the BindFrom attribute with a nsnumber supports the following types: + // - bool + // - byte + // - double + // - float + // - short + // - int + // - long + // - sbyte + // - ushort + // - uint + // - ulong + // - nfloat + // - nint + // - nuint + // - Enums: this are simply casted to their backing representation + // if we do not match the expected type, return null + + // make sure that the parameter type is valid and return the required method for the nsnumber variable +#pragma warning disable format + var factoryMethod = parameter.Type switch { + { Name: "nint" } => "FromNInt", + { Name: "nuint" } => "FromNUInt", + { Name: "nfloat" or "NFloat" } => "FromNFloat", + { IsEnum: true, IsSmartEnum: true } => null, // we do not support smart enums, there is a special case for them + { IsEnum: true, EnumUnderlyingType: SpecialType.System_SByte } => "FromSByte", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Byte } => "FromByte", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int16 } => "FromInt16", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt16 } => "FromUInt16", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int32 } => "FromInt32", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt32 } => "FromUInt32", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int64 } => "FromInt64", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt64 } => "FromUInt64", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_IntPtr } => "FromNint", + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UIntPtr } => "FromNUint", + { SpecialType: SpecialType.System_Boolean } => "FromBoolean", + { SpecialType: SpecialType.System_Byte } => "FromByte", + { SpecialType: SpecialType.System_Double } => "FromDouble", + { SpecialType: SpecialType.System_Single } => "FromFloat", + { SpecialType: SpecialType.System_Int16 } => "FromInt16", + { SpecialType: SpecialType.System_Int32 } => "FromInt32", + { SpecialType: SpecialType.System_Int64 } => "FromInt64", + { SpecialType: SpecialType.System_SByte } => "FromSByte", + { SpecialType: SpecialType.System_UInt16 } => "FromUInt16", + { SpecialType: SpecialType.System_UInt32 } => "FromUInt32", + { SpecialType: SpecialType.System_UInt64 } => "FromUInt64", + { SpecialType: SpecialType.System_IntPtr } => "FromNint", + { SpecialType: SpecialType.System_UIntPtr } => "FromNUint", + _ => null, + }; +#pragma warning restore format + + if (factoryMethod is null) + return null; + + var variableName = parameter.GetNameForVariableType (Parameter.VariableType.BindFrom); + if (variableName is null) + return null; + + // generates: NSNumber.FromDouble + var factoryInvocation = InvocationExpression ( + MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName ("NSNumber"), + IdentifierName (factoryMethod).WithTrailingTrivia (Space)) + ); + + // the arguments of the factory information depends on if we are dealing with a enum, in which case we cast + // or not, in which case we just add the arguments + if (parameter.Type.IsEnum) { + // generates: NSNumber.FromDouble ((int)value); + factoryInvocation = factoryInvocation + .WithArgumentList (ArgumentList (SingletonSeparatedList (Argument ( + CastExpression ( + IdentifierName (parameter.Type.EnumUnderlyingType.GetKeyword () ?? ""), + IdentifierName (parameter.Name).WithLeadingTrivia (Space)))))); + } else { + // generates: NSNumber.FromDouble (value); + factoryInvocation = factoryInvocation + .WithArgumentList (ArgumentList (SingletonSeparatedList ( + Argument (IdentifierName (parameter.Name))))); + } + + var declarator = + VariableDeclarator (Identifier (variableName).WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithInitializer (EqualsValueClause (factoryInvocation.WithLeadingTrivia (Space))); + + // generats: var nba_variable = NSNumber.FromDouble(value); + var declaration = VariableDeclaration (IdentifierName (Identifier ( + TriviaList (), SyntaxKind.VarKeyword, "var", "var", TriviaList ()))) + .WithVariables (SingletonSeparatedList (declarator)); + + return LocalDeclarationStatement (declaration); + } + + internal static LocalDeclarationStatementSyntax? GetNSValueAuxVariable (in Parameter parameter) + { + + // the BindFrom attribute with a nsvalue supports the following types: + // - CGAffineTransform + // - NSRange + // - CGVector + // - SCNMatrix4 + // - CLLocationCoordinate2D + // - SCNVector3 + // - SCNVector4 + // - CGPoint / PointF + // - CGRect / RectangleF + // - CGSize / SizeF + // - UIEdgeInsets + // - UIOffset + // - MKCoordinateSpan + // - CMTimeRange + // - CMTime + // - CMTimeMapping + // - CATransform3D + var t = parameter.Type.Name; + +#pragma warning disable format + // get the factory method based on the parameter type, if it is not found, return null + var factoryMethod = parameter.Type switch { + { FullyQualifiedName: "CoreGraphics.CGAffineTransform" } => "FromCGAffineTransform", + { FullyQualifiedName: "Foundation.NSRange" } => "FromRange", + { FullyQualifiedName: "CoreGraphics.CGVector" } => "FromCGVector", + { FullyQualifiedName: "SceneKit.SCNMatrix4" } => "FromSCNMatrix4", + { FullyQualifiedName: "CoreLocation.CLLocationCoordinate2D" } => "FromMKCoordinate", + { FullyQualifiedName: "SceneKit.SCNVector3" } => "FromVector", + { FullyQualifiedName: "SceneKit.SCNVector4" } => "FromVector", + { FullyQualifiedName: "CoreGraphics.CGPoint" } => "FromCGPoint", + { FullyQualifiedName: "CoreGraphics.CGRect" } => "FromCGRect", + { FullyQualifiedName: "CoreGraphics.CGSize" } => "FromCGSize", + { FullyQualifiedName: "UIKit.UIEdgeInsets" } => "FromUIEdgeInsets", + { FullyQualifiedName: "UIKit.UIOffset" } => "FromUIOffset", + { FullyQualifiedName: "MapKit.MKCoordinateSpan" } => "FromMKCoordinateSpan", + { FullyQualifiedName: "CoreMedia.CMTimeRange" } => "FromCMTimeRange", + { FullyQualifiedName: "CoreMedia.CMTime" } => "FromCMTime", + { FullyQualifiedName: "CoreMedia.CMTimeMapping" } => "FromCMTimeMapping", + { FullyQualifiedName: "CoreAnimation.CATransform3D" } => "FromCATransform3D", + _ => null, + }; +#pragma warning restore format + + if (factoryMethod is null) + return null; + + var variableName = parameter.GetNameForVariableType (Parameter.VariableType.BindFrom); + if (variableName is null) + return null; + + // generates: NSValue.FromCMTime + var factoryInvocation = InvocationExpression ( + MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName ("NSValue"), + IdentifierName (factoryMethod).WithTrailingTrivia (Space)) + ).WithArgumentList (ArgumentList (SingletonSeparatedList ( + Argument (IdentifierName (parameter.Name))))); + + var declarator = + VariableDeclarator (Identifier (variableName).WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithInitializer (EqualsValueClause (factoryInvocation.WithLeadingTrivia (Space))); + + // generats: var nba_variable = NSNumber.FromDouble(value); + var declaration = VariableDeclaration (IdentifierName (Identifier ( + TriviaList (), SyntaxKind.VarKeyword, "var", "var", TriviaList ()))) + .WithVariables (SingletonSeparatedList (declarator)); + + return LocalDeclarationStatement (declaration); + } + + internal static LocalDeclarationStatementSyntax? GetNSStringSmartEnumAuxVariable (in Parameter parameter) + { + if (!parameter.Type.IsSmartEnum) + return null; + + var variableName = parameter.GetNameForVariableType (Parameter.VariableType.BindFrom); + if (variableName is null) + return null; + + // smart enums are very simple to do, we need to call the GetConstant that was generated as an extension + // method + var factoryInvocation = InvocationExpression ( + MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName (parameter.Name), + IdentifierName ("GetConstant").WithTrailingTrivia (Space)) + ); + + var declarator = + VariableDeclarator (Identifier (variableName).WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithInitializer (EqualsValueClause (factoryInvocation.WithLeadingTrivia (Space))); + + // generats: var nba_variable = NSNumber.FromDouble(value); + var declaration = VariableDeclaration (IdentifierName (Identifier ( + TriviaList (), SyntaxKind.VarKeyword, "var", "var", TriviaList ()))) + .WithVariables (SingletonSeparatedList (declarator)); + + return LocalDeclarationStatement (declaration); + } + + internal static LocalDeclarationStatementSyntax? GetNSArrayBindFromAuxVariable (in Parameter parameter) + { + // we can only work with parameters that are an array + if (!parameter.Type.IsArray) + return null; + + var variableName = parameter.GetNameForVariableType (Parameter.VariableType.BindFrom); + if (variableName is null) + return null; + + // use a switch to decide which of the constructors we are going to use to build the array. + var lambdaFunctionVariable = "obj"; + var nsNumberExpr = ObjectCreationExpression ( + IdentifierName ("NSNumber").WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithArgumentList (ArgumentList (SingletonSeparatedList ( + Argument (IdentifierName (lambdaFunctionVariable))))); + var nsValueExpr = ObjectCreationExpression ( + IdentifierName ("NSValue").WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithArgumentList (ArgumentList (SingletonSeparatedList ( + Argument (IdentifierName (lambdaFunctionVariable))))); + var smartEnumExpr = InvocationExpression (MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName (lambdaFunctionVariable).WithLeadingTrivia (Space), + IdentifierName ("GetConstant"))); + +#pragma warning disable format + ExpressionSyntax? constructor = parameter.Type switch { + // smart enums + { IsEnum: true, IsSmartEnum: true } => smartEnumExpr, + // NSNumber types: + { Name: "nint" } => nsNumberExpr, + { Name: "nuint" } => nsNumberExpr, + { Name: "nfloat" or "NFloat" } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_SByte } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Byte } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int16 } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt16 } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int32 } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt32 } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_Int64 } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UInt64 } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_IntPtr } => nsNumberExpr, + { IsEnum: true, EnumUnderlyingType: SpecialType.System_UIntPtr } => nsNumberExpr, + { SpecialType: SpecialType.System_Boolean } => nsNumberExpr, + { SpecialType: SpecialType.System_Byte } => nsNumberExpr, + { SpecialType: SpecialType.System_Double } => nsNumberExpr, + { SpecialType: SpecialType.System_Single } => nsNumberExpr, + { SpecialType: SpecialType.System_Int16 } => nsNumberExpr, + { SpecialType: SpecialType.System_Int32 } => nsNumberExpr, + { SpecialType: SpecialType.System_Int64 } => nsNumberExpr, + { SpecialType: SpecialType.System_SByte } => nsNumberExpr, + { SpecialType: SpecialType.System_UInt16 } => nsNumberExpr, + { SpecialType: SpecialType.System_UInt32 } => nsNumberExpr, + { SpecialType: SpecialType.System_UInt64 } => nsNumberExpr, + { SpecialType: SpecialType.System_IntPtr } => nsNumberExpr, + { SpecialType: SpecialType.System_UIntPtr } => nsNumberExpr, + // NSValue related types: + { FullyQualifiedName: "CoreGraphics.CGAffineTransform" } => nsValueExpr, + { FullyQualifiedName: "Foundation.NSRange" } => nsValueExpr, + { FullyQualifiedName: "CoreGraphics.CGVector" } => nsValueExpr, + { FullyQualifiedName: "SceneKit.SCNMatrix4" } => nsValueExpr, + { FullyQualifiedName: "CoreLocation.CLLocationCoordinate2D" } => nsValueExpr, + { FullyQualifiedName: "SceneKit.SCNVector3" } => nsValueExpr, + { FullyQualifiedName: "SceneKit.SCNVector4" } => nsValueExpr, + { FullyQualifiedName: "CoreGraphics.CGPoint" } => nsValueExpr, + { FullyQualifiedName: "CoreGraphics.CGRect" } => nsValueExpr, + { FullyQualifiedName: "CoreGraphics.CGSize" } => nsValueExpr, + { FullyQualifiedName: "UIKit.UIEdgeInsets" } => nsValueExpr, + { FullyQualifiedName: "UIKit.UIOffset" } => nsValueExpr, + { FullyQualifiedName: "MapKit.MKCoordinateSpan" } => nsNumberExpr, + { FullyQualifiedName: "CoreMedia.CMTimeRange" } => nsNumberExpr, + { FullyQualifiedName: "CoreMedia.CMTime" } => nsValueExpr, + { FullyQualifiedName: "CoreMedia.CMTimeMapping" } => nsValueExpr, + { FullyQualifiedName: "CoreAnimation.CATransform3D" } => nsValueExpr, + _ => null + }; +#pragma warning restore format + + if (constructor is null) + return null; + // generates: + // obj => new NSNumber (obj); + // obj => new NSValue (obj); + // obj => obj.GetValue (); + var lambdaExpression = SimpleLambdaExpression (Parameter (Identifier (lambdaFunctionVariable).WithTrailingTrivia (Space))) + .WithExpressionBody (constructor.WithLeadingTrivia (Space)); + + // generate: NSArray.FromNSObjects (o => new NSNumber (o), shape); + var factoryInvocation = InvocationExpression (MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName ("NSArray"), + IdentifierName ("FromNSObjects").WithTrailingTrivia (Space))).WithArgumentList ( + ArgumentList ( + SeparatedList ( + new SyntaxNodeOrToken [] { + Argument (lambdaExpression), + Token (SyntaxKind.CommaToken), + Argument (IdentifierName (parameter.Name).WithLeadingTrivia (Space)) + }))); + + var declarator = + VariableDeclarator (Identifier (variableName).WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithInitializer (EqualsValueClause (factoryInvocation.WithLeadingTrivia (Space))); + + var declaration = VariableDeclaration (IdentifierName (Identifier ( + TriviaList (), SyntaxKind.VarKeyword, "var", "var", TriviaList ()))) + .WithVariables (SingletonSeparatedList (declarator)); + + return LocalDeclarationStatement (declaration); + } + + /// + /// Returns the aux variable declaration needed when a parameter has the BindFrom attribute. + /// + /// The parameter whose aux variable we want to declare. + /// The syntax declaration of the aux variable or null if it could not be generated. + internal static LocalDeclarationStatementSyntax? GetBindFromAuxVariable (in Parameter parameter) + { + if (parameter.BindAs is null) + return null; + +#pragma warning disable format + // based on the bindas type call one of the helper factory methods + return (Type: parameter.BindAs.Value.Type, IsArray: parameter.Type.IsArray) switch { + { IsArray: true } => GetNSArrayBindFromAuxVariable (parameter), + { Type: "Foundation.NSNumber" } => GetNSNumberAuxVariable (parameter), + { Type: "Foundation.NSValue" } => GetNSValueAuxVariable (parameter), + { Type: "Foundation.NSString" } => GetNSStringSmartEnumAuxVariable(parameter), + _ => null, + }; +#pragma warning restore format + } + + /// + /// Generate the definition for an autorelease pool to wrap a method/property call. + /// + /// The variable declaration for a auto release pool. + internal static LocalDeclarationStatementSyntax GetAutoreleasePoolVariable () + { + const string poolVariableName = "autorelease_pool"; + // object creation + var create = + ObjectCreationExpression ( + IdentifierName ("NSAutoreleasePool").WithLeadingTrivia (Space).WithTrailingTrivia (Space)) + .WithArgumentList (ArgumentList ()); + + // return the autorelease pool definition + var declarator = VariableDeclarator (Identifier (poolVariableName)); + declarator = declarator.WithInitializer (EqualsValueClause (create.WithLeadingTrivia (Space)) + .WithLeadingTrivia (Space)); + + var variableDeclaration = VariableDeclaration (IdentifierName ( + Identifier (TriviaList (), SyntaxKind.VarKeyword, "var", "var", TriviaList ()))) + .WithTrailingTrivia (Space) + .WithVariables (SingletonSeparatedList (declarator)); + + return LocalDeclarationStatement (variableDeclaration); + } + + /// + /// Generate the method that will check the ui thread based on the platform. + /// + /// The platform targeted in the compilation. + /// The correct expression to check if the code is executing in the UI thread. + internal static ExpressionStatementSyntax? EnsureUiThread (PlatformName platform) + { + (string Namespace, string Classname)? caller = platform switch { + PlatformName.iOS => ("UIKit", "UIApplication"), + PlatformName.TvOS => ("UIKit", "UIApplication"), + PlatformName.MacCatalyst => ("UIKit", "UIApplication"), + PlatformName.MacOSX => ("AppKit", "NSApplication"), + _ => null + }; + if (caller is null) + return null; + + return ExpressionStatement (InvocationExpression (MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName (caller.Value.Namespace), + IdentifierName (caller.Value.Classname)), + IdentifierName ("EnsureUIThread").WithTrailingTrivia (Space)))); + } + + /// + /// Generate the declaration needed for the exception marhsaling. + /// + /// The local declaration needed for the exception marshaling. + internal static LocalDeclarationStatementSyntax GetExceptionHandleAuxVariable () + { + const string handleVariableName = "exception_gchandle"; + const string intPtr = "IntPtr"; + // object creation + var zeroPtr = MemberAccessExpression ( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName (intPtr), + IdentifierName ("Zero")); + + var declarator = VariableDeclarator (Identifier (handleVariableName)) + .WithInitializer (EqualsValueClause (zeroPtr)); + + return LocalDeclarationStatement ( + VariableDeclaration (IdentifierName (intPtr)) + .WithVariables (SingletonSeparatedList (declarator))) + .NormalizeWhitespace (); // no special mono style + } + + static string? GetObjCMessageSendMethodName (ExportData exportData, + TypeInfo returnType, ImmutableArray parameters, bool isSuper = false, bool isStret = false) + where T : Enum + { + var flags = exportData.Flags; + if (flags is null) + // flags are not set, should be a bug, but we will return null + return null; + + // the name of the objcSend method is calculated in the following way + // {CustomMarshallPrefix}_{MarshallTypeOfReturnType}_{objcSendMsg}{stret?_stret}_{string.Join('_', MarshallTypeArgs)}{nativeException?_exception}{CustomMarsahllPostfix} + // we will use a sb to make things easy to follow + var sb = new StringBuilder (); + + // first, decide if the user created a custom marshalling by checking the flags of the export data + CustomMarshalDirective? customMarshalDirective = null; + if (flags.HasCustomMarshalDirective ()) { + customMarshalDirective = exportData.ToCustomMarshalDirective (); + } + + if (customMarshalDirective?.NativePrefix is not null) { + sb.Append (customMarshalDirective.NativePrefix); + } else if (flags.HasMarshalNativeExceptions ()) { + sb.Append ("xamarin_"); + } + + // return types do not have a reference kind + sb.Append (returnType.ToMarshallType ()); + sb.Append ('_'); + // append the msg method based if it is for super or not, do not append '_' intimidatingly, since if we do + // not have parameters, we are done + sb.Append (isSuper ? objc_msgSendSuper : objc_msgSend); + if (isStret) { + sb.Append ("_stret"); + } + + // loop over params and get their native handler name + if (parameters.Length > 0) { + sb.Append ('_'); + sb.AppendJoin ('_', parameters.Select (p => p.Type.ToMarshallType ())); + } + + // check if we do have a custom marshall exception set for the export + + // check any possible custom postfix naming + if (customMarshalDirective?.NativeSuffix is not null) { + sb.Append (customMarshalDirective.NativeSuffix); + } else if (flags.HasMarshalNativeExceptions ()) { + sb.Append ("_exception"); + } + + return sb.ToString (); + } + + public static (string? Getter, string? Setter) GetObjCMessageSendMethods (in Property property, + bool isSuper = false, bool isStret = false) + { + if (property.IsProperty) { + // the getter and the setter depend of the accessors that have been set for the property, we do not want + // to calculate things that we won't use. The export data used will also depend if the getter/setter has a + // export attribute attached + var getter = property.GetAccessor (AccessorKind.Getter); + string? getterMsgSend = null; + if (getter is not null) { + var getterExportData = getter.Value.ExportPropertyData ?? property.ExportPropertyData; + if (getterExportData is not null) { + getterMsgSend = GetObjCMessageSendMethodName (getterExportData.Value, property.ReturnType, [], + isSuper, isStret); + } + } + + var setter = property.GetAccessor (AccessorKind.Setter); + string? setterMsgSend = null; + if (setter is not null) { + var setterExportData = setter.Value.ExportPropertyData ?? property.ExportPropertyData; + if (setterExportData is not null) { + setterMsgSend = GetObjCMessageSendMethodName (setterExportData.Value, TypeInfo.Void, + [property.ValueParameter], isSuper, isStret); + } + } + + return (Getter: getterMsgSend, Setter: setterMsgSend); + } + + return default; + } + + public static string? GetObjCMessageSendMethod (in Method method, bool isSuper = false, bool isStret = false) + => GetObjCMessageSendMethodName (method.ExportMethodData, method.ReturnType, method.Parameters, isSuper, + isStret); +} diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.cs index d7cd1f070103..64baf71f0e72 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.cs @@ -4,11 +4,13 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.DataModel; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.Macios.Generator.Emitters; static partial class BindingSyntaxFactory { + /// /// Returns an argument syntax for the provided kind and literal expression. /// @@ -21,7 +23,7 @@ static ArgumentSyntax GetLiteralExpressionArgument (SyntaxKind kind, string lite } static CompilationUnitSyntax StaticInvocationExpression (string staticClassName, string methodName, - SyntaxNodeOrToken [] argumentList) + SyntaxNodeOrToken [] argumentList, bool suppressNullableWarning = false) { var invocation = InvocationExpression ( MemberAccessExpression ( @@ -34,7 +36,10 @@ static CompilationUnitSyntax StaticInvocationExpression (string staticClassName, var compilationUnit = CompilationUnit ().WithMembers ( SingletonList ( GlobalStatement ( - ExpressionStatement (invocation)))); + ExpressionStatement ( + suppressNullableWarning + ? PostfixUnaryExpression (SyntaxKind.SuppressNullableWarningExpression, invocation) + : invocation)))); return compilationUnit; } @@ -65,4 +70,51 @@ static CompilationUnitSyntax StaticInvocationGenericExpression (string staticCla )))); return compilationUnit; } + + static CompilationUnitSyntax ThrowException (string type, string message) + { + var argumentList = ArgumentList (SingletonSeparatedList ( + GetLiteralExpressionArgument (SyntaxKind.StringLiteralExpression, message) + )).WithLeadingTrivia (Space); + + var throwExpression = ThrowStatement ( + ObjectCreationExpression (IdentifierName (type)) + .WithArgumentList (argumentList)).NormalizeWhitespace (); + + return CompilationUnit ().WithMembers ( + SingletonList ( + GlobalStatement (throwExpression))); + } + + static CompilationUnitSyntax ThrowNotSupportedException (string message) + => ThrowException (type: "NotSupportedException", message: message); + + /// + /// Generates the syntax to declare the variable used by a field property. + /// + /// The field property whose backing variable we want to generate. + /// The variable declaration syntax. + public static CompilationUnitSyntax FieldPropertyBackingVariable (in Property property) + { + var variableType = property.ReturnType.FullyQualifiedName; + if (property.ReturnType.SpecialType is SpecialType.System_IntPtr or SpecialType.System_UIntPtr + && property.ReturnType.MetadataName is not null) { + variableType = property.ReturnType.MetadataName; + } + var compilationUnit = CompilationUnit ().WithMembers ( + SingletonList ( + FieldDeclaration ( + VariableDeclaration ( + property.IsReferenceType // nullable only for reference types + ? NullableType (IdentifierName (variableType)) + : IdentifierName (variableType) + ) + .WithVariables ( + SingletonSeparatedList ( + VariableDeclarator ( + Identifier (property.BackingField))))) + .WithModifiers (TokenList (Token (SyntaxKind.StaticKeyword))))) // fields are static variables + .NormalizeWhitespace (); + return compilationUnit; + } } diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/CategoryEmitter.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/CategoryEmitter.cs index 062ffb944468..d26f286a65c2 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/CategoryEmitter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/CategoryEmitter.cs @@ -10,7 +10,7 @@ namespace Microsoft.Macios.Generator.Emitters; class CategoryEmitter : ICodeEmitter { - public string GetSymbolName (in CodeChanges codeChanges) => string.Empty; + public string GetSymbolName (in Binding binding) => string.Empty; public IEnumerable UsingStatements => []; public bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out ImmutableArray? diagnostics) { diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/ClassEmitter.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/ClassEmitter.cs index a683f06ca5c9..8e287d1db360 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/ClassEmitter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/ClassEmitter.cs @@ -1,20 +1,25 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Context; using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Generator.Formatters; +using Microsoft.Macios.Generator.IO; using ObjCBindings; +using Property = Microsoft.Macios.Generator.DataModel.Property; +using static Microsoft.Macios.Generator.Emitters.BindingSyntaxFactory; namespace Microsoft.Macios.Generator.Emitters; class ClassEmitter : ICodeEmitter { - public string GetSymbolName (in CodeChanges codeChanges) => codeChanges.Name; + public string GetSymbolName (in Binding binding) => binding.Name; public IEnumerable UsingStatements => [ "System", @@ -29,13 +34,13 @@ class ClassEmitter : ICodeEmitter { ]; - void EmitDefaultConstructors (in BindingContext bindingContext, TabbedStringBuilder classBlock, bool disableDefaultCtor) + void EmitDefaultConstructors (in BindingContext bindingContext, TabbedWriter classBlock, bool disableDefaultCtor) { if (!disableDefaultCtor) { classBlock.AppendGeneratedCodeAttribute (); classBlock.AppendDesignatedInitializer (); - classBlock.AppendRaw ( + classBlock.WriteRaw ( $@"[Export (""init"")] public {bindingContext.Changes.Name} () : base (NSObjectFlag.Empty) {{ @@ -45,17 +50,101 @@ void EmitDefaultConstructors (in BindingContext bindingContext, TabbedStringBuil InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.Selector.GetHandle (""init"")), ""init""); }} "); - classBlock.AppendLine (); + classBlock.WriteLine (); } classBlock.AppendGeneratedCodeAttribute (); classBlock.AppendEditorBrowsableAttribute (EditorBrowsableState.Advanced); - classBlock.AppendLine ($"protected {bindingContext.Changes.Name} (NSObjectFlag t) : base (t) {{}}"); + classBlock.WriteLine ($"protected {bindingContext.Changes.Name} (NSObjectFlag t) : base (t) {{}}"); - classBlock.AppendLine (); + classBlock.WriteLine (); classBlock.AppendGeneratedCodeAttribute (); classBlock.AppendEditorBrowsableAttribute (EditorBrowsableState.Advanced); - classBlock.AppendLine ($"protected internal {bindingContext.Changes.Name} (NativeHandle handle) : base (handle) {{}}"); + classBlock.WriteLine ($"protected internal {bindingContext.Changes.Name} (NativeHandle handle) : base (handle) {{}}"); + } + + /// + /// Emit the code for all the field properties in the class. The code will add any necessary backing fields and + /// will return all properties that are notifications. + /// + /// The current class name. + /// All properties of the class, the method will filter those that are fields. + /// Current class block. + /// An immutable array with all the properties that are marked as notifications + /// and that need a helper class to be generated. + void EmitFields (string className, in ImmutableArray properties, TabbedWriter classBlock, + out ImmutableArray notificationProperties) + { + var notificationsBuilder = ImmutableArray.CreateBuilder (); + foreach (var property in properties.OrderBy (p => p.Name)) { + if (!property.IsField) + continue; + + classBlock.WriteLine (); + // a field should always have a getter, if it does not, we do not generate the property + var getter = property.GetAccessor (AccessorKind.Getter); + if (getter is null) + continue; + + // provide a backing variable for the property if and only if we are dealing with a reference type + if (property.IsReferenceType) { + classBlock.WriteLine (FieldPropertyBackingVariable (property).ToString ()); + } + + classBlock.WriteLine (); + classBlock.AppendMemberAvailability (property.SymbolAvailability); + classBlock.AppendGeneratedCodeAttribute (optimizable: true); + if (property.IsNotification) { + // add it to the bucket so that we can later generate the necessary partial class for the + // notifications + notificationsBuilder.Add (property); + classBlock.AppendNotificationAdvice (className, property.Name); + } + + using (var propertyBlock = classBlock.CreateBlock (property.ToDeclaration ().ToString (), block: true)) { + // generate the accessors, we will always have a get, a set is optional depending on the type + // if the symbol availability of the accessor is different of the one from the property, write it + var backingField = property.BackingField; + + // be very verbose with the availability, makes the life easier to the dotnet analyzer + propertyBlock.AppendMemberAvailability (getter.Value.SymbolAvailability); + using (var getterBlock = propertyBlock.CreateBlock ("get", block: true)) { + // fields with a reference type have a backing fields, while value types do not + if (property.IsReferenceType) { + getterBlock.WriteRaw ( +$@"if ({backingField} is null) + {backingField} = {FieldConstantGetter (property)} +return {backingField}; +"); + } else { + // directly return the call from the getter + getterBlock.WriteLine ($"return {FieldConstantGetter (property)}"); + } + } + + var setter = property.GetAccessor (AccessorKind.Setter); + if (setter is null) + // we are done with the current property + continue; + + propertyBlock.WriteLine (); // add space between getter and setter since we have the attrs + propertyBlock.AppendMemberAvailability (setter.Value.SymbolAvailability); + using (var setterBlock = propertyBlock.CreateBlock ("set", block: true)) { + if (property.IsReferenceType) { + // set the backing field + setterBlock.WriteLine ($"{backingField} = value;"); + } + // call the native code + setterBlock.WriteLine ($"{FieldConstantSetter (property, "value")}"); + } + } + } + notificationProperties = notificationsBuilder.ToImmutable (); + } + + void EmitNotifications (in ImmutableArray properties, TabbedWriter classBlock) + { + // to be implemented, do not throw or tests will fail. } public bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out ImmutableArray? diagnostics) @@ -71,34 +160,39 @@ public bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out } // namespace declaration - bindingContext.Builder.AppendLine (); - bindingContext.Builder.AppendLine ($"namespace {string.Join (".", bindingContext.Changes.Namespace)};"); - bindingContext.Builder.AppendLine (); + bindingContext.Builder.WriteLine (); + bindingContext.Builder.WriteLine ($"namespace {string.Join (".", bindingContext.Changes.Namespace)};"); + bindingContext.Builder.WriteLine (); // register the class only if we are not dealing with a static class var bindingData = (BindingTypeData) bindingContext.Changes.BindingInfo; - // registration depends on the class name. If the binding data contains a name, we use that one, else + // Registration depends on the class name. If the binding data contains a name, we use that one, else // we use the name of the class var registrationName = bindingData.Name ?? bindingContext.Changes.Name; if (!bindingContext.Changes.IsStatic) { - bindingContext.Builder.AppendLine ($"[Register (\"{registrationName}\", true)]"); + bindingContext.Builder.WriteLine ($"[Register (\"{registrationName}\", true)]"); } var modifiers = $"{string.Join (' ', bindingContext.Changes.Modifiers)} "; using (var classBlock = bindingContext.Builder.CreateBlock ($"{(string.IsNullOrWhiteSpace (modifiers) ? string.Empty : modifiers)}class {bindingContext.Changes.Name}", true)) { if (!bindingContext.Changes.IsStatic) { classBlock.AppendGeneratedCodeAttribute (optimizable: true); - classBlock.AppendLine ($"static readonly NativeHandle class_ptr = Class.GetHandle (\"{registrationName}\");"); - classBlock.AppendLine (); - classBlock.AppendLine ("public override NativeHandle ClassHandle => class_ptr;"); - classBlock.AppendLine (); + classBlock.WriteLine ($"static readonly NativeHandle class_ptr = Class.GetHandle (\"{registrationName}\");"); + classBlock.WriteLine (); + classBlock.WriteLine ("public override NativeHandle ClassHandle => class_ptr;"); + classBlock.WriteLine (); EmitDefaultConstructors (bindingContext: bindingContext, classBlock: classBlock, disableDefaultCtor: bindingData.Flags.HasFlag (Class.DisableDefaultCtor)); } - classBlock.AppendLine ("// TODO: add binding code here"); + EmitFields (bindingContext.Changes.Name, bindingContext.Changes.Properties, classBlock, + out var notificationProperties); + + // emit the notification helper classes, leave this for the very bottom of the class + EmitNotifications (notificationProperties, classBlock); + classBlock.WriteLine ("// TODO: add binding code here"); } return true; } diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/EmitterFactory.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/EmitterFactory.cs index b0c0e516f462..b1332aeb8b82 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/EmitterFactory.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/EmitterFactory.cs @@ -17,6 +17,6 @@ static class EmitterFactory { { BindingType.Protocol, new InterfaceEmitter () }, { BindingType.Category, new CategoryEmitter () }, }; - public static bool TryCreate (CodeChanges changes, [NotNullWhen (true)] out ICodeEmitter? emitter) + public static bool TryCreate (Binding changes, [NotNullWhen (true)] out ICodeEmitter? emitter) => emitters.TryGetValue (changes.BindingType, out emitter); } diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/EnumEmitter.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/EnumEmitter.cs index b653c3222b78..b547025f7942 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/EnumEmitter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/EnumEmitter.cs @@ -3,99 +3,103 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.IO; using Microsoft.CodeAnalysis; using Microsoft.Macios.Generator.Context; using Microsoft.Macios.Generator.DataModel; using Microsoft.Macios.Generator.Formatters; +using Microsoft.Macios.Generator.IO; namespace Microsoft.Macios.Generator.Emitters; class EnumEmitter : ICodeEmitter { - public string GetSymbolName (in CodeChanges codeChanges) => $"{codeChanges.Name}Extensions"; + public string GetSymbolName (in Binding binding) => $"{binding.Name}Extensions"; public IEnumerable UsingStatements => ["Foundation", "ObjCRuntime", "System"]; - void EmitEnumFieldAtIndex (TabbedStringBuilder classBlock, in CodeChanges codeChanges, int index) + void EmitEnumFieldAtIndex (TabbedWriter classBlock, in Binding binding, int index) { - var enumField = codeChanges.EnumMembers [index]; + var enumField = binding.EnumMembers [index]; if (enumField.FieldInfo is null) return; var (fieldData, libraryName, libraryPath) = enumField.FieldInfo.Value; classBlock.AppendMemberAvailability (enumField.SymbolAvailability); - classBlock.AppendLine ($"[Field (\"{fieldData.SymbolName}\", \"{libraryPath ?? libraryName}\")]"); - using (var propertyBlock = classBlock.CreateBlock ($"internal unsafe static IntPtr {fieldData.SymbolName}", true)) - using (var getterBlock = propertyBlock.CreateBlock ("get", true)) { - getterBlock.AppendLine ($"fixed (IntPtr *storage = &values [{index}])"); - getterBlock.AppendLine ( - $"\treturn Dlfcn.CachePointer (Libraries.{libraryName}.Handle, \"{fieldData.SymbolName}\", storage);"); + classBlock.WriteLine ($"[Field (\"{fieldData.SymbolName}\", \"{libraryPath ?? libraryName}\")]"); + using (var propertyBlock = + classBlock.CreateBlock ($"internal unsafe static IntPtr {fieldData.SymbolName}", true)) { + using (var getterBlock = propertyBlock.CreateBlock ("get", true)) { + getterBlock.WriteLine ($"fixed (IntPtr *storage = &values [{index}])"); + getterBlock.WriteLine ( + $"\treturn Dlfcn.CachePointer (Libraries.{libraryName}.Handle, \"{fieldData.SymbolName}\", storage);"); + } } } - bool TryEmit (TabbedStringBuilder classBlock, in CodeChanges codeChanges) + bool TryEmit (TabbedWriter classBlock, in Binding binding) { // keep track of the field symbols, they have to be unique, if we find a duplicate we return false and // abort the code generation var backingFields = new HashSet (); - for (var index = 0; index < codeChanges.EnumMembers.Length; index++) { - if (codeChanges.EnumMembers [index].FieldInfo is null) + for (var index = 0; index < binding.EnumMembers.Length; index++) { + if (binding.EnumMembers [index].FieldInfo is null) continue; - if (!backingFields.Add (codeChanges.EnumMembers [index].FieldInfo!.Value.FieldData.SymbolName)) { + if (!backingFields.Add (binding.EnumMembers [index].FieldInfo!.Value.FieldData.SymbolName)) { return false; } - classBlock.AppendLine (); - EmitEnumFieldAtIndex (classBlock, codeChanges, index); + classBlock.WriteLine (); + EmitEnumFieldAtIndex (classBlock, binding, index); } return true; } - void EmitExtensionMethods (TabbedStringBuilder classBlock, in CodeChanges codeChanges) + void EmitExtensionMethods (TabbedWriter classBlock, in Binding binding) { - if (codeChanges.EnumMembers.Length == 0) + if (binding.EnumMembers.Length == 0) return; // smart enum require 4 diff methods to be able to retrieve the values // Get constant - using (var getConstantBlock = classBlock.CreateBlock ($"public static NSString? GetConstant (this {codeChanges.Name} self)", true)) { - getConstantBlock.AppendLine ("IntPtr ptr = IntPtr.Zero;"); + using (var getConstantBlock = classBlock.CreateBlock ($"public static NSString? GetConstant (this {binding.Name} self)", true)) { + getConstantBlock.WriteLine ("IntPtr ptr = IntPtr.Zero;"); using (var switchBlock = getConstantBlock.CreateBlock ("switch ((int) self)", true)) { - for (var index = 0; index < codeChanges.EnumMembers.Length; index++) { - var enumMember = codeChanges.EnumMembers [index]; + for (var index = 0; index < binding.EnumMembers.Length; index++) { + var enumMember = binding.EnumMembers [index]; if (enumMember.FieldInfo is null) continue; var (fieldData, _, _) = enumMember.FieldInfo.Value; - switchBlock.AppendLine ($"case {index}: // {fieldData.SymbolName}"); - switchBlock.AppendLine ($"\tptr = {fieldData.SymbolName};"); - switchBlock.AppendLine ("\tbreak;"); + switchBlock.WriteLine ($"case {index}: // {fieldData.SymbolName}"); + switchBlock.WriteLine ($"\tptr = {fieldData.SymbolName};"); + switchBlock.WriteLine ("\tbreak;"); } } - getConstantBlock.AppendLine ("return (NSString?) Runtime.GetNSObject (ptr);"); + getConstantBlock.WriteLine ("return (NSString?) Runtime.GetNSObject (ptr);"); } - classBlock.AppendLine (); + classBlock.WriteLine (); // Get value - using (var getValueBlock = classBlock.CreateBlock ($"public static {codeChanges.Name} GetValue (NSString constant)", true)) { - getValueBlock.AppendLine ("if (constant is null)"); - getValueBlock.AppendLine ("\tthrow new ArgumentNullException (nameof (constant));"); - foreach (var enumMember in codeChanges.EnumMembers) { + using (var getValueBlock = classBlock.CreateBlock ($"public static {binding.Name} GetValue (NSString constant)", true)) { + getValueBlock.WriteLine ("if (constant is null)"); + getValueBlock.WriteLine ("\tthrow new ArgumentNullException (nameof (constant));"); + foreach (var enumMember in binding.EnumMembers) { if (enumMember.FieldInfo is null) continue; var (fieldData, _, _) = enumMember.FieldInfo.Value; - getValueBlock.AppendLine ($"if (constant.IsEqualTo ({fieldData.SymbolName}))"); - getValueBlock.AppendLine ($"\treturn {codeChanges.Name}.{enumMember.Name};"); + getValueBlock.WriteLine ($"if (constant.IsEqualTo ({fieldData.SymbolName}))"); + getValueBlock.WriteLine ($"\treturn {binding.Name}.{enumMember.Name};"); } - getValueBlock.AppendLine ( + getValueBlock.WriteLine ( "throw new NotSupportedException ($\"The constant {constant} has no associated enum value on this platform.\");"); } - classBlock.AppendLine (); + classBlock.WriteLine (); // To ConstantArray - classBlock.AppendRaw ( -@$"internal static NSString?[]? ToConstantArray (this {codeChanges.Name}[]? values) + classBlock.WriteRaw ( +@$"internal static NSString?[]? ToConstantArray (this {binding.Name}[]? values) {{ if (values is null) return null; @@ -106,15 +110,15 @@ void EmitExtensionMethods (TabbedStringBuilder classBlock, in CodeChanges codeCh }} return rv.ToArray (); }}"); - classBlock.AppendLine (); - classBlock.AppendLine (); + classBlock.WriteLine (); + classBlock.WriteLine (); // ToEnumArray - classBlock.AppendRaw ( -@$"internal static {codeChanges.Name}[]? ToEnumArray (this NSString[]? values) + classBlock.WriteRaw ( +@$"internal static {binding.Name}[]? ToEnumArray (this NSString[]? values) {{ if (values is null) return null; - var rv = new global::System.Collections.Generic.List<{codeChanges.Name}> (); + var rv = new global::System.Collections.Generic.List<{binding.Name}> (); for (var i = 0; i < values.Length; i++) {{ var value = values [i]; rv.Add (GetValue (value)); @@ -136,28 +140,28 @@ public bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out } // in the old generator we had to copy over the enum, in this new approach, the only code // we need to create is the extension class for the enum that is backed by fields - bindingContext.Builder.AppendLine (); - bindingContext.Builder.AppendLine ($"namespace {string.Join (".", bindingContext.Changes.Namespace)};"); - bindingContext.Builder.AppendLine (); + bindingContext.Builder.WriteLine (); + bindingContext.Builder.WriteLine ($"namespace {string.Join (".", bindingContext.Changes.Namespace)};"); + bindingContext.Builder.WriteLine (); bindingContext.Builder.AppendMemberAvailability (bindingContext.Changes.SymbolAvailability); bindingContext.Builder.AppendGeneratedCodeAttribute (); var extensionClassDeclaration = bindingContext.Changes.ToSmartEnumExtensionDeclaration (GetSymbolName (bindingContext.Changes)); using (var classBlock = bindingContext.Builder.CreateBlock (extensionClassDeclaration.ToString (), true)) { - classBlock.AppendLine (); - classBlock.AppendLine ($"static IntPtr[] values = new IntPtr [{bindingContext.Changes.EnumMembers.Length}];"); + classBlock.WriteLine (); + classBlock.WriteLine ($"static IntPtr[] values = new IntPtr [{bindingContext.Changes.EnumMembers.Length}];"); // foreach member in the enum we need to create a field that holds the value, the property emitter // will take care of generating the property. Do not order it by name to keep the order of the enum if (!TryEmit (classBlock, bindingContext.Changes)) { diagnostics = []; // empty diagnostics since it was a user error return false; } - classBlock.AppendLine (); + classBlock.WriteLine (); // emit the extension methods that will be used to get the values from the enum EmitExtensionMethods (classBlock, bindingContext.Changes); - classBlock.AppendLine (); + classBlock.WriteLine (); } return true; diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/ICodeEmitter.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/ICodeEmitter.cs index c389ab7ce754..4392f461def9 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/ICodeEmitter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/ICodeEmitter.cs @@ -13,7 +13,7 @@ namespace Microsoft.Macios.Generator.Emitters; /// Interface to be implemented by all those classes that know how to emit code for a binding. /// interface ICodeEmitter { - string GetSymbolName (in CodeChanges codeChanges); + string GetSymbolName (in Binding binding); bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out ImmutableArray? diagnostics); IEnumerable UsingStatements { get; } } diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/InterfaceEmitter.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/InterfaceEmitter.cs index 2d20cd8107e8..416ec8a1da6e 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/InterfaceEmitter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/InterfaceEmitter.cs @@ -10,7 +10,7 @@ namespace Microsoft.Macios.Generator.Emitters; class InterfaceEmitter : ICodeEmitter { - public string GetSymbolName (in CodeChanges codeChanges) => string.Empty; + public string GetSymbolName (in Binding binding) => string.Empty; public IEnumerable UsingStatements => []; public bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out ImmutableArray? diagnostics) { diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/LibraryEmitter.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/LibraryEmitter.cs index 8a4351f089e2..dae97f1fa760 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/LibraryEmitter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/LibraryEmitter.cs @@ -7,11 +7,12 @@ using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.IO; namespace Microsoft.Macios.Generator.Emitters; class LibraryEmitter ( - RootBindingContext context, + RootContext context, TabbedStringBuilder builder) { public string SymbolNamespace => "ObjCRuntime"; public string SymbolName => "Libraries"; @@ -43,17 +44,17 @@ public bool TryEmit (ImmutableArray<(string LibraryName, string? LibraryPath)> l return true; } - builder.AppendLine ("using Foundation;"); - builder.AppendLine ("using ObjCBindings;"); - builder.AppendLine ("using ObjCRuntime;"); - builder.AppendLine ("using System;"); + builder.WriteLine ("using Foundation;"); + builder.WriteLine ("using ObjCBindings;"); + builder.WriteLine ("using ObjCRuntime;"); + builder.WriteLine ("using System;"); // keep track if we added a lib, if not we don't need to generate the class bool added = false; - builder.AppendLine (); - builder.AppendLine ($"namespace ObjCRuntime;"); - builder.AppendLine (); + builder.WriteLine (); + builder.WriteLine ($"namespace ObjCRuntime;"); + builder.WriteLine (); builder.AppendGeneratedCodeAttribute (); using (var classBlock = builder.CreateBlock ($"static partial class {SymbolName}", true)) { @@ -63,12 +64,12 @@ public bool TryEmit (ImmutableArray<(string LibraryName, string? LibraryPath)> l using (var nestedClass = classBlock.CreateBlock ($"static public class {className}", true)) { if (name == "__Internal") { - nestedClass.AppendLine ("static public readonly IntPtr Handle = Dlfcn.dlopen (null, 0);"); + nestedClass.WriteLine ("static public readonly IntPtr Handle = Dlfcn.dlopen (null, 0);"); } else if (context.IsSystemLibrary (name)) { - nestedClass.AppendLine ( + nestedClass.WriteLine ( $"static public readonly IntPtr Handle = Dlfcn._dlopen (Constants.{name}Library, 0);"); } else { - nestedClass.AppendLine ( + nestedClass.WriteLine ( $"static public readonly IntPtr Handle = Dlfcn.dlopen (\"{path}\", 0);"); } } diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/TrampolineEmitter.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/TrampolineEmitter.cs index d6c056a733fb..f9b114f338af 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/TrampolineEmitter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/TrampolineEmitter.cs @@ -11,7 +11,7 @@ namespace Microsoft.Macios.Generator.Emitters; class TrampolineEmitter : ICodeEmitter { public string SymbolNamespace => string.Empty; - public string GetSymbolName (in CodeChanges codeChanges) => string.Empty; + public string GetSymbolName (in Binding binding) => string.Empty; public IEnumerable UsingStatements { get; } = []; public bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out ImmutableArray? diagnostics) { diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/ApplePlatformExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/ApplePlatformExtensions.cs new file mode 100644 index 000000000000..d15da844a0d4 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/ApplePlatformExtensions.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Xamarin.Utils; + +namespace Microsoft.Macios.Generator.Extensions; + +public static class ApplePlatformExtensions { + + /// + /// Return the platform define for the given ApplePlatform for use in #if directives. + /// + /// Apple platform. + /// the platform define + public static string? ToPlatformDefine (this ApplePlatform self) => self switch { + ApplePlatform.iOS => "IOS", + ApplePlatform.TVOS => "TVOS", + ApplePlatform.MacOSX => "MONOMAC", + ApplePlatform.MacCatalyst => "__MACCATALYST__", + _ => null + }; +} diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/CompilationExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/CompilationExtensions.cs index aa8e8c738efc..2dfb6398af6b 100644 --- a/src/rgen/Microsoft.Macios.Generator/Extensions/CompilationExtensions.cs +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/CompilationExtensions.cs @@ -1,11 +1,17 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.Macios.Generator.Extensions; static class CompilationExtensions { - /// /// Return the current platform that the compilation is targeting. /// @@ -42,4 +48,56 @@ public static PlatformName GetCurrentPlatform (this Compilation self) // we cannot identify the platform we are working on return PlatformName.None; } + + public static ImmutableArray GetPreprocessorSymbols (this Compilation self) + { + CSharpSyntaxTree? firstTree = (CSharpSyntaxTree?) self.SyntaxTrees.FirstOrDefault (); + + return firstTree is null ? ImmutableArray.Empty : [.. firstTree.Options.PreprocessorSymbolNames]; + } + + + // list of known ui namespaces + static readonly HashSet uiNamespaces = new HashSet { + "AppKit", + "UIKit", + "Twitter", + "NewsstandKit", + "QuickLook", + "EventKitUI", + "AddressBookUI", + "MessageUI", + "PhotosUI", + "HealthKitUI", + "GameKit", + "MapKit" + }; + + readonly static Lock uiNamespaceLock = new Lock (); + static HashSet? uiNamespacesCache = null; + + /// + /// Calculates the UI namespaces for the current compilation. + /// + /// The compilation under qury. + /// For the namespaces to be recalculated. + /// The currently configured UI namespaces. + public static IReadOnlySet GetUINamespaces (this Compilation self, bool force = false) + { + lock (uiNamespaceLock) { + if (force || uiNamespacesCache is null) { + uiNamespacesCache = new (); + // build the hash set based on the current definitions used in the compilation + var preprocessorSymbols = self.GetPreprocessorSymbols (); + foreach (var ns in uiNamespaces) { + var define = $"HAS_{ns.ToUpper ()}"; + if (preprocessorSymbols.Contains (define)) { + uiNamespacesCache.Add (ns); + } + } + } + + return uiNamespacesCache; + } + } } diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/Delegates.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/Delegates.cs new file mode 100644 index 000000000000..e1b5ac3919b3 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/Delegates.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Generator.Extensions; + +/// +/// Delegate to try to parse a value struct from an attribute. +/// +/// The type of the returned struct. +delegate bool TryParseDelegate (AttributeData attributeData, [NotNullWhen (true)] out T? value) + where T : struct; + +/// +/// Delegate that returns a list of attribute names. +/// +delegate string? GetAttributeNames (); diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/EnumExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/EnumExtensions.cs new file mode 100644 index 000000000000..f335effbd790 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/EnumExtensions.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace Microsoft.Macios.Generator.Extensions; + +static class EnumExtensions { + + public static bool HasCustomMarshalDirective (this Enum self) + { + return self switch { + // cast to the flags we know that could have the value and return it + ObjCBindings.Method methodFlag => methodFlag.HasFlag (ObjCBindings.Method.CustomMarshalDirective), + ObjCBindings.Property propertyFlag => propertyFlag.HasFlag (ObjCBindings.Property.CustomMarshalDirective), + _ => false + }; + } + + public static bool HasMarshalNativeExceptions (this Enum self) + { + return self switch { + // cast to the flags we know that could have the value and return it + ObjCBindings.Method methodFlag => methodFlag.HasFlag (ObjCBindings.Method.MarshalNativeExceptions), + ObjCBindings.Property propertyFlag => propertyFlag.HasFlag (ObjCBindings.Property.MarshalNativeExceptions), + _ => false + }; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.Generator.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.Generator.cs new file mode 100644 index 000000000000..7a7c6dd180aa --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.Generator.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Attributes; +using ObjCBindings; + +namespace Microsoft.Macios.Generator.Extensions; + +static partial class FieldSymbolExtensions { + + /// + /// Retrieve the FieldData from the field symbol. + /// + /// The field whose attribute data we want to parse. + /// True if the FieldData attribute was presend and could be parsed. + public static FieldData? GetFieldData (this IFieldSymbol fieldSymbol) + => GetFieldData> (fieldSymbol, AttributesNames.EnumFieldAttribute, FieldData.TryParse); +} diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.cs index f03daa88f780..8e2517854c03 100644 --- a/src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.cs +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/FieldSymbolExtensions.cs @@ -1,20 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + using Microsoft.CodeAnalysis; -using Microsoft.Macios.Generator.Attributes; -using ObjCBindings; namespace Microsoft.Macios.Generator.Extensions; -static class FieldSymbolExtensions { - public static FieldData? GetFieldData (this IFieldSymbol fieldSymbol) +static partial class FieldSymbolExtensions { + + /// + /// Generic method to retrieve the FieldAttribute on an IFieldSymbol and parse it. The method is generic to allow + /// to parse different types of FieldAttribute depending on the API that was used to mark the field. Old APIs + /// (xamarin bgen API) and the new API (ObjCBindings rgen API) use different FieldAttribute. + /// + /// The field whose attribute data we want to parse. + /// The name of the attribute to parse. This name is different depending on the API used. + /// The delegate to use to parse the attribute data. + /// The type of the struct that will contain the data of the attribute. + /// Ture if the attribute was found and could be parsed. + public static T? GetFieldData (IFieldSymbol fieldSymbol, string attributeName, TryParseDelegate tryParseDelegate) where T : struct { var attributes = fieldSymbol.GetAttributeData (); if (attributes.Count == 0) return null; // Get all the FieldAttribute, parse it and add the data to the result - if (!attributes.TryGetValue (AttributesNames.EnumFieldAttribute, out var fieldAttrDataList) || + if (!attributes.TryGetValue (attributeName, out var fieldAttrDataList) || fieldAttrDataList.Count != 1) return null; @@ -23,9 +33,10 @@ static class FieldSymbolExtensions { if (fieldSyntax is null) return null; - if (FieldData.TryParse (fieldAttrData, out var fieldData)) + if (tryParseDelegate (fieldAttrData, out var fieldData)) return fieldData.Value; return null; } + } diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.Generator.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.Generator.cs new file mode 100644 index 000000000000..835dd9a3111c --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.Generator.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.DataModel; + +namespace Microsoft.Macios.Generator.Extensions; + +static partial class SemanticModelExtensions { + + public static void GetSymbolData (this SemanticModel self, BaseTypeDeclarationSyntax declaration, + BindingType bindingType, + out string name, + out string? baseClass, + out ImmutableArray interfaces, + out ImmutableArray namespaces, + out SymbolAvailability symbolAvailability, + out BindingInfo bindingInfo) + { + var symbol = self.GetDeclaredSymbol (declaration); + GetSymbolData (symbol, out name, out baseClass, out interfaces, out namespaces, out symbolAvailability); + if (symbol is null) + bindingInfo = default; + else { + bindingInfo = bindingType switch { + BindingType.Category => new BindingInfo (symbol.GetBindingData ()), + BindingType.Class => new BindingInfo (symbol.GetBindingData ()), + BindingType.Protocol => new BindingInfo (symbol.GetBindingData ()), + BindingType.SmartEnum => new BindingInfo (BindingType.SmartEnum, symbol.GetBindingData ()), + _ => default, + }; + } + } + +} diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs index c90a5a1123be..c8a88a4163ab 100644 --- a/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs @@ -2,14 +2,21 @@ // Licensed under the MIT License. using System.Collections.Immutable; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.Availability; -using Microsoft.Macios.Generator.DataModel; namespace Microsoft.Macios.Generator.Extensions; -static class SemanticModelExtensions { +static partial class SemanticModelExtensions { + /// + /// Retrieves all the data from a symbol needed for a binding/transformation. + /// + /// The symbol being queried. + /// Symbol name. + /// Symbol base class. + /// List of the interfaces implemented by the symbol. + /// Collection with the namespaces of the symbol. + /// The symbols availability. public static void GetSymbolData (ISymbol? symbol, out string name, out string? baseClass, @@ -40,28 +47,4 @@ public static void GetSymbolData (ISymbol? symbol, namespaces = bucket.ToImmutableArray (); } - public static void GetSymbolData (this SemanticModel self, BaseTypeDeclarationSyntax declaration, - BindingType bindingType, - out string name, - out string? baseClass, - out ImmutableArray interfaces, - out ImmutableArray namespaces, - out SymbolAvailability symbolAvailability, - out BindingInfo bindingInfo) - { - var symbol = self.GetDeclaredSymbol (declaration); - GetSymbolData (symbol, out name, out baseClass, out interfaces, out namespaces, out symbolAvailability); - if (symbol is null) - bindingInfo = default; - else { - bindingInfo = bindingType switch { - BindingType.Category => new BindingInfo (symbol.GetBindingData ()), - BindingType.Class => new BindingInfo (symbol.GetBindingData ()), - BindingType.Protocol => new BindingInfo (symbol.GetBindingData ()), - BindingType.SmartEnum => new BindingInfo (BindingType.SmartEnum, symbol.GetBindingData ()), - _ => default, - }; - } - } - } diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/SpecialTypeExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/SpecialTypeExtensions.cs new file mode 100644 index 000000000000..21049b621965 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/SpecialTypeExtensions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Generator.Extensions; + +static class SpecialTypeExtensions { + + public static string? GetKeyword (this SpecialType? self) + => self?.GetKeyword (); + + /// + /// Return the keyword for a given special type. + /// + /// The special type to convert. + /// The string representation of the keyword. + public static string GetKeyword (this SpecialType self) + { + var kind = self switch { + SpecialType.System_Void => SyntaxKind.VoidKeyword, + SpecialType.System_Boolean => SyntaxKind.BoolKeyword, + SpecialType.System_Byte => SyntaxKind.ByteKeyword, + SpecialType.System_SByte => SyntaxKind.SByteKeyword, + SpecialType.System_Int16 => SyntaxKind.ShortKeyword, + SpecialType.System_UInt16 => SyntaxKind.UShortKeyword, + SpecialType.System_Int32 => SyntaxKind.IntKeyword, + SpecialType.System_UInt32 => SyntaxKind.UIntKeyword, + SpecialType.System_Int64 => SyntaxKind.LongKeyword, + SpecialType.System_UInt64 => SyntaxKind.ULongKeyword, + SpecialType.System_Double => SyntaxKind.DoubleKeyword, + SpecialType.System_Single => SyntaxKind.FloatKeyword, + SpecialType.System_Decimal => SyntaxKind.DecimalKeyword, + SpecialType.System_String => SyntaxKind.StringKeyword, + SpecialType.System_Char => SyntaxKind.CharKeyword, + SpecialType.System_Object => SyntaxKind.ObjectKeyword, + // Note that "dynamic" is a contextual keyword, so it should never show up here. + _ => SyntaxKind.None + }; + return Token (kind).Text; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Core.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Core.cs new file mode 100644 index 000000000000..d09c088df04b --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Core.cs @@ -0,0 +1,479 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Availability; + +namespace Microsoft.Macios.Generator.Extensions; + +static partial class TypeSymbolExtensions { + + const string nativeObjectInterface = "ObjCRuntime.INativeObject"; + const string nsObjectClass = "Foundation.NSObject"; + const string dictionaryContainerClass = "Foundation.DictionaryContainer"; + + /// + /// Retrieve a dictionary with the attribute data of all the attributes attached to a symbol. Because + /// an attribute can appear more than once, the valus are a collection of attribute data. + /// + /// The symbol whose attributes we want to retrieve. + /// A dictionary with the attribute names as keys and the related attribute data. + public static Dictionary> GetAttributeData (this ISymbol symbol) + { + var boundAttributes = symbol.GetAttributes (); + var attributes = new Dictionary> (); + foreach (var attributeData in boundAttributes) { + var attrName = attributeData.AttributeClass?.ToDisplayString (); + if (string.IsNullOrEmpty (attrName)) + continue; + if (!attributes.TryGetValue (attrName, out var attributeDataList)) { + attributeDataList = new List (); + attributes.Add (attrName, attributeDataList); + } + + attributeDataList.Add (attributeData); + } + + // if we are dealing with a method, we want to also return the attributes used for the return type + if (symbol is not IMethodSymbol methodSymbol) + return attributes; + + var returnAttributes = methodSymbol.GetReturnTypeAttributes (); + foreach (var attributeData in returnAttributes) { + var attrName = attributeData.AttributeClass?.ToDisplayString (); + if (string.IsNullOrEmpty (attrName)) + continue; + if (!attributes.TryGetValue (attrName, out var attributeDataList)) { + attributeDataList = new List (); + attributes.Add (attrName, attributeDataList); + } + + attributeDataList.Add (attributeData); + } + + return attributes; + } + + /// + /// Return the list of parent symbols in ascending order. + /// + /// The symbol whose parents to retrieve. + /// Array with all the parent symbols until we reach the containing namespace. + public static ImmutableArray GetParents (this ISymbol symbol) + { + var result = new List (); + // when looking for the parents of a symbol we need to make a distinction between a general ISymbol such as + // a INamedType symbol and a IMethodSymbol that represents a property accessor. Properties are NOT treated as + // containing symbols of their accessors. Accessors are related to their property symbols via the AssociatedSymbol + // property. In our code generator we want to include the property symbol as a parent of the accessor to combine + // correctly the availability attributes. + var current = (symbol is IMethodSymbol { AssociatedSymbol: not null } methodSymbol) + ? methodSymbol.AssociatedSymbol + : symbol.ContainingSymbol; + if (current is null) + return []; + + while (current is not INamespaceSymbol) { + result.Add (current); + current = current.ContainingSymbol; + } + + return [.. result]; + } + + public static bool HasAttribute (this ISymbol symbol, string attribute) + { + var boundAttributes = symbol.GetAttributes (); + if (boundAttributes.Length == 0) { + return false; + } + + foreach (var attributeData in boundAttributes) { + var attrName = attributeData.AttributeClass?.ToDisplayString (); + if (attrName == attribute) { + return true; + } + } + + return false; + } + + internal static T? GetAttribute (this ISymbol symbol, GetAttributeNames getAttributeNames, TryParseDelegate tryParse) + where T : struct + { + var attributes = symbol.GetAttributeData (); + if (attributes.Count == 0) + return null; + + // retrieve the name of the attribute based on the flag + var attrName = getAttributeNames (); + if (attrName is null) + return null; + if (!attributes.TryGetValue (attrName, out var exportAttrDataList) || + exportAttrDataList.Count != 1) + return null; + + var exportAttrData = exportAttrDataList [0]; + var fieldSyntax = exportAttrData.ApplicationSyntaxReference?.GetSyntax (); + if (fieldSyntax is null) + return null; + + if (tryParse (exportAttrData, out var exportData)) + return exportData.Value; + return null; + } + + internal static T? GetAttribute (this ISymbol symbol, string attributeName, TryParseDelegate tryParse) + where T : struct + => GetAttribute (symbol, () => attributeName, tryParse); + + /// + /// Return the layout kind used by the symbol. + /// + /// The struct symbol whose layout we need to retrieve. + /// The layout kind used by the symbol. + public static LayoutKind GetStructLayout (this ITypeSymbol symbol) + { + // Check for StructLayout attribute with LayoutKind.Sequential + var layoutAttribute = symbol.GetAttributes () + .FirstOrDefault (attr => + attr.AttributeClass?.ToString () == typeof (StructLayoutAttribute).FullName); + + if (layoutAttribute is not null) { + return (LayoutKind) layoutAttribute.ConstructorArguments [0].Value!; + } + + // the default is auto, another lyaout would have been set in the attr + return LayoutKind.Auto; + } + + /// + /// Return all the fields that determine the size of a struct. + /// + /// The symbol whose fields to retireve. + /// an array with all the none static fields of a struct. + public static IFieldSymbol [] GetStructFields (this ITypeSymbol symbol) + => symbol.GetMembers () + .OfType () + .Where (field => !field.IsStatic) + .ToArray (); + + /// + /// Returns if a type is blittable or not. + /// + /// + /// + /// + public static bool IsBlittable (this ITypeSymbol symbol) + { + if (symbol.NullableAnnotation == NullableAnnotation.Annotated) + return false; + + while (true) { + // per the documentation, the following system types are blittable + switch (symbol.SpecialType) { + case SpecialType.System_Byte: + case SpecialType.System_SByte: + case SpecialType.System_Int16: + case SpecialType.System_UInt16: + case SpecialType.System_Int32: + case SpecialType.System_UInt32: + case SpecialType.System_Int64: + case SpecialType.System_UInt64: + case SpecialType.System_Single: + case SpecialType.System_Double: + case SpecialType.System_IntPtr: + case SpecialType.System_UIntPtr: + return true; + case SpecialType.System_Array: + // if we are dealing with an array, an array of blittable elements is blittable + symbol = symbol.ContainingType; + continue; + } + + if (symbol is IArrayTypeSymbol arrayTypeSymbol) { + symbol = arrayTypeSymbol.ElementType; + continue; + } + + if (symbol.TypeKind == TypeKind.Enum && symbol is INamedTypeSymbol enumSymbol) { + // an enum is blittable based on its backing field + symbol = enumSymbol.EnumUnderlyingType!; + continue; + } + + // if we are dealing with a structure, we have to check the layout type and all its children + if (symbol.TypeKind == TypeKind.Struct) { + // Check for StructLayout attribute with LayoutKind.Sequential + if (symbol.GetStructLayout () == LayoutKind.Auto) { + return false; + } + + // Recursively check all fields of the struct + var instanceFields = symbol.GetStructFields (); + foreach (var member in instanceFields) { + if (!member.Type.IsBlittable ()) { + return false; + } + } + + return true; + } + + // any other types are not blittable + return false; + } + } + + /// + /// Return the offset of a field in a Explicitly layout struct. + /// + /// A Field symbol. + /// + public static int GetFieldOffset (this IFieldSymbol symbol) + { + var offsetAttribute = symbol.GetAttributes () + .FirstOrDefault (attr => + attr.AttributeClass?.ToString () == typeof (FieldOffsetAttribute).FullName); + + return offsetAttribute is not null + ? (int) offsetAttribute.ConstructorArguments [0].Value! + : 0; + } + + /// + /// Return the value of the MarshallAs attribute. + /// + /// The symbol under test. + /// The type to use for the symbol marshaling. + public static (UnmanagedType Type, int SizeConst)? GetMarshalAs (this ISymbol symbol) + { + var marshalAsAttribute = symbol.GetAttributes () + .FirstOrDefault (attr => + attr.AttributeClass?.ToString () == typeof (MarshalAsAttribute).FullName); + if (marshalAsAttribute is null) + return null; + var type = (UnmanagedType) marshalAsAttribute.ConstructorArguments [0].Value!; + int sizeConst = 0; + foreach (var (name, value) in marshalAsAttribute.NamedArguments) { + if (name == "SizeConst") + sizeConst = (int) value.Value!; + } + + return (type, sizeConst); + } + + /// + /// Indicate whether the current symbol represents a type whose definition is nested inside the definition of + /// another symbol. + /// + /// The symbol under test. + /// True if the symbol is nested. + internal static bool IsNested (this ITypeSymbol symbol) => symbol.ContainingType is not null; + + /// + /// Try to get the size of a built-in type. + /// + /// The symbol under test. + /// The platform target. + /// The size of the native type. + /// True if we could calculate the size. + internal static bool TryGetBuiltInTypeSize (this ITypeSymbol symbol, bool is64bits, out int size) + { + if (symbol.IsNested ()) { + size = 0; + return false; + } + +#pragma warning disable format + + var symbolInfo = ( + ContainingNamespace: symbol.ContainingNamespace.ToDisplayString (), + Name: symbol.Name, + SpecialType: symbol.SpecialType + ); + + var (currentSize, result) = symbolInfo switch { + { SpecialType: SpecialType.System_Void } => (0, true), + { ContainingNamespace: "ObjCRuntime", Name: "NativeHandle" } => (is64bits ? 8 : 4, true), + { ContainingNamespace: "System.Runtime.InteropServices", Name: "NFloat" } => (is64bits ? 8 : 4, true), + { ContainingNamespace: "System", Name: "Char" or "Boolean" or "SByte" or "Byte" } => (1, true), + { ContainingNamespace: "System", Name: "Int16" or "UInt16" } => (2, true), + { ContainingNamespace: "System", Name: "Single" or "Int32" or "UInt32" } => (4, true), + { ContainingNamespace: "System", Name: "Double" or "Int64" or "UInt64" } => (8, true), + { ContainingNamespace: "System", Name: "IntPtr" or "UIntPtr" or "nuint" or "nint" } => (is64bits ? 8 : 4, true), + _ => (0, false) + }; +#pragma warning restore format + size = currentSize; + return result; + } + + static bool TryGetBuiltInTypeSize (this ITypeSymbol type) + => TryGetBuiltInTypeSize (type, true /* doesn't matter */, out _); + + static int AlignAndAdd (int size, int add, ref int maxElementSize) + { + maxElementSize = Math.Max (maxElementSize, add); + if (size % add != 0) + size += add - size % add; + return size + add; + } + + + static void GetValueTypeSize (this ITypeSymbol originalSymbol, ITypeSymbol type, List fieldSymbols, + bool is64Bits, ref int size, + ref int maxElementSize) + { + // FIXME: + // SIMD types are not handled correctly here (they need 16-bit alignment). + // However, we don't annotate those types in any way currently, so first we'd need to + // add the proper attributes so that the generator can distinguish those types from other types. + + if (type.TryGetBuiltInTypeSize (is64Bits, out var typeSize) && typeSize > 0) { + fieldSymbols.Add (type); + size = AlignAndAdd (size, typeSize, ref maxElementSize); + return; + } + + // composite struct + foreach (var field in type.GetStructFields ()) { + var marshalAs = field.GetMarshalAs (); + if (marshalAs is null) { + GetValueTypeSize (originalSymbol, field.Type, fieldSymbols, is64Bits, ref size, ref maxElementSize); + continue; + } + + var (marshalAsType, sizeConst) = marshalAs.Value; + var multiplier = 1; + switch (marshalAsType) { + case UnmanagedType.ByValArray: + var types = new List (); + var arrayTypeSymbol = (field as IArrayTypeSymbol)!; + GetValueTypeSize (originalSymbol, arrayTypeSymbol.ElementType, types, is64Bits, ref typeSize, ref maxElementSize); + multiplier = sizeConst; + break; + case UnmanagedType.U1: + case UnmanagedType.I1: + typeSize = 1; + break; + case UnmanagedType.U2: + case UnmanagedType.I2: + typeSize = 2; + break; + case UnmanagedType.U4: + case UnmanagedType.I4: + case UnmanagedType.R4: + typeSize = 4; + break; + case UnmanagedType.U8: + case UnmanagedType.I8: + case UnmanagedType.R8: + typeSize = 8; + break; + default: + throw new Exception ($"Unhandled MarshalAs attribute: {marshalAs.Value} on field {field.ToDisplayString ()}"); + } + fieldSymbols.Add (field.Type); + size = AlignAndAdd (size, typeSize, ref maxElementSize); + size += (multiplier - 1) * size; + } + } + + /// + /// Return the size of a blittable structure that can be used in a PInvoke + /// + /// The type symbol whose size we want to get. + /// The fileds of the struct. + /// If the calculation is for a 64b machine. + /// + internal static int GetValueTypeSize (this ITypeSymbol type, List fieldTypes, bool is64Bits) + { + int size = 0; + int maxElementSize = 1; + + if (type.GetStructLayout () == LayoutKind.Explicit) { + // Find the maximum of "field size + field offset" for each field. + foreach (var field in type.GetStructFields ()) { + var fieldOffset = field.GetFieldOffset (); + var elementSize = 0; + GetValueTypeSize (type, field.Type, fieldTypes, is64Bits, ref elementSize, ref maxElementSize); + size = Math.Max (size, elementSize + fieldOffset); + } + } else { + GetValueTypeSize (type, type, fieldTypes, is64Bits, ref size, ref maxElementSize); + } + + if (size % maxElementSize != 0) + size += (maxElementSize - size % maxElementSize); + + return size; + } + + /// + /// Returns the parents and all the implemented interfaces (including those of the parents). + /// + /// The symbol whose inheritance we want to retrieve. + /// If the type implements the INativeObject interface. + /// If the type inherits from Foundation.DictionaryContainer. + /// An immutable array of the parents in order from closest to furthest. + /// All implemented interfaces by the type and its parents. + /// If the type inherits from NSObject. + public static void GetInheritance ( + this ITypeSymbol symbol, out bool isNSObject, out bool isNativeObject, out bool isDictionaryContainer, + out ImmutableArray parents, + out ImmutableArray interfaces) + { + isNSObject = symbol.ToDisplayString ().Trim () == nsObjectClass; + isNativeObject = false; + isDictionaryContainer = false; + + // parents will be returned directly in a Immutable array via a builder since the order is important + // interfaces will use a hash set because we do not want duplicates. + var parentsBuilder = ImmutableArray.CreateBuilder (); + // init the set with all the interfaces of the current symbol + var interfacesSet = new HashSet (symbol.Interfaces.Select (i => i.ToDisplayString ())); + + var currentType = symbol.BaseType; + while (currentType is not null) { + // check if we reach the NSObject as a parent + var parentName = currentType.ToDisplayString ().Trim (); + isNSObject |= parentName == nsObjectClass; + isDictionaryContainer |= parentName == dictionaryContainerClass; + parentsBuilder.Add (parentName); + + // union with the current interfaces + interfacesSet.UnionWith (currentType.Interfaces.Select (i => i.ToDisplayString ())); + + currentType = currentType.BaseType; + } + + isNativeObject = interfacesSet.Contains (nativeObjectInterface); + parents = parentsBuilder.ToImmutable (); + interfaces = [.. interfacesSet]; + } + + /// + /// Returns the symbol availability taking into account the parent symbols availability. + /// + /// That means that the attributes used on the current symbol are merged with the attributes used + /// in all the symbol parents following the correct child-parent order. + /// + /// The symbol whose availability we want to retrieve. + /// A symbol availability structure for the symbol. + public static SymbolAvailability GetSupportedPlatforms (this ISymbol symbol) + { + var availability = GetAvailabilityForSymbol (symbol); + // get the parents and return the merge + foreach (var parent in GetParents (symbol)) { + availability = availability.MergeWithParent (GetAvailabilityForSymbol (parent)); + } + + return availability; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Generator.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Generator.cs new file mode 100644 index 000000000000..5676dc0953a3 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.Generator.cs @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; + +namespace Microsoft.Macios.Generator.Extensions; + +static partial class TypeSymbolExtensions { + + /// + /// Return the symbol availability WITHOUT taking into account the parent symbols availability. + /// + /// The symbols whose availability attributes we want to retrieve. + /// The symbol availability WITHOUT taking into account the parent symbols. + /// This is a helper method, you probably don't want to use it. + static SymbolAvailability GetAvailabilityForSymbol (this ISymbol symbol) + { + //get the attribute of the symbol and look for the Supported and Unsupported attributes and + // add the different platforms to the result hashsets + var builder = SymbolAvailability.CreateBuilder (); + var boundAttributes = symbol.GetAttributes (); + if (boundAttributes.Length == 0) { + // no attrs in the symbol, therefore the symbol is supported in all platforms + return builder.ToImmutable (); + } + + foreach (var attributeData in boundAttributes) { + var attrName = attributeData.AttributeClass?.ToDisplayString (); + if (string.IsNullOrEmpty (attrName)) + continue; + // we only care in this case about the support and unsupported attrs, ignore any other + switch (attrName) { + case AttributesNames.SupportedOSPlatformAttribute: + if (SupportedOSPlatformData.TryParse (attributeData, out var supportedPlatform)) { + builder.Add (supportedPlatform.Value); + } + + break; + case AttributesNames.UnsupportedOSPlatformAttribute: + if (UnsupportedOSPlatformData.TryParse (attributeData, out var unsupportedPlatform)) { + builder.Add (unsupportedPlatform.Value); + } + + break; + case AttributesNames.ObsoletedOSPlatformAttribute: + if (ObsoletedOSPlatformData.TryParse (attributeData, out var obsoletedOsPlatform)) { + builder.Add (obsoletedOsPlatform.Value); + } + + break; + default: + continue; + } + } + + return builder.ToImmutable (); + } + + /// + /// Test if a symbol represents a smart enum. + /// + /// The symbol under query. + /// True if the symbol is a smart enum. + public static bool IsSmartEnum (this ITypeSymbol symbol) + { + // a type is a smart enum if its type is a enum one AND it was decorated with the + // binding type attribute + return symbol.TypeKind == TypeKind.Enum + && symbol.HasAttribute (AttributesNames.BindingAttribute); + } + + /// + /// Retrieves the binding type data from a symbol that represents a smart enum. For any other binding types use + /// the generic method. + /// + /// The symbol under query. + /// The binding type data for a smart enum binding. + public static BindingTypeData GetBindingData (this ISymbol symbol) + => GetAttribute (symbol, AttributesNames.BindingAttribute, BindingTypeData.TryParse) ?? default; + + /// + /// Retrieves the binding type data from a symbol that represents a binding type. + /// + /// The symbol under query. + /// The flag that identifies the type of binding. + /// The binding type data for the binding that matches the flat T. + public static BindingTypeData GetBindingData (this ISymbol symbol) where T : Enum + => GetAttribute> (symbol, AttributesNames.GetBindingTypeAttributeName, BindingTypeData.TryParse) ?? default; + + /// + /// Retrieve the data of an export attribute on a symbol. + /// + /// The tagged symbol. + /// Enum type used in the attribute. + /// The data of the export attribute if present or null if it was not found. + /// If the passed enum is unknown or not supported as an enum for the export attribute, null will be + /// returned. + public static ExportData? GetExportData (this ISymbol symbol) where T : Enum + => GetAttribute> (symbol, AttributesNames.GetExportAttributeName, ExportData.TryParse); + + /// + /// Retrieve the data of a field attribute on a symbol, usually a property. + /// + /// The tagged symbol. + /// Enum type used in the attribute. + /// The data of the export attribute if present or null if it was not found. + /// If the passed enum is unknown or not supported as an enum for the field attribute, null will be + /// returned. + public static FieldData? GetFieldData (this ISymbol symbol) where T : Enum + => GetAttribute> (symbol, AttributesNames.GetFieldAttributeName, FieldData.TryParse); + + /// + /// Retrieve the data from the bind from attribute on a symbol. + /// + /// The tagged symbol. + /// The data of a BindFromAttribute that was added to the symbol or null if it was not found. + public static BindFromData? GetBindFromData (this ISymbol symbol) + => GetAttribute (symbol, AttributesNames.BindFromAttribute, BindFromData.TryParse); + + public static bool X86NeedStret (ITypeSymbol returnType) + { + if (!returnType.IsValueType || returnType.SpecialType == SpecialType.System_Enum || + returnType.TryGetBuiltInTypeSize ()) + return false; + + var fieldTypes = new List (); + var size = GetValueTypeSize (returnType, fieldTypes, false); + + if (size > 8) + return true; + + return fieldTypes.Count == 3; + } + + public static bool X86_64NeedStret (ITypeSymbol returnType) + { + if (!returnType.IsValueType || returnType.SpecialType == SpecialType.System_Enum || + returnType.TryGetBuiltInTypeSize ()) + return false; + + var fieldTypes = new List (); + return GetValueTypeSize (returnType, fieldTypes, true) > 16; + } + + public static bool ArmNeedStret (ITypeSymbol returnType, Compilation compilation) + { + var currentPlatform = compilation.GetCurrentPlatform (); + bool has32bitArm = currentPlatform != PlatformName.TvOS && currentPlatform != PlatformName.MacOSX; + if (!has32bitArm) + return false; + + ITypeSymbol t = returnType; + + if (!t.IsValueType || t.SpecialType == SpecialType.System_Enum || t.TryGetBuiltInTypeSize ()) + return false; + + var fieldTypes = new List (); + var size = t.GetValueTypeSize (fieldTypes, false); + + bool isiOS = currentPlatform == PlatformName.iOS; + + if (isiOS && size <= 4 && fieldTypes.Count == 1) { + +#pragma warning disable format + return fieldTypes [0] switch { + { Name: "nint" } => false, + { Name: "nuint" } => false, + { SpecialType: SpecialType.System_Char } => false, + { SpecialType: SpecialType.System_Byte } => false, + { SpecialType: SpecialType.System_SByte } => false, + { SpecialType: SpecialType.System_UInt16 } => false, + { SpecialType: SpecialType.System_Int16 } => false, + { SpecialType: SpecialType.System_UInt32 } => false, + { SpecialType: SpecialType.System_Int32 } => false, + { SpecialType: SpecialType.System_IntPtr } => false, + { SpecialType: SpecialType.System_UIntPtr } => false, + _ => true + }; +#pragma warning restore format + } + + return true; + } + + /// + /// Return if a given ITypeSymbol requires to use the objc_MsgSend_stret variants. + /// + /// The type we are testing. + /// The current compilation, used to determine the target platform. + /// If the type represented by the symtol needs a stret call variant. + public static bool NeedsStret (this ITypeSymbol returnType, Compilation compilation) + { + if (X86NeedStret (returnType)) + return true; + + if (X86_64NeedStret (returnType)) + return true; + + return ArmNeedStret (returnType, compilation); + } + + /// + /// A type is considered wrapped if it is an Interface or is an child of the NSObject class or the NSObject + /// itself. + /// + /// The symbol to check if it is wrapped. + /// If the symbol is a NSObject of inherits from an NSObject. + /// True if the ymbol is considered to be wrapped. + public static bool IsWrapped (this ITypeSymbol symbol, bool isNSObject) + => symbol.TypeKind == TypeKind.Interface || isNSObject; + + /// + /// A type is considered wrapped if it is an Interface or is an child of the NSObject class or the NSObject + /// itself. + /// + /// The symbol to check if it is wrapped. + /// True if the ymbol is considered to be wrapped. + public static bool IsWrapped (this ITypeSymbol symbol) + { + symbol.GetInheritance ( + isNSObject: out bool isNSObject, + isNativeObject: out bool _, + isDictionaryContainer: out bool _, + parents: out ImmutableArray _, + interfaces: out ImmutableArray _); + // either we are a NSObject or we are a subclass of it + return IsWrapped (symbol, isNSObject); + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.cs deleted file mode 100644 index 209966924556..000000000000 --- a/src/rgen/Microsoft.Macios.Generator/Extensions/TypeSymbolExtensions.cs +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Runtime.InteropServices; -using Microsoft.CodeAnalysis; -using Microsoft.Macios.Generator.Attributes; -using Microsoft.Macios.Generator.Availability; - -namespace Microsoft.Macios.Generator.Extensions; - -static class TypeSymbolExtensions { - /// - /// Retrieve a dictionary with the attribute data of all the attributes attached to a symbol. Because - /// an attribute can appear more than once, the valus are a collection of attribute data. - /// - /// The symbol whose attributes we want to retrieve. - /// A dictionary with the attribute names as keys and the related attribute data. - public static Dictionary> GetAttributeData (this ISymbol symbol) - { - var boundAttributes = symbol.GetAttributes (); - if (boundAttributes.Length == 0) { - // return an empty dictionary if there are no attributes - return new (); - } - - var attributes = new Dictionary> (); - foreach (var attributeData in boundAttributes) { - var attrName = attributeData.AttributeClass?.ToDisplayString (); - if (string.IsNullOrEmpty (attrName)) - continue; - if (!attributes.TryGetValue (attrName, out var attributeDataList)) { - attributeDataList = new List (); - attributes.Add (attrName, attributeDataList); - } - - attributeDataList.Add (attributeData); - } - - return attributes; - } - - /// - /// Return the list of parent symbols in ascending order. - /// - /// The symbol whose parents to retrieve. - /// Array with all the parent symbols until we reach the containing namespace. - public static ImmutableArray GetParents (this ISymbol symbol) - { - var result = new List (); - var current = symbol.ContainingSymbol; - if (current is null) - return []; - - while (current is not INamespaceSymbol) { - result.Add (current); - current = current.ContainingSymbol; - } - - return [.. result]; - } - - /// - /// Return the symbol availability WITHOUT taking into account the parent symbols availability. - /// - /// The symbols whose availability attributes we want to retrieve. - /// The symbol availability WITHOUT taking into account the parent symbols. - /// This is a helper method, you probably don't want to use it. - static SymbolAvailability GetAvailabilityForSymbol (this ISymbol symbol) - { - //get the attribute of the symbol and look for the Supported and Unsupported attributes and - // add the different platforms to the result hashsets - var builder = SymbolAvailability.CreateBuilder (); - var boundAttributes = symbol.GetAttributes (); - if (boundAttributes.Length == 0) { - // no attrs in the symbol, therefore the symbol is supported in all platforms - return builder.ToImmutable (); - } - - foreach (var attributeData in boundAttributes) { - var attrName = attributeData.AttributeClass?.ToDisplayString (); - if (string.IsNullOrEmpty (attrName)) - continue; - // we only care in this case about the support and unsupported attrs, ignore any other - switch (attrName) { - case AttributesNames.SupportedOSPlatformAttribute: - if (SupportedOSPlatformData.TryParse (attributeData, out var supportedPlatform)) { - builder.Add (supportedPlatform.Value); - } - - break; - case AttributesNames.UnsupportedOSPlatformAttribute: - if (UnsupportedOSPlatformData.TryParse (attributeData, out var unsupportedPlatform)) { - builder.Add (unsupportedPlatform.Value); - } - - break; - case AttributesNames.ObsoletedOSPlatformAttribute: - if (ObsoletedOSPlatformData.TryParse (attributeData, out var obsoletedOsPlatform)) { - builder.Add (obsoletedOsPlatform.Value); - } - - break; - default: - continue; - } - } - - return builder.ToImmutable (); - } - - /// - /// Returns the symbol availability taking into account the parent symbols availability. - /// - /// That means that the attributes used on the current symbol are merged with the attributes used - /// in all the symbol parents following the correct child-parent order. - /// - /// The symbol whose availability we want to retrieve. - /// A symbol availability structure for the symbol. - public static SymbolAvailability GetSupportedPlatforms (this ISymbol symbol) - { - var availability = GetAvailabilityForSymbol (symbol); - // get the parents and return the merge - foreach (var parent in GetParents (symbol)) { - availability = availability.MergeWithParent (GetAvailabilityForSymbol (parent)); - } - return availability; - } - - public static bool HasAttribute (this ISymbol symbol, string attribute) - { - var boundAttributes = symbol.GetAttributes (); - if (boundAttributes.Length == 0) { - return false; - } - foreach (var attributeData in boundAttributes) { - var attrName = attributeData.AttributeClass?.ToDisplayString (); - if (attrName == attribute) { - return true; - } - } - return false; - } - - public static bool IsSmartEnum (this ITypeSymbol symbol) - { - // a type is a smart enum if its type is a enum one AND it was decorated with the - // binding type attribute - return symbol.TypeKind == TypeKind.Enum - && symbol.HasAttribute (AttributesNames.BindingAttribute); - } - - public static BindingTypeData GetBindingData (this ISymbol symbol) - { - var boundAttributes = symbol.GetAttributes (); - if (boundAttributes.Length == 0) { - // no attrs in the symbol, therefore the symbol is supported in all platforms - return default; - } - // we are looking for the basic BindingAttribute attr - foreach (var attributeData in boundAttributes) { - var attrName = attributeData.AttributeClass?.ToDisplayString (); - if (string.IsNullOrEmpty (attrName) || attrName != AttributesNames.BindingAttribute) - continue; - if (BindingTypeData.TryParse (attributeData, out var bindingData)) { - return bindingData.Value; - } - } - - return default; - } - - public static BindingTypeData GetBindingData (this ISymbol symbol) where T : Enum - { - var boundAttributes = symbol.GetAttributes (); - if (boundAttributes.Length == 0) { - // no attrs in the symbol, therefore the symbol is supported in all platforms - return default; - } - - var targetAttrName = AttributesNames.GetBindingTypeAttributeName (); - foreach (var attributeData in boundAttributes) { - var attrName = attributeData.AttributeClass?.ToDisplayString (); - if (string.IsNullOrEmpty (attrName) || attrName != targetAttrName) - continue; - if (BindingTypeData.TryParse (attributeData, out var bindingData)) { - return bindingData.Value; - } - } - - return default; - } - - delegate string? GetAttributeNames (); - delegate bool TryParse (AttributeData data, [NotNullWhen (true)] out T? value) where T : struct; - - static T? GetAttribute (this ISymbol symbol, GetAttributeNames getAttributeNames, TryParse tryParse) where T : struct - { - var attributes = symbol.GetAttributeData (); - if (attributes.Count == 0) - return null; - - // retrieve the name of the attribute based on the flag - var attrName = getAttributeNames (); - if (attrName is null) - return null; - if (!attributes.TryGetValue (attrName, out var exportAttrDataList) || - exportAttrDataList.Count != 1) - return null; - - var exportAttrData = exportAttrDataList [0]; - var fieldSyntax = exportAttrData.ApplicationSyntaxReference?.GetSyntax (); - if (fieldSyntax is null) - return null; - - if (tryParse (exportAttrData, out var exportData)) - return exportData.Value; - return null; - } - - /// - /// Retrieve the data of an export attribute on a symbol. - /// - /// The tagged symbol. - /// Enum type used in the attribute. - /// The data of the export attribute if present or null if it was not found. - /// If the passed enum is unknown or not supported as an enum for the export attribute, null will be - /// returned. - public static ExportData? GetExportData (this ISymbol symbol) where T : Enum - => GetAttribute> (symbol, AttributesNames.GetExportAttributeName, ExportData.TryParse); - - /// - /// Retrieve the data of a field attribute on a symbol. - /// - /// The tagged symbol. - /// Enum type used in the attribute. - /// The data of the export attribute if present or null if it was not found. - /// If the passed enum is unknown or not supported as an enum for the field attribute, null will be - /// returned. - public static FieldData? GetFieldData (this ISymbol symbol) where T : Enum - => GetAttribute> (symbol, AttributesNames.GetFieldAttributeName, FieldData.TryParse); - - /// - /// Returns if a type is blittable or not. - /// - /// - /// - /// - public static bool IsBlittable (this ITypeSymbol symbol) - { - if (symbol.NullableAnnotation == NullableAnnotation.Annotated) - return false; - - while (true) { - // per the documentation, the following system types are blittable - switch (symbol.SpecialType) { - case SpecialType.System_Byte: - case SpecialType.System_SByte: - case SpecialType.System_Int16: - case SpecialType.System_UInt16: - case SpecialType.System_Int32: - case SpecialType.System_UInt32: - case SpecialType.System_Int64: - case SpecialType.System_UInt64: - case SpecialType.System_Single: - case SpecialType.System_Double: - case SpecialType.System_IntPtr: - case SpecialType.System_UIntPtr: - return true; - case SpecialType.System_Array: - // if we are dealing with an array, an array of blittable elements is blittable - symbol = symbol.ContainingType; - continue; - } - - if (symbol is IArrayTypeSymbol arrayTypeSymbol) { - symbol = arrayTypeSymbol.ElementType; - continue; - } - - if (symbol.TypeKind == TypeKind.Enum && symbol is INamedTypeSymbol enumSymbol) { - // an enum is blittable based on its backing field - symbol = enumSymbol.EnumUnderlyingType!; - continue; - } - - // if we are dealing with a structure, we have to check the layout type and all its children - if (symbol.TypeKind == TypeKind.Struct) { - // Check for StructLayout attribute with LayoutKind.Sequential - var layoutAttribute = symbol.GetAttributes () - .FirstOrDefault (attr => attr.AttributeClass?.ToString () == typeof (StructLayoutAttribute).FullName); - - if (layoutAttribute is not null) { - var layoutKind = (LayoutKind) layoutAttribute.ConstructorArguments [0].Value!; - if (layoutKind == LayoutKind.Auto) { - return false; - } - } else { - return false; - } - - // Recursively check all fields of the struct - var instanceFields = symbol.GetMembers () - .OfType () - .Where (field => !field.IsStatic); - foreach (var member in instanceFields) { - if (!member.Type.IsBlittable ()) { - return false; - } - } - - return true; - } - - // any other types are not blittable - return false; - } - } - - /// - /// Returns the parents and all the implemented interfaces (including those of the parents). - /// - /// The symbol whose inheritance we want to retrieve. - /// If the type implements the INativeObject interface. - /// An immutable array of the parents in order from closest to furthest. - /// All implemented interfaces by the type and its parents. - /// If the type inherits from NSObject. - public static void GetInheritance ( - this ITypeSymbol symbol, out bool isNSObject, out bool isNativeObject, out ImmutableArray parents, out ImmutableArray interfaces) - { - const string nativeObjectInterface = "ObjCRuntime.INativeObject"; - const string nsObjectClass = "Foundation.NSObject"; - - isNSObject = false; - isNativeObject = false; - - // parents will be returned directly in a Immutable array via a builder since the order is important - // interfaces will use a hash set because we do not want duplicates. - var parentsBuilder = ImmutableArray.CreateBuilder (); - // init the set with all the interfaces of the current symbol - var interfacesSet = new HashSet (symbol.Interfaces.Select (i => i.ToDisplayString ())); - - var currentType = symbol.BaseType; - while (currentType is not null) { - // check if we reach the NSObject as a parent - var parentName = currentType.ToDisplayString ().Trim (); - isNSObject |= parentName == nsObjectClass; - parentsBuilder.Add (parentName); - - // union with the current interfaces - interfacesSet.UnionWith (currentType.Interfaces.Select (i => i.ToDisplayString ())); - - currentType = currentType.BaseType; - } - - isNativeObject = interfacesSet.Contains (nativeObjectInterface); - parents = parentsBuilder.ToImmutable (); - interfaces = [.. interfacesSet]; - } -} diff --git a/src/rgen/Microsoft.Macios.Generator/Formatters/ParameterFormatter.cs b/src/rgen/Microsoft.Macios.Generator/Formatters/ParameterFormatter.cs index e2805069b386..5e8b9d4c8582 100644 --- a/src/rgen/Microsoft.Macios.Generator/Formatters/ParameterFormatter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Formatters/ParameterFormatter.cs @@ -37,21 +37,21 @@ public static ParameterListSyntax GetParameterList (this in ImmutableArray (OmittedArraySizeExpression ())))); - return parameter.IsNullable + return parameter.Type.IsNullable ? NullableType (arrayType) : arrayType; } // dealing with a non-array type - return parameter.IsNullable - ? NullableType (IdentifierName (parameter.Type)) - : IdentifierName (parameter.Type); + return parameter.Type.IsNullable + ? NullableType (IdentifierName (parameter.Type.FullyQualifiedName)) + : IdentifierName (parameter.Type.FullyQualifiedName); } public static ParameterSyntax ToDeclaration (this in ParameterDataModel parameter) diff --git a/src/rgen/Microsoft.Macios.Generator/Formatters/PropertyFormatter.cs b/src/rgen/Microsoft.Macios.Generator/Formatters/PropertyFormatter.cs index 51d573c83f7b..a5c8fe1f4dcd 100644 --- a/src/rgen/Microsoft.Macios.Generator/Formatters/PropertyFormatter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Formatters/PropertyFormatter.cs @@ -9,22 +9,28 @@ namespace Microsoft.Macios.Generator.Formatters; static class PropertyFormatter { + /// /// Return the declaration represented by the given property. /// /// The property whose declaration we want to generate. /// A compilation unit syntax node with the declaration of the property. - public static CompilationUnitSyntax? ToDeclaration (this in Property? property) + public static CompilationUnitSyntax ToDeclaration (this in Property property) { - if (property is null) - return null; - var compilationUnit = CompilationUnit ().WithMembers ( SingletonList ( PropertyDeclaration ( - type: property.Value.ReturnType.GetIdentifierSyntax (), - identifier: Identifier (property.Value.Name)) - .WithModifiers (TokenList (property.Value.Modifiers)))).NormalizeWhitespace (); + type: property.ReturnType.GetIdentifierSyntax (), + identifier: Identifier (property.Name)) + .WithModifiers (TokenList (property.Modifiers)))).NormalizeWhitespace (); return compilationUnit; } + + /// + /// Return the declaration represented by the given property. + /// + /// The property whose declaration we want to generate. + /// A compilation unit syntax node with the declaration of the property. + public static CompilationUnitSyntax? ToDeclaration (this in Property? property) + => property?.ToDeclaration (); } diff --git a/src/rgen/Microsoft.Macios.Generator/Formatters/SmartEnumFormatter.cs b/src/rgen/Microsoft.Macios.Generator/Formatters/SmartEnumFormatter.cs index 43ea585f060f..e34102170cdf 100644 --- a/src/rgen/Microsoft.Macios.Generator/Formatters/SmartEnumFormatter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Formatters/SmartEnumFormatter.cs @@ -16,7 +16,7 @@ static class SmartEnumFormatter { /// The smart enum code change. /// The name to use for the extension class. /// The class declaration for the extension class for a smart enum change. - public static CompilationUnitSyntax ToSmartEnumExtensionDeclaration (this in CodeChanges smartEnumChange, + public static CompilationUnitSyntax ToSmartEnumExtensionDeclaration (this in Binding smartEnumChange, string extensionClassName) { // add to a set to make sure we do no duplicate them and make sure static and partial are present @@ -40,7 +40,7 @@ public static CompilationUnitSyntax ToSmartEnumExtensionDeclaration (this in Cod /// The smart enum code change. /// The name to use for the extension class. /// The class declaration for the extension class for a smart enum change. - public static CompilationUnitSyntax? ToSmartEnumExtensionDeclaration (this in CodeChanges? smartEnumChange, + public static CompilationUnitSyntax? ToSmartEnumExtensionDeclaration (this in Binding? smartEnumChange, string extensionClassName) => smartEnumChange is null ? null : ToSmartEnumExtensionDeclaration (smartEnumChange.Value, extensionClassName); } diff --git a/src/rgen/Microsoft.Macios.Generator/Formatters/TypeInfoFormatter.cs b/src/rgen/Microsoft.Macios.Generator/Formatters/TypeInfoFormatter.cs index 5406e34d00f1..a72717656163 100644 --- a/src/rgen/Microsoft.Macios.Generator/Formatters/TypeInfoFormatter.cs +++ b/src/rgen/Microsoft.Macios.Generator/Formatters/TypeInfoFormatter.cs @@ -17,7 +17,7 @@ public static TypeSyntax GetIdentifierSyntax (this in TypeInfo typeInfo) // reduce the surprise factor for a customer debugging the generated code. var name = typeInfo.SpecialType is SpecialType.System_IntPtr or SpecialType.System_UIntPtr ? typeInfo.MetadataName! // we know is not null - : typeInfo.Name; + : typeInfo.FullyQualifiedName; if (typeInfo.IsArray) { // could be a params array or simply an array diff --git a/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.Generator.cs b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.Generator.cs new file mode 100644 index 000000000000..32f61d6a54e0 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.Generator.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using Microsoft.Macios.Generator.Attributes; +using ObjCRuntime; + +namespace Microsoft.Macios.Generator.IO; + +partial class TabbedStringBuilder { + + public TabbedStringBuilder AppendExportData (in ExportData exportData) where T : Enum + { + // Try to write the smaller amount of data. We are using the old ExportAttribute until we make the final move + if (exportData.ArgumentSemantic != ArgumentSemantic.None) { + WriteLine ($"[Export (\"{exportData.Selector}\", ArgumentSemantic.{exportData.ArgumentSemantic})]"); + } else { + WriteLine ($"[Export (\"{exportData.Selector}\")]"); + } + return this; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.cs b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.cs new file mode 100644 index 000000000000..5d815eb27fdb --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilder.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; +using System.Text; + +namespace Microsoft.Macios.Generator.IO; + +/// +/// String builder wrapper that keeps track of the current indentation level by abusing the IDisposable pattern. Rather +/// than dispose data, what the IDisposable pattern allows is to create a new block with an increased indentation, that +/// way we do not need to keep track of the current indentation level. +/// +/// var classBlock = new TabbedStringBuilder (sb); +/// classBlock.AppendLine ("public static NSString? GetConstant (this {enumSymbol.Name} self)"); +/// // open a new {} block, no need to keep track of the indentation, the new block has it +/// using (var getConstantBlock = classBlock.CreateBlock (isBlock: true)) { +/// // write the contents of the method here. +/// } +/// +/// +partial class TabbedStringBuilder : TabbedWriter { + + /// + /// Created a new tabbed string builder that will use the given sb to write code. + /// + /// The string builder to be used to write code. + /// The original tab size. + /// States if we are creating a {} block. + public TabbedStringBuilder (StringBuilder builder, int currentCount = 0, bool block = false) + : base (new StringWriter (builder), currentCount, block) { } + + /// + /// Create a new block with the given line. This method can be used to write if/else statements. + /// + /// The new line to append + /// If the new line should considered a block. + /// The current builder. + public override TabbedWriter CreateBlock (string line, bool block) + { + if (!string.IsNullOrEmpty (line)) { + Writer.WriteLine (line); + } + + return new TabbedStringBuilder (InnerWriter.GetStringBuilder (), Writer.Indent, block); + } + + /// + /// Return code as a string. + /// + /// The code written so far. + public string ToCode () + { + // we need to make sure that if we are a block, that we close it + if (IsBlock) { + Writer.Flush (); + Writer.Indent -= 1; + Writer.WriteLine ('}'); + IsBlock = false; + } + return InnerWriter.GetStringBuilder ().ToString (); + } + + /// + /// Clear the content of the internal string builder. + /// + public void Clear () + { + if (Writer.InnerWriter is StringWriter stringWriter) { + stringWriter.GetStringBuilder ().Clear (); + } else { + Writer.InnerWriter.Flush (); + } + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderAvailability.cs b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderAvailability.cs new file mode 100644 index 000000000000..e8c584b18c28 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderAvailability.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; +using Microsoft.Macios.Generator.Availability; +using Xamarin.Utils; + +namespace Microsoft.Macios.Generator.IO; + +static class TabbedStringBuilderAvailability { + + public static TabbedWriter AppendMemberAvailability (this TabbedWriter self, in SymbolAvailability allPlatformsAvailability) + { + foreach (var availability in allPlatformsAvailability.PlatformAvailabilities) { + var platformName = availability.Platform.AsString ().ToLower (); + if (availability.SupportedVersion is not null) { + var versionStr = (PlatformAvailability.IsDefaultVersion (availability.SupportedVersion)) + ? string.Empty + : availability.SupportedVersion.ToString (); + self.WriteLine ($"[SupportedOSPlatform (\"{platformName}{versionStr}\")]"); + } + + // loop over the unsupported versions of the platform + foreach (var (version, message) in availability.UnsupportedVersions) { + var versionStr = (PlatformAvailability.IsDefaultVersion (version)) ? string.Empty : version.ToString (); + if (message is null) { + self.WriteLine ($"[UnsupportedOSPlatform (\"{platformName}{versionStr}\")]"); + } else { + self.WriteLine ($"[UnsupportedOSPlatform (\"{platformName}{versionStr}\", \"{message}\")]"); + } + } + + // loop over the obsolete versions of the platform + foreach (var (version, obsoleteInfo) in availability.ObsoletedVersions) { + var versionStr = (PlatformAvailability.IsDefaultVersion (version)) ? string.Empty : version.ToString (); + + switch (obsoleteInfo) { + case (null, null): + self.WriteLine ($"[ObsoletedOSPlatform (\"{platformName}{versionStr}\")]"); + break; + case (not null, null): + self.WriteLine ($"[ObsoletedOSPlatform (\"{platformName}{versionStr}\", \"{obsoleteInfo.Message}\")]"); + break; + case (null, not null): + self.WriteLine ($"[ObsoletedOSPlatform (\"{platformName}{versionStr}\", Url=\"{obsoleteInfo.Url}\")]"); + break; + case (not null, not null): + self.WriteLine ( + $"[ObsoletedOSPlatform (\"{platformName}{versionStr}\", \"{obsoleteInfo.Message}\", Url=\"{obsoleteInfo.Url}\")]"); + break; + } + } + } + + return self; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderExtensions.cs b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderExtensions.cs new file mode 100644 index 000000000000..2fbe23d81cff --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/IO/TabbedStringBuilderExtensions.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.IO; + +namespace Microsoft.Macios.Generator.IO; + +static class TabbedStringBuilderExtensions { + /// + /// Append the generated code attribute to the current string builder. Added for convenience. + /// + /// A tabbed string builder. + /// If the binding is Optimizable or not. + /// The current builder. + public static TabbedWriter AppendGeneratedCodeAttribute (this TabbedWriter self, bool optimizable = true) + { + if (optimizable) { + const string attr = "[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]"; + self.WriteLine (attr); + } else { + const string attr = "[BindingImpl (BindingImplOptions.GeneratedCode)]"; + self.WriteLine (attr); + } + + return self; + } + + /// + /// Append the notification advice attribute to the current string builder. Added for convenience. + /// + /// A tabbed string builder. + /// The class that contains the notification. + /// The name of the notification. + /// + public static TabbedWriter AppendNotificationAdvice (this TabbedWriter self, in string className, in string notification) + { + string attr = + $"[Advice (\"Use '{className}.Notifications.{notification}' helper method instead.\")]"; + self.WriteLine (attr); + return self; + } + + /// + /// Append a EditorBrowsable attribute. Added for convenience. + /// + /// A tabbed string builder. + /// The current builder. + public static TabbedWriter AppendEditorBrowsableAttribute (this TabbedWriter self, EditorBrowsableState state) + { + string attr = $"[EditorBrowsable (EditorBrowsableState.{state})]"; + self.WriteLine (attr); + return self; + } + + /// + /// Append the designated initializer attribute to the current string builder. Added for convenience. + /// + /// A tabbed string builder. + /// The current builder. + public static TabbedWriter AppendDesignatedInitializer (this TabbedWriter self) + { + const string attr = "[DesignatedInitializer]"; + self.WriteLine (attr); + return self; + } + + /// + /// Writes the autogenerated header and other pragmas. + /// + /// A tabbed string builder. + /// The current builder. + public static TabbedWriter WriteHeader (this TabbedWriter self) + { + // let people know this is generated code + self.WriteLine ("// "); + + // enable nullable! + self.WriteLine (); + self.WriteLine ("#nullable enable"); + self.WriteLine (); + return self; + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/IO/TabbedWriter.cs b/src/rgen/Microsoft.Macios.Generator/IO/TabbedWriter.cs new file mode 100644 index 000000000000..0251ef289200 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Generator/IO/TabbedWriter.cs @@ -0,0 +1,341 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Macios.Generator.IO; + +abstract class TabbedWriter : IDisposable, IAsyncDisposable where T : TextWriter { + readonly SemaphoreSlim indentationSemaphore = new SemaphoreSlim (1, 1); + protected readonly IndentedTextWriter Writer; + protected readonly T InnerWriter; + protected bool IsBlock; + + /// + /// Created a new tabbed string builder that will use the given sb to write code. + /// + /// The string builder to be used to write code. + /// The original tab size. + /// States if we are creating a {} block. + public TabbedWriter (T innerTextWriter, int currentCount = 0, bool block = false) + { + InnerWriter = innerTextWriter; + Writer = new IndentedTextWriter (innerTextWriter, "\t"); + IsBlock = block; + if (IsBlock) { + // increase by 1 because we are in a block + Writer.Indent = currentCount; + Writer.WriteLine ('{'); + Writer.Indent += 1; + } else { + Writer.Indent = currentCount; + } + Writer.Flush (); + } + + /// + /// Append a new empty line to the string builder using no tabs since it is empty. + /// + /// The current tabbed string builder. + public TabbedWriter WriteLine () + { + var oldIndent = Writer.Indent; + Writer.Indent = 0; + Writer.WriteLine (); + Writer.Indent = oldIndent; + return this; + } + + /// + /// Append a new empty line to the string builder using no tabs since it is empty. + /// + /// The current tabbed string builder. + public async Task> WriteLineAsync () + { + // because we are dealing with a method that changes the indentaiton DURING the write, we need + // to lock the writer to make sure that the indentation is correct. + await indentationSemaphore.WaitAsync (); + try { + var oldIndent = Writer.Indent; + Writer.Indent = 0; + await Writer.WriteLineAsync (); + Writer.Indent = oldIndent; + } finally { + indentationSemaphore.Release (); + } + + return this; + } + + /// + /// Append content, but do not add a \n + /// + /// The content to append. + /// The current builder. + public TabbedWriter Write (string line) + { + if (!string.IsNullOrWhiteSpace (line)) { + Writer.Write (line); + } + + return this; + } + + /// + /// Append content, but do not add a \n + /// + /// The content to append. + /// The current builder. + public async Task> WriteAsync (string line) + { + if (!string.IsNullOrWhiteSpace (line)) { + await Writer.WriteAsync (line); + } + + return this; + } + + /// + /// Append content, but do not add a \n + /// + /// The content to append. + /// The current builder. + public TabbedWriter Write (ReadOnlySpan span) + { + if (!span.IsWhiteSpace ()) { + Writer.Write (span); + } + + return this; + } + + /// + /// Append a new tabbed line. + /// + /// The line to append. + /// The current builder. + public TabbedWriter WriteLine (string line) + { + if (string.IsNullOrWhiteSpace (line)) { + WriteLine (); + } else { + Writer.WriteLine (line); + } + + return this; + } + + /// + /// Append a new tabbed line. + /// + /// The line to append. + /// The current builder. + public async Task> WriteLineAsync (string line) + { + if (string.IsNullOrWhiteSpace (line)) { + await WriteLineAsync (); + } else { + await Writer.WriteLineAsync (line); + } + + return this; + } + + /// + /// Append a new tabbed lien from the span. + /// + /// The line to append. + /// The current builder. + public TabbedWriter WriteLine (ReadOnlySpan span) + { + if (span.IsWhiteSpace ()) { + WriteLine (); + } else { + Writer.WriteLine (span); + } + + return this; + } + +#if NET9_0 + public TabbedWriter Write (ref DefaultInterpolatedStringHandler handler) + { + Writer.Write (handler.ToStringAndClear ()); + return this; + } + + public TabbedWriter WriteLine (ref DefaultInterpolatedStringHandler handler) + { + Writer.WriteLine (handler.ToStringAndClear ()); + return this; + } + + /// + /// Append a new raw literal by prepending the correct indentation. + /// + /// The raw string to append. + /// The current builder. + public TabbedWriter WriteRaw (string rawString) + { + // we will split the raw string in lines and then append them so that the + // tabbing is correct + var lines = rawString.AsSpan().Split('\n'); + var enumerator = lines.GetEnumerator(); + bool hasNext = enumerator.MoveNext(); + while (hasNext) + { + var range = enumerator.Current; + var line = rawString.AsSpan(range); + hasNext = enumerator.MoveNext(); + if (!hasNext) + { + Write (line); + break; + } + WriteLine (line); + } + return this; + } + +#else + /// + /// Append a new raw literal by prepending the correct indentation. + /// + /// The raw string to append. + /// The current builder. + public TabbedWriter WriteRaw (string rawString) + { + // we will split the raw string in lines and then append them so that the + // tabbing is correct + var lines = rawString.Split (['\n'], StringSplitOptions.None); + for (var index = 0; index < lines.Length; index++) { + var line = lines [index]; + if (index == lines.Length - 1) { + Write (line); + } else { + WriteLine (line); + } + } + return this; + } +#endif + + /// + /// Append a new raw literal by prepending the correct indentation. + /// + /// The raw string to append. + /// The current builder. + public async Task> WriteRawAsync (string rawString) + { + // we will split the raw string in lines and then append them so that the + // tabbing is correct + var lines = rawString.Split (['\n'], StringSplitOptions.None); + for (var index = 0; index < lines.Length; index++) { + var line = lines [index]; + if (index == lines.Length - 1) { + await WriteAsync (line); + } else { + await WriteLineAsync (line); + } + } + return this; + } + + /// + /// Create a new block with the given line. This method can be used to write if/else statements. + /// + /// The new line to append + /// If the new line should considered a block. + /// The current builder. + public abstract TabbedWriter CreateBlock (string line, bool block); + + /// + /// Create a bew empty block. + /// + /// If it is a block that uses {} or not. + /// The new bloc. + public TabbedWriter CreateBlock (bool block) => CreateBlock (string.Empty, block); + + /// + /// Concatenate an array of lines as a single block. The generated code is similar to the following + /// + /// + /// using (var nsobject = Create ()) + /// using (var nsstring = Create ()) + /// using (var x = new NSString ()) { + /// // your code goes here. + /// } + /// + /// + /// The lines to concatenate. + /// True if the block should use braces, false otherwise. + /// + public TabbedWriter CreateBlock (IEnumerable lines, bool block) + { + var array = lines as string [] ?? lines.ToArray (); + if (array.Length == 0) { + return CreateBlock (IsBlock); + } + + // append all the lines, then create a block + for (var i = 0; i < array.Length - 1; i++) { + Writer.WriteLine (array [i]); + } + return CreateBlock (array [^1], block); + } + + public virtual void Close () + { + // if we are closing, and it is a block, we need to close the block + if (IsBlock) { + Writer.Indent -= 1; + Writer.WriteLine ('}'); + IsBlock = false; + } + Writer.Flush (); + } + + public virtual async Task CloseAsync () + { + // if we are closing, and it is a block, we need to close the block + if (IsBlock) { + Writer.Indent -= 1; + await Writer.WriteLineAsync ('}'); + IsBlock = false; + } + await Writer.FlushAsync (); + } + + protected virtual void Dispose (bool disposing) + { + if (disposing) { + Close (); + Writer.Dispose (); + } + } + + /// + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + public async ValueTask DisposeAsync () + { + if (indentationSemaphore is IAsyncDisposable indentationSemaphoreAsyncDisposable) + await indentationSemaphoreAsyncDisposable.DisposeAsync (); + else + indentationSemaphore.Dispose (); + await CloseAsync (); + await Writer.DisposeAsync (); + await InnerWriter.DisposeAsync (); + } +} diff --git a/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj b/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj index a665eeb811f0..36e3c26124e0 100644 --- a/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj +++ b/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj @@ -34,6 +34,9 @@ external\PlatformNameExtensions.cs + + external\Registrar.core.cs + True True diff --git a/src/rgen/Microsoft.Macios.Generator/TabbedStringBuilder.cs b/src/rgen/Microsoft.Macios.Generator/TabbedStringBuilder.cs deleted file mode 100644 index 7d650808de07..000000000000 --- a/src/rgen/Microsoft.Macios.Generator/TabbedStringBuilder.cs +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -using System; -using System.ComponentModel; -using System.Linq; -using System.Net.Http; -using System.Net.Mail; -using System.Runtime.CompilerServices; -using System.Security.Cryptography; -using System.Text; -using Microsoft.Macios.Generator.Availability; -using Microsoft.Macios.Generator.DataModel; -using Xamarin.Utils; - -namespace Microsoft.Macios.Generator; - -/// -/// String builder wrapper that keeps track of the current indentation level by abusing the IDisposable pattern. Rather -/// than dispose data, what the IDisposable pattern allows is to create a new block with an increased indentation, that -/// way we do not need to keep track of the current indentation level. -/// -/// var classBlock = new TabbedStringBuilder (sb); -/// classBlock.AppendLine ("public static NSString? GetConstant (this {enumSymbol.Name} self)"); -/// // open a new {} block, no need to keep track of the indentation, the new block has it -/// using (var getConstantBlock = classBlock.CreateBlock (isBlock: true)) { -/// // write the contents of the method here. -/// } -/// -/// -class TabbedStringBuilder : IDisposable { - readonly StringBuilder sb; - readonly uint tabCount; - readonly bool isBlock; - bool disposed; - - /// - /// Created a new tabbed string builder that will use the given sb to write code. - /// - /// The string builder to be used to write code. - /// The original tab size. - /// States if we are creating a {} block. - public TabbedStringBuilder (StringBuilder builder, uint currentCount = 0, bool block = false) - { - sb = builder; - isBlock = block; - if (isBlock) { - // increase by 1 because we are in a block - tabCount = currentCount; - WriteTabs ().Append ('{').AppendLine (); - tabCount++; - } else { - tabCount = currentCount; - } - } - - StringBuilder WriteTabs () => sb.Append ('\t', (int) tabCount); - - /// - /// Append a new empty line to the string builder using the correct tab size. - /// - /// The current tabbed string builder. - public TabbedStringBuilder AppendLine () - { - sb.AppendLine (); - return this; - } - - /// - /// Append conteng, but do not add a \n - /// - /// The content to append. - /// The current builder. - public TabbedStringBuilder Append (string line) - { - if (string.IsNullOrWhiteSpace (line)) { - sb.Append (line); - } else { - WriteTabs ().Append (line); - } - - return this; - } - - /// - /// Append conteng, but do not add a \n - /// - /// The content to append. - /// The current builder. - public TabbedStringBuilder Append (ReadOnlySpan span) - { - if (span.IsWhiteSpace ()) { - sb.Append (span); - } else { - WriteTabs ().Append (span); - } - - return this; - } - - /// - /// Append a new tabbed line. - /// - /// The line to append. - /// The current builder. - public TabbedStringBuilder AppendLine (string line) - { - if (string.IsNullOrWhiteSpace (line)) { - sb.AppendLine (line); - } else { - WriteTabs ().AppendLine (line); - } - - return this; - } - - /// - /// Append a new tabbed lien from the span. - /// - /// The line to append. - /// The current builder. - public TabbedStringBuilder AppendLine (ReadOnlySpan span) - { - if (span.IsWhiteSpace ()) { - sb.Append (span).AppendLine (); - } else { - WriteTabs ().Append (span).AppendLine (); - } - - return this; - } - - public TabbedStringBuilder Append (ref DefaultInterpolatedStringHandler handler) - { - WriteTabs ().Append (handler.ToStringAndClear ()); - return this; - } - - public TabbedStringBuilder AppendLine (ref DefaultInterpolatedStringHandler handler) - { - WriteTabs ().Append (handler.ToStringAndClear ()).AppendLine (); - return this; - } - - /// - /// Append a new raw literal by prepending the correct indentation. - /// - /// The raw string to append. - /// The current builder. - public TabbedStringBuilder AppendRaw (string rawString) - { - // we will split the raw string in lines and then append them so that the - // tabbing is correct - var lines = rawString.AsSpan ().Split ('\n'); - var count = 0; - foreach (var range in lines) { - if (count > 0) - AppendLine (); - var line = rawString.AsSpan (range); - Append (line); - count++; - } - - return this; - } - - /// - /// Append the generated code attribute to the current string builder. Added for convenience. - /// - /// If the binding is Optimizable or not. - /// The current builder. - public TabbedStringBuilder AppendGeneratedCodeAttribute (bool optimizable = true) - { - if (optimizable) { - const string attr = "[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]"; - AppendLine (attr); - } else { - const string attr = "[BindingImpl (BindingImplOptions.GeneratedCode)]"; - AppendLine (attr); - } - - return this; - } - - public TabbedStringBuilder AppendMemberAvailability (in SymbolAvailability allPlatformsAvailability) - { - foreach (var availability in allPlatformsAvailability.PlatformAvailabilities) { - var platformName = availability.Platform.AsString ().ToLower (); - if (availability.SupportedVersion is not null) { - var versionStr = (PlatformAvailability.IsDefaultVersion (availability.SupportedVersion)) - ? string.Empty - : availability.SupportedVersion.ToString (); - AppendLine ($"[SupportedOSPlatform (\"{platformName}{versionStr}\")]"); - } - - // loop over the unsupported versions of the platform - foreach (var (version, message) in availability.UnsupportedVersions) { - var versionStr = (PlatformAvailability.IsDefaultVersion (version)) ? string.Empty : version.ToString (); - if (message is null) { - AppendLine ($"[UnsupportedOSPlatform (\"{platformName}{versionStr}\")]"); - } else { - AppendLine ($"[UnsupportedOSPlatform (\"{platformName}{versionStr}\", \"{message}\")]"); - } - } - - // loop over the obsolete versions of the platform - foreach (var (version, obsoleteInfo) in availability.ObsoletedVersions) { - var versionStr = (PlatformAvailability.IsDefaultVersion (version)) ? string.Empty : version.ToString (); - - switch (obsoleteInfo) { - case (null, null): - AppendLine ($"[ObsoletedOSPlatform (\"{platformName}{versionStr}\")]"); - break; - case (not null, null): - AppendLine ($"[ObsoletedOSPlatform (\"{platformName}{versionStr}\", \"{obsoleteInfo.Message}\")]"); - break; - case (null, not null): - AppendLine ($"[ObsoletedOSPlatform (\"{platformName}{versionStr}\", Url=\"{obsoleteInfo.Url}\")]"); - break; - case (not null, not null): - AppendLine ( - $"[ObsoletedOSPlatform (\"{platformName}{versionStr}\", \"{obsoleteInfo.Message}\", Url=\"{obsoleteInfo.Url}\")]"); - break; - } - } - } - - return this; - } - - /// - /// Append a EditorBrowsable attribute. Added for convenience. - /// - /// The current builder. - public TabbedStringBuilder AppendEditorBrowsableAttribute (EditorBrowsableState state) - { - string attr = $"[EditorBrowsable (EditorBrowsableState.{state})]"; - AppendLine (attr); - return this; - } - - public TabbedStringBuilder AppendDesignatedInitializer () - { - const string attr = "[DesignatedInitializer]"; - AppendLine (attr); - return this; - } - - /// - /// Writes the autogenerated header and other pragmas. - /// - /// The current builder. - public TabbedStringBuilder WriteHeader () - { - // let people know this is generated code - AppendLine ("// "); - - // enable nullable! - AppendLine (); - AppendLine ("#nullable enable"); - AppendLine (); - return this; - } - - /// - /// Create a bew empty block. - /// - /// If it is a block that uses {} or not. - /// The new bloc. - public TabbedStringBuilder CreateBlock (bool block) => CreateBlock (string.Empty, block); - - /// - /// Create a new block with the given line. This method can be used to write if/else statements. - /// - /// The new line to append - /// If the new line should considered a block. - /// The current builder. - public TabbedStringBuilder CreateBlock (string line, bool block) - { - if (!string.IsNullOrEmpty (line)) { - WriteTabs ().AppendLine (line); - } - - return new TabbedStringBuilder (sb, tabCount, block); - } - - /// - /// Return the string builder as a string. - /// - /// - public override string ToString () - { - Dispose (); - return sb.ToString (); - } - - /// - /// Clear the content of the internal string builder. - /// - public void Clear () - { - sb.Clear (); - } - - /// - /// Does not really dispose anything, it just closes the current block. - /// - public void Dispose () - { - if (disposed || !isBlock) return; - - disposed = true; - sb.Append ('\t', (int) tabCount - 1); - sb.Append ('}').AppendLine (); - } -} diff --git a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/AttributeType.cs b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/AttributeType.cs new file mode 100644 index 000000000000..9548f874b006 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/AttributeType.cs @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Macios.Transformer.Generator; + +public enum AttributeType { + None, + Flag, + Data, +} diff --git a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingAttributeData.cs b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingAttributeData.cs new file mode 100644 index 000000000000..c2c5ea00819a --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingAttributeData.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Generator.Attributes; + +readonly struct BindingAttributeData { + + public static string Name = "BindingAttributeAttribute"; + public static string Source = @"// +using System; + +namespace Microsoft.Macios.Transformer.Generator; + +[AttributeUsage(AttributeTargets.Field)] +public class BindingAttributeAttribute(Type dataModelType, AttributeTargets target = AttributeTargets.All) : System.Attribute { + + public Type DataModelType { get; } = dataModelType; + public AttributeTargets Target { get; } = target; + + public BindingAttributeAttribute (Type dataModelType) : this (dataModelType, AttributeTargets.All) { } +} +"; + + public string DataModelType { get; } // is a type in the attribute, but we do not care for the transformation + public AttributeTargets Target { get; } + + public BindingAttributeData (string dataModelType) + { + DataModelType = dataModelType; + } + + public BindingAttributeData (string dataModelType, AttributeTargets targets) + { + DataModelType = dataModelType; + Target = targets; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out BindingAttributeData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string baseType; + var target = AttributeTargets.All; + + // custom marshal directive values + + switch (count) { + case 1: + baseType = ((INamedTypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + break; + case 2: + baseType = ((INamedTypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + target = (AttributeTargets) attributeData.ConstructorArguments [1].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (baseType, target); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "Target": + target = (AttributeTargets) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (baseType, target); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingFlagData.cs b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingFlagData.cs new file mode 100644 index 000000000000..8419ac643398 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Attributes/BindingFlagData.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Generator.Attributes; + +/// +/// Struct representing the data of a Binding attribute. +/// +readonly struct BindingFlagData { + public static string Name = "BindingFlagAttribute"; + public static string Source = @"// +using System; + +namespace Microsoft.Macios.Transformer.Generator; + +[AttributeUsage(AttributeTargets.Field)] +public class BindingFlagAttribute(AttributeTargets target = AttributeTargets.All) : System.Attribute { + public AttributeTargets Target { get; } = target; +} +"; + public AttributeTargets Target { get; } + + public BindingFlagData (AttributeTargets target) + { + Target = target; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out BindingFlagData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + AttributeTargets target; + switch (count) { + case 1: + target = (AttributeTargets) attributeData.ConstructorArguments [0].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + data = new (target); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj new file mode 100644 index 000000000000..f5ded35508aa --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj @@ -0,0 +1,38 @@ + + + + netstandard2.1 + false + enable + latest + + true + true + true + + Microsoft.Macios.Transformer.Generator + Microsoft.Macios.Transformer.Generator + + RS2007;RS1041;APL0003 + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + TabbedStringBuilder.cs + + + TabbedWriter.cs + + + + + diff --git a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Properties/launchSettings.json b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Properties/launchSettings.json new file mode 100644 index 000000000000..798e8ddd7ccc --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Properties/launchSettings.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "DebugRoslynSourceGenerator": { + "commandName": "DebugRoslynComponent", + "targetProject": "../Microsoft.Macios.Transformer.Generator.Sample/Microsoft.Macios.Transformer.Generator.Sample.csproj" + } + } +} \ No newline at end of file diff --git a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/XamarinBindingAPIGenerator.cs b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/XamarinBindingAPIGenerator.cs new file mode 100644 index 000000000000..12bdce689603 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/XamarinBindingAPIGenerator.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using Microsoft.Macios.Generator; +using Microsoft.Macios.Generator.IO; +using Microsoft.Macios.Transformer.Generator.Attributes; + + +namespace Microsoft.Macios.Transformer.Generator; + +/// +/// Generator that will write the needed code to parse the old Xamarin API in the transformer. The +/// idea is that there is a lot of code that is needed by the tansformer that can be generated. +/// +[Generator] +public class XamarinBindingAPIGenerator : IIncrementalGenerator { + const string Namespace = "Microsoft.Macios.Transformer.Generator"; + + public void Initialize (IncrementalGeneratorInitializationContext context) + { + // Add the marker attribute to the compilation. + context.RegisterPostInitializationOutput (ctx => ctx.AddSource ( + "BindingFlagAttribute.g.cs", + SourceText.From (BindingFlagData.Source, Encoding.UTF8))); + + context.RegisterPostInitializationOutput (ctx => ctx.AddSource ( + "BindingAttributeAttribute.g.cs", + SourceText.From (BindingAttributeData.Source, Encoding.UTF8))); + + // Filter the [BindingFlagAttribute] annotate fields. + var provider = context.SyntaxProvider + .CreateSyntaxProvider ( + (s, _) => s is FieldDeclarationSyntax, + (ctx, _) => GetClassDeclarationForSourceGen (ctx)) + .Where (t => t.attrType != AttributeType.None); + + // Generate the source code. + context.RegisterSourceOutput (context.CompilationProvider.Combine (provider.Collect ()), + ((ctx, t) => GenerateCode (ctx, t.Left, t.Right))); + } + + static (FieldDeclarationSyntax, AttributeType attrType) GetClassDeclarationForSourceGen ( + GeneratorSyntaxContext context) + { + var declarationSyntax = Unsafe.As (context.Node); + + // Go through all attributes of the field + foreach (AttributeListSyntax attributeListSyntax in declarationSyntax.AttributeLists) { + foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) { + if (context.SemanticModel.GetSymbolInfo (attributeSyntax).Symbol is not IMethodSymbol attributeSymbol) + continue; // if we can't get the symbol, ignore it + + string attributeName = attributeSymbol.ContainingType.ToDisplayString (); + + if (attributeName == $"{Namespace}.{BindingFlagData.Name}") + return (declarationSyntax, AttributeType.Flag); + if (attributeName == $"{Namespace}.{BindingAttributeData.Name}") + return (declarationSyntax, AttributeType.Data); + } + } + + return (declarationSyntax, AttributeType.None); + } + + static string [] GetFlagsForTarget (Dictionary flags, + AttributeTargets [] targets) + => flags.Where (kv => targets.Any (t => kv.Value.Targets.HasFlag (t))) + .Select (kv => kv.Key) + .ToArray (); + + static (string AttributeFullName, string AttributeName, BindingAttributeData Data) [] GetAttributesForTarget ( + Dictionary dataAttribute, + AttributeTargets [] targets) + // return all the attributes that have at least one of the targets + => dataAttribute.Where (kv => targets.Any (t => kv.Value.Data.Target.HasFlag (t))) + .Select (kv => kv.Value) + .ToArray (); + + + static void WriteFlagProperty (TabbedWriter sb, string flagName) + { + // write the backing field + sb.WriteLine ($"readonly bool _{flagName} = false;"); + using (var flagPropertyBlock = sb.CreateBlock ($"public bool {flagName}", block: true)) { + flagPropertyBlock.WriteLine ($"get => _{flagName};"); + flagPropertyBlock.WriteLine ($"private init => _{flagName} = value;"); + } + } + + static void WriteAttributeProperty (TabbedWriter sb, + (string AttributeFullName, string AttributeName, BindingAttributeData Data) attrData) + { + // add a property that will state if we have the attr, this will help with nullability + sb.WriteLine ($"readonly bool _has{attrData.AttributeName} = false;"); + sb.WriteLine ($"[MemberNotNullWhen (true, nameof ({attrData.AttributeName}))]"); + using (var flagPropertyBlock = sb.CreateBlock ($"public bool Has{attrData.AttributeName}", block: true)) { + flagPropertyBlock.WriteLine ($"get => _has{attrData.AttributeName};"); + flagPropertyBlock.WriteLine ($"private init => _has{attrData.AttributeName} = value;"); + } + sb.WriteLine (); + sb.WriteLine ($"readonly {attrData.Data.DataModelType}? _{attrData.AttributeName} = null;"); + // decorate to help with nullability + using (var attributePropertyBlock = sb.CreateBlock ($"public {attrData.Data.DataModelType}? {attrData.AttributeName}", block: true)) { + attributePropertyBlock.WriteLine ($"get => _{attrData.AttributeName};"); + attributePropertyBlock.WriteLine ($"private init => _{attrData.AttributeName} = value;"); + } + } + + static void WriteDataModelExtension (TabbedStringBuilder sb, string dataModel, string [] flags, + (string AttributeFullName, string AttributeName, BindingAttributeData Data) [] attributes) + { + sb.Clear (); + sb.WriteLine ("// "); + sb.WriteLine ("#nullable enable"); + sb.WriteLine (""); + sb.WriteLine ("using System;"); + sb.WriteLine ("using System.Diagnostics.CodeAnalysis;"); + sb.WriteLine ("using Microsoft.CodeAnalysis;"); + sb.WriteLine ("using Microsoft.Macios.Transformer.Extensions;"); + sb.WriteLine (); + sb.WriteLine ("namespace Microsoft.Macios.Generator.DataModel;"); + sb.WriteLine (); + using (var modelBlock = sb.CreateBlock ($"readonly partial struct {dataModel}", block: true)) { + // add all the properties that will allow us to get the flags make them public getter and private init + // so that they can be set when we add the attr dict. + foreach (var flag in flags) { + modelBlock.WriteLine (); + WriteFlagProperty (modelBlock, flag); + } + + foreach (var attrData in attributes) { + modelBlock.WriteLine (); + WriteAttributeProperty (modelBlock, attrData); + } + + // property to store the dictionary + modelBlock.WriteLine (); + modelBlock.WriteLine ("readonly Dictionary>? _attributesDictionary = null;"); + using (var dictionaryPropertyBlock = + modelBlock.CreateBlock ("public Dictionary>? AttributesDictionary", + block: true)) { + dictionaryPropertyBlock.WriteLine ("get => _attributesDictionary;"); + using (var initBlock = dictionaryPropertyBlock.CreateBlock ("private init", block: true)) { + initBlock.WriteLine ("_attributesDictionary = value;"); + using (var ifBlock = initBlock.CreateBlock ("if (_attributesDictionary is not null)", block: true)) { + foreach (var flag in flags) { + ifBlock.WriteLine ($"{flag} = _attributesDictionary.{flag} ();"); + } + + foreach (var attributeData in attributes) { + // check if the attribute is present, if it is, set the value + ifBlock.WriteLine ($"Has{attributeData.AttributeName} = _attributesDictionary.Has{attributeData.AttributeName} ();"); + using (var attrIfBlock = ifBlock.CreateBlock ($"if (Has{attributeData.AttributeName})", block: true)) { + attrIfBlock.WriteLine ($"{attributeData.AttributeName} = _attributesDictionary.Get{attributeData.AttributeName} ();"); + } + } + } + } + } + } + } + + static void GenerateModelExtension (TabbedStringBuilder sb, string dataModel, + Dictionary flags, + Dictionary attributes, + AttributeTargets [] targets, + SourceProductionContext context) + { + var methodFlags = GetFlagsForTarget (flags, targets); + var methodAttributes = GetAttributesForTarget (attributes, targets); + WriteDataModelExtension (sb, dataModel, methodFlags, methodAttributes); + context.AddSource ($"{dataModel}.Transformer.g.cs", + SourceText.From (sb.ToCode (), Encoding.UTF8)); + } + + static AttributeTargets GetTarget (ISymbol symbol) + { + var attrData = symbol.GetAttributes (); + // loop over attrs, if we find the BindingFlagAttribute, return the target + foreach (var attr in attrData) { + if (attr.AttributeClass?.Name == BindingFlagData.Name + && BindingFlagData.TryParse (attr, out var data)) { + return data.Value.Target; + } + } + + return AttributeTargets.All; + } + + static BindingAttributeData? GetAttributeData (ISymbol symbol) + { + var attrData = symbol.GetAttributes (); + // loop over attrs, if we find the BindingFlagAttribute, return the target + foreach (var attr in attrData) { + if (attr.AttributeClass?.Name == BindingAttributeData.Name + && BindingAttributeData.TryParse (attr, out var data)) { + return data; + } + } + + return null; + } + + void GenerateCode (SourceProductionContext context, Compilation compilation, + ImmutableArray<(FieldDeclarationSyntax Field, AttributeType Type)> declarations) + { + // loop over the fields and create two dictionaries, one for flags and one for data + var flags = new Dictionary (); + var dataAttributes = + new Dictionary (); + + foreach (var (fieldDeclarationSyntax, attrType) in declarations) { + // We need to get semantic model of the class to retrieve metadata. + var semanticModel = compilation.GetSemanticModel (fieldDeclarationSyntax.SyntaxTree); + + switch (attrType) { + // the attr type will let use know what data can be retrieved from the field + case AttributeType.Flag: + GetFlagsFromField (fieldDeclarationSyntax, semanticModel, flags); + break; + case AttributeType.Data: + GetAttributesFromField (fieldDeclarationSyntax, semanticModel, dataAttributes); + break; + } + } + + // all flags are collected, generate the code + var sb = new TabbedStringBuilder (new ()); + GenerateDictionaryExtension (sb, flags, dataAttributes); + + // Add the source code to the compilation. + context.AddSource ("AttributeDataDictionaryExtensions.g.cs", + SourceText.From (sb.ToCode (), Encoding.UTF8)); + +#pragma warning disable format + // generate the extra methods for the data model, group the fields by the model type based on the target + var models = new (string Model, AttributeTargets[] Targets) [] { + ("EnumMember", [AttributeTargets.Field]), + ("Parameter", [AttributeTargets.Parameter]), + ("Accessor", [AttributeTargets.Property]), + ("Property", [AttributeTargets.Property]), + ("Constructor", [AttributeTargets.Constructor]), + ("Method", [AttributeTargets.Method]), + ("Binding", [AttributeTargets.Interface, AttributeTargets.Class, AttributeTargets.Enum, AttributeTargets.Struct]), + ("TypeInfo", [AttributeTargets.Parameter]) + }; +#pragma warning restore format + + foreach (var (model, target) in models) { + GenerateModelExtension (sb, model, flags, dataAttributes, target, context); + } + } + + static void GenerateDictionaryExtension (TabbedStringBuilder sb, + Dictionary flags, + Dictionary dataAttributes) + { + sb.WriteLine ("// "); + sb.WriteLine ("#nullable enable"); + sb.WriteLine ("using System;"); + sb.WriteLine ("using System.Diagnostics.CodeAnalysis;"); + sb.WriteLine ("using Microsoft.CodeAnalysis;"); + sb.WriteLine (); + sb.WriteLine ("namespace Microsoft.Macios.Transformer.Extensions;"); + sb.WriteLine (); + using (var classBlock = sb.CreateBlock ("static class AttributeDataDictionaryExtension", block: true)) { + // loop over the flags and generate a helper static method to retrieve it from a attribute data dict + foreach (var (methodName, attributeName) in flags) { + using (var methodBlock = classBlock.CreateBlock ( + $"public static bool {methodName} (this Dictionary> self)", + block: true)) { + methodBlock.WriteLine ($"return self.ContainsKey ({attributeName.AttributeFullName});"); + } + + classBlock.WriteLine (); + } + + // same operation over the data attributes + foreach (var (methodName, attributeInfo) in dataAttributes) { + // property to check if the attribute is present + using (var methodBlock = classBlock.CreateBlock ( + $"public static bool {methodName} (this Dictionary> self)", + block: true)) { + methodBlock.WriteLine ($"return self.ContainsKey ({attributeInfo.AttributeFullName});"); + } + + classBlock.WriteLine (); + // property to access the attribute + using (var methodBlock = classBlock.CreateBlock ( + $"public static {attributeInfo.Data.DataModelType}? Get{attributeInfo.AttributeName} (this Dictionary> self)", + block: true)) { + methodBlock.WriteRaw ( +$@"if (self.{methodName} ()) {{ + var data = self.GetAttribute<{attributeInfo.Data.DataModelType}> ({attributeInfo.AttributeFullName}, {attributeInfo.Data.DataModelType}.TryParse); + return data; +}} else {{ + return null; +}} +"); + } + + classBlock.WriteLine (); + } + + // add a generic method that will allow use to retrieve an attribute type + classBlock.WriteRaw ( +@"public delegate bool TryParseDelegate (AttributeData attributeData, [NotNullWhen (true)] out T? data) where T : struct; + +public static T? GetAttribute (this Dictionary> self, string attrName, TryParseDelegate tryParse) where T : struct +{ + if (!self.TryGetValue (attrName, out var attrs)) + return null; + + foreach (var attr in attrs) { + if (tryParse (attr, out var data)) + return data.Value; + } + + return null; +} +"); + } + } + + static void GetAttributesFromField (FieldDeclarationSyntax fieldDeclarationSyntax, SemanticModel semanticModel, + Dictionary dataAttributes) + { + foreach (var variableSyntax in fieldDeclarationSyntax.Declaration.Variables) { + // get the symbol to retrieve the data + if (semanticModel.GetDeclaredSymbol (variableSyntax) is not IFieldSymbol symbol) + continue; + var flagName = $"Has{symbol.Name}"; + var attributeFullName = symbol.ToDisplayString ().Trim (); + var attrData = GetAttributeData (symbol); + if (attrData is not null) { + dataAttributes [flagName] = (attributeFullName, symbol.Name, attrData.Value); + } + } + } + + static void GetFlagsFromField (FieldDeclarationSyntax fieldDeclarationSyntax, SemanticModel semanticModel, + Dictionary flags) + { + foreach (var variableSyntax in fieldDeclarationSyntax.Declaration.Variables) { + // get the symbol to retrieve the data + if (semanticModel.GetDeclaredSymbol (variableSyntax) is not IFieldSymbol symbol) + continue; + var flagName = $"Has{symbol.Name.Replace ("Attribute", "Flag")}"; + var attrName = symbol.ToDisplayString ().Trim (); + var target = GetTarget (symbol); + flags [flagName] = (attrName, target); + } + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/AsyncData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/AsyncData.cs new file mode 100644 index 000000000000..3630e6924c9a --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/AsyncData.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct AsyncData { + /// + /// Diff the constructor used in the bindings. + /// + internal enum ConstructorType { + ResultType, + MethodName + } + + public string? ResultType { get; init; } // this in the attr is a type, but we do not care for the transformation + public string? MethodName { get; init; } + public string? ResultTypeName { get; init; } + public string? PostNonResultSnippet { get; init; } + + public AsyncData () { } + + public AsyncData (string resultType, ConstructorType constructorType) + { + if (constructorType == ConstructorType.ResultType) + ResultType = resultType; + else + MethodName = resultType; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out AsyncData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + ConstructorType constructorType = ConstructorType.MethodName; + string? resultType = null; + string? resultTypeName = null; + string? methodName = null; + string? postNonResultSnippet = null; + + switch (count) { + case 0: + break; + case 1: + // we have to diff constructors that take a single parameter, either a string or a type + if (attributeData.ConstructorArguments [0].Value! is string methodNameValue) { + constructorType = ConstructorType.MethodName; + methodName = methodNameValue; + } else { + constructorType = ConstructorType.ResultType; + resultType = ((ITypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + } + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + if (constructorType == ConstructorType.ResultType) + data = new (resultType!, ConstructorType.ResultType); + else + data = new (methodName!, ConstructorType.MethodName); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "ResultType": + resultType = ((ITypeSymbol) value.Value!).ToDisplayString (); + break; + case "MethodName": + methodName = (string) value.Value!; + break; + case "ResultTypeName": + resultTypeName = (string) value.Value!; + break; + case "PostNonResultSnippet": + postNonResultSnippet = (string) value.Value!; + break; + default: + data = null; + return false; + } + } + + if (count == 0) { + // use the default constructor and use the init properties + data = new () { + ResultType = resultType, + MethodName = methodName, + ResultTypeName = resultTypeName, + PostNonResultSnippet = postNonResultSnippet + }; + return true; + } + + switch (constructorType) { + case ConstructorType.MethodName: + data = new (methodName!, ConstructorType.MethodName) { + ResultType = resultType, + ResultTypeName = resultTypeName, + PostNonResultSnippet = postNonResultSnippet + }; + break; + case ConstructorType.ResultType: + data = new (resultType!, ConstructorType.ResultType) { + MethodName = methodName, + ResultTypeName = resultTypeName, + PostNonResultSnippet = postNonResultSnippet + }; + break; + } + + return false; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/BackingFieldTypeData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/BackingFieldTypeData.cs new file mode 100644 index 000000000000..fbd4cda7eb81 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/BackingFieldTypeData.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct BackingFieldTypeData { + + public string TypeName { get; } + + public BackingFieldTypeData (string typeName) + { + TypeName = typeName; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out BackingFieldTypeData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string backingField; + // custom marshal directive values + + switch (count) { + case 1: + backingField = ((ITypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (backingField); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "BackingFieldType": + backingField = ((ITypeSymbol) value.Value!).ToDisplayString (); + break; + default: + data = null; + return false; + } + } + + data = new (backingField); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/BaseTypeData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/BaseTypeData.cs new file mode 100644 index 000000000000..61269d3624b6 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/BaseTypeData.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct BaseTypeData { + + public string BaseType { get; } // is a type in the attribute, but we do not care for the transformation + public string? Name { get; init; } = null; + public string [] Events { get; init; } = []; // it is a collection of types, but we do not care for the transformation + public string [] Delegates { get; init; } = []; + public bool Singleton { get; init; } + + public string? KeepRefUntil { get; init; } = null; + + public bool IsStubClass { get; init; } + + public BaseTypeData (string baseType) + { + BaseType = baseType; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out BaseTypeData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string baseType; + string? name = null; + string [] events = []; + string [] delegates = []; + var singleton = false; + string? keepRefUntil = null; + var isStubClass = false; + + // custom marshal directive values + + switch (count) { + case 1: + baseType = ((ITypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (baseType); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "Name": + name = (string?) value.Value!; + break; + case "Events": + events = value.Values.Select ( + v => ((ITypeSymbol) v.Value!).ToDisplayString ()) + .ToArray (); + break; + case "Delegates": + delegates = value.Values.Select (v => (string) v.Value!).ToArray (); + break; + case "Singleton": + singleton = (bool) value.Value!; + break; + case "KeepRefUntil": + keepRefUntil = (string?) value.Value!; + break; + case "IsStubClass": + isStubClass = (bool) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (baseType) { + Name = name, + Events = events, + Delegates = delegates, + Singleton = singleton, + KeepRefUntil = keepRefUntil, + IsStubClass = isStubClass, + }; + return true; + } + + public bool Equals (BaseTypeData other) + { + var stringCollectionComparer = new CollectionComparer (StringComparer.Ordinal); + + if (BaseType != other.BaseType) + return false; + if (Name != other.Name) + return false; + if (!stringCollectionComparer.Equals (Events, other.Events)) + return false; + if (!stringCollectionComparer.Equals (Delegates, other.Delegates)) + return false; + if (Singleton != other.Singleton) + return false; + if (KeepRefUntil != other.KeepRefUntil) + return false; + return IsStubClass == other.IsStubClass; + } + + /// + public override int GetHashCode () + { + var hash = new HashCode (); + hash.Add (BaseType); + hash.Add (Name); + foreach (var e in Events) { + hash.Add (e); + } + foreach (var d in Delegates) { + hash.Add (d); + } + hash.Add (Singleton); + hash.Add (KeepRefUntil); + return hash.ToHashCode (); + } + + public override string ToString () + { + var sb = new StringBuilder ($"BaseTypeData {{ BaseType: {BaseType}, Name: {Name ?? "null"}, "); + sb.Append ("Events: ["); + sb.AppendJoin (", ", Events); + sb.Append ("], Delegates: ["); + sb.AppendJoin (", ", Delegates); + sb.Append ($"], Singleton: {Singleton}, KeepRefUntil: {KeepRefUntil ?? "null"}, IsStubClass: {IsStubClass} }}"); + return sb.ToString (); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/BindAsData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/BindAsData.cs new file mode 100644 index 000000000000..f986f84267b5 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/BindAsData.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct BindAsData { + + public string Type { get; init; } + public string? OriginalType { get; init; } + + public BindAsData (string type) + { + Type = type; + } + + public BindAsData (string type, string? originalType) + { + Type = type; + OriginalType = originalType; + + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out BindAsData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string type; + string? originalType = null; + + switch (count) { + case 1: + type = ((ITypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (type); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "Type": + type = ((ITypeSymbol) value.Value!).ToDisplayString (); + break; + case "OriginalType": + originalType = ((ITypeSymbol) value.Value!).ToDisplayString (); + break; + default: + data = null; + return false; + } + } + + data = new (type, originalType); + return true; + } + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/BindData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/BindData.cs new file mode 100644 index 000000000000..435d80715c2b --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/BindData.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct BindData { + + public string Selector { get; } + public bool Virtual { get; init; } + + public BindData (string selector, bool isVirtual = false) + { + Selector = selector; + Virtual = isVirtual; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out BindData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string selector; + bool @virtual = false; + + switch (count) { + case 1: + selector = (string) attributeData.ConstructorArguments [0].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (selector); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "Selector": + selector = (string) value.Value!; + break; + case "Virtual": + @virtual = (bool) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (selector) { Virtual = @virtual, }; + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterData.cs new file mode 100644 index 000000000000..7bb609fc001a --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterData.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using MethodAttributes = Mono.Cecil.MethodAttributes; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct CoreImageFilterData { + + public MethodAttributes DefaultCtorVisibility { get; init; } + + public MethodAttributes IntPtrCtorVisibility { get; init; } + + public MethodAttributes StringCtorVisibility { get; init; } + + public CoreImageFilterData () + { + + DefaultCtorVisibility = MethodAttributes.Public; + IntPtrCtorVisibility = MethodAttributes.Private; + StringCtorVisibility = MethodAttributes.Private; + } + + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out CoreImageFilterData? data) + { + var defaultVisibility = MethodAttributes.Public; + var intPtrVisibility = MethodAttributes.Private; + var stringVisibility = MethodAttributes.Private; + + // there is not positional constructor for this attribute + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "DefaultCtorVisibility": + defaultVisibility = (MethodAttributes) Convert.ToSingle ((int) value.Value!); + break; + case "IntPtrCtorVisibility": + intPtrVisibility = (MethodAttributes) Convert.ToSingle ((int) value.Value!); + break; + case "StringCtorVisibility": + stringVisibility = (MethodAttributes) Convert.ToSingle ((int) value.Value!); + break; + default: + data = null; + return false; + } + } + + data = new () { + DefaultCtorVisibility = defaultVisibility, + IntPtrCtorVisibility = intPtrVisibility, + StringCtorVisibility = stringVisibility, + }; + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterPropertyData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterPropertyData.cs new file mode 100644 index 000000000000..f428b55753a2 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/CoreImageFilterPropertyData.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct CoreImageFilterPropertyData { + + public string Name { get; } + + public CoreImageFilterPropertyData (string name) + { + Name = name; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out CoreImageFilterPropertyData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string name; + + switch (count) { + case 1: + name = (string) attributeData.ConstructorArguments [0].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (name); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "Name": + name = (string) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (name); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/ErrorDomainData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/ErrorDomainData.cs new file mode 100644 index 000000000000..59149c8dfc5c --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/ErrorDomainData.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct ErrorDomainData { + + public string ErrorDomain { get; } + public string? LibraryName { get; } + + + public ErrorDomainData (string domain) + { + ErrorDomain = domain; + } + + public ErrorDomainData (string domain, string? libraryName) + { + ErrorDomain = domain; + LibraryName = libraryName; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out ErrorDomainData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string errorDomain; + string? libraryName = null; + + switch (count) { + case 1: + errorDomain = (string) attributeData.ConstructorArguments [0].Value!; + break; + case 2: + errorDomain = (string) attributeData.ConstructorArguments [0].Value!; + libraryName = (string) attributeData.ConstructorArguments [1].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (errorDomain, libraryName); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "ErrorDomain": + errorDomain = (string) value.Value!; + break; + case "LibraryName": + libraryName = (string) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (errorDomain, libraryName); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/ExportData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/ExportData.cs new file mode 100644 index 000000000000..0107dd9ff5a1 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/ExportData.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using ObjCRuntime; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct ExportData { + + /// + /// The exported native selector. + /// + public string? Selector { get; } + + /// + /// Argument semantics to use with the selector. + /// + public ArgumentSemantic ArgumentSemantic { get; } = ArgumentSemantic.None; + + public ExportData (string? selector) + { + Selector = selector; + } + + public ExportData (string? selector, ArgumentSemantic argumentSemantic) + { + Selector = selector; + ArgumentSemantic = argumentSemantic; + } + + /// + /// Try to parse the attribute data to retrieve the information of an ExportAttribute. + /// + /// The attribute data to be parsed. + /// The parsed data. Null if we could not parse the attribute data. + /// True if the data was parsed. + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out ExportData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string? selector; + ArgumentSemantic argumentSemantic = ArgumentSemantic.None; + + // custom marshal directive values + + switch (count) { + case 1: + selector = (string?) attributeData.ConstructorArguments [0].Value!; + break; + case 2: + selector = (string?) attributeData.ConstructorArguments [0].Value!; + argumentSemantic = (ArgumentSemantic) attributeData.ConstructorArguments [1].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (selector, argumentSemantic); + return true; + } + + foreach (var (name, value) in attributeData.NamedArguments) { + switch (name) { + case "Selector": + selector = (string?) value.Value!; + break; + case "ArgumentSemantic": + argumentSemantic = (ArgumentSemantic) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (selector, argumentSemantic); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/FieldData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/FieldData.cs new file mode 100644 index 000000000000..9a5774aa79a1 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/FieldData.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct FieldData { + + public string SymbolName { get; } + public string? LibraryName { get; } + + internal FieldData (string symbolName, string? libraryName) + { + SymbolName = symbolName; + LibraryName = libraryName; + } + + internal FieldData (string symbolName) : this (symbolName, null) { } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out FieldData? data) + { + data = null; + + var count = attributeData.ConstructorArguments.Length; + string? symbolName; + string? libraryName = null; + switch (count) { + case 1: + symbolName = (string?) attributeData.ConstructorArguments [0].Value!; + break; + case 2: + symbolName = (string?) attributeData.ConstructorArguments [0].Value!; + libraryName = (string?) attributeData.ConstructorArguments [1].Value!; + break; + default: + // 0 should not be an option. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (symbolName, libraryName); + return true; + } + + // LibraryName can be a param value + foreach (var (name, value) in attributeData.NamedArguments) { + switch (name) { + case "LibraryName": + libraryName = (string?) value.Value!; + break; + default: + data = null; + return false; + } + } + data = new (symbolName, libraryName); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/NativeData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/NativeData.cs new file mode 100644 index 000000000000..869821afb983 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/NativeData.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct NativeData { + + public string? NativeName { get; } + + public NativeData () { } + + public NativeData (string? nativeName) + { + NativeName = nativeName; + } + + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out NativeData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string? nativeName; + + switch (count) { + case 0: + nativeName = null; + break; + case 1: + nativeName = (string) attributeData.ConstructorArguments [0].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (nativeName); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "NativeName": + nativeName = (string) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (nativeName); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/NotificationData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/NotificationData.cs new file mode 100644 index 000000000000..51ccef7fb59d --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/NotificationData.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct NotificationData { + + /// + /// Diff the constructor used in the bindings. + /// + internal enum ConstructorType { + NotificationType, + NotificationCenter, + All + } + + public string? Type { get; init; } + public string? NotificationCenter { get; init; } + + public NotificationData (string? data, ConstructorType constructorType) + { + if (constructorType == ConstructorType.NotificationType) { + Type = data; + } else { + NotificationCenter = data; + } + } + + public NotificationData (string? type, string? notificationCenter) + { + Type = type; + NotificationCenter = notificationCenter; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out NotificationData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + ConstructorType constructorType = ConstructorType.NotificationType; + string? notificationType = null; + string? notificationCenter = null; + + switch (count) { + case 0: + break; + case 1: + // we have to diff constructors that take a single parameter, either a string or a type + if (attributeData.ConstructorArguments [0].Value! is string notificationCenterValue) { + constructorType = ConstructorType.NotificationCenter; + notificationCenter = notificationCenterValue; + } else { + constructorType = ConstructorType.NotificationType; + notificationType = ((INamedTypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + } + break; + case 2: + constructorType = ConstructorType.All; + notificationType = ((INamedTypeSymbol) attributeData.ConstructorArguments [0].Value!).ToDisplayString (); + notificationCenter = (string?) attributeData.ConstructorArguments [1].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = constructorType switch { + ConstructorType.NotificationCenter => new (notificationCenter, ConstructorType.NotificationCenter), + ConstructorType.NotificationType => new (notificationType, ConstructorType.NotificationType), + _ => new (notificationType, notificationCenter) + }; + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "Type": + notificationType = ((INamedTypeSymbol) value.Value!).ToDisplayString (); + break; + case "NotificationCenter": + notificationCenter = (string) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (notificationType, notificationCenter); + return true; + } + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/SnippetData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/SnippetData.cs new file mode 100644 index 000000000000..3a1a0b5e2450 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/SnippetData.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct SnippetData { + + public string Code { get; } + + public bool Optimizable { get; } + + public SnippetData (string code) + { + Code = code; + } + + public SnippetData (string code, bool optimizable) + { + Code = code; + Optimizable = optimizable; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out SnippetData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string code; + var optimizable = false; + + // custom marshal directive values + + switch (count) { + case 1: + code = (string) attributeData.ConstructorArguments [0].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (code); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "Code": + code = (string?) value.Value!; + break; + case "Optimizable": + optimizable = (bool) value.Value!; + break; + default: + data = null; + return false; + } + } + + data = new (code, optimizable); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/StrongDictionaryData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/StrongDictionaryData.cs new file mode 100644 index 000000000000..bf7d4ea4c396 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/StrongDictionaryData.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct StrongDictionaryData { + + public string TypeWithKeys { get; } + public string? Suffix { get; } + + public StrongDictionaryData (string typeWithKeys) + { + TypeWithKeys = typeWithKeys; + } + + public StrongDictionaryData (string typeWithKeys, string? suffix) + { + TypeWithKeys = typeWithKeys; + Suffix = suffix; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out StrongDictionaryData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + string typeWithKeys; + string? suffix = null; + + // custom marshal directive values + + switch (count) { + case 1: + typeWithKeys = (string) attributeData.ConstructorArguments [0].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + if (attributeData.NamedArguments.Length == 0) { + data = new (typeWithKeys); + return true; + } + + foreach (var (argumentName, value) in attributeData.NamedArguments) { + switch (argumentName) { + case "TypeWithKeys": + typeWithKeys = (string?) value.Value!; + break; + case "Suffix": + suffix = (string?) value.Value!; + break; + } + } + + data = new (typeWithKeys, suffix); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/ThreadSafeData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/ThreadSafeData.cs new file mode 100644 index 000000000000..9c57e6f149ae --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/ThreadSafeData.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Attributes; + +readonly record struct ThreadSafeData { + + public bool Safe { get; } = true; + + public ThreadSafeData () : this (true) { } + + public ThreadSafeData (bool safe) + { + Safe = safe; + } + + public static bool TryParse (AttributeData attributeData, + [NotNullWhen (true)] out ThreadSafeData? data) + { + data = null; + var count = attributeData.ConstructorArguments.Length; + if (count == 0) { + data = new (); + return true; + } + bool safe = true; + switch (count) { + case 1: + safe = (bool) attributeData.ConstructorArguments [0].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + data = new ThreadSafeData (safe); + return true; + } + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Attributes/XamarinAvailabilityData.cs b/src/rgen/Microsoft.Macios.Transformer/Attributes/XamarinAvailabilityData.cs new file mode 100644 index 000000000000..c9336a522575 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Attributes/XamarinAvailabilityData.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Attributes; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Attributes; + +static class XamarinAvailabilityData { + + static readonly IReadOnlyDictionary supportedAttributes = new Dictionary { + { AttributesNames.iOSAttribute, ApplePlatform.iOS }, + { AttributesNames.TVAttribute, ApplePlatform.TVOS }, + { AttributesNames.MacAttribute, ApplePlatform.MacOSX }, + { AttributesNames.MacCatalystAttribute, ApplePlatform.MacCatalyst }, + }; + + static readonly IReadOnlyDictionary unsupportedAttributes = new Dictionary { + { AttributesNames.NoiOSAttribute, ApplePlatform.iOS }, + { AttributesNames.NoTVAttribute, ApplePlatform.TVOS }, + { AttributesNames.NoMacAttribute, ApplePlatform.MacOSX }, + { AttributesNames.NoMacCatalystAttribute, ApplePlatform.MacCatalyst }, + }; + + public static bool TryParseSupportedOSData (string attributeName, AttributeData attributeData, + [NotNullWhen (true)] out SupportedOSPlatformData? data) + { + data = null; + if (!supportedAttributes.TryGetValue (attributeName, out var platform)) { + // not a supported attribute + return false; + } + + var count = attributeData.ConstructorArguments.Length; + int major = 0; + int? minor = null; + int? subminor = null; + + // custom marshal directive values + + switch (count) { + case 1: + major = (byte) attributeData.ConstructorArguments [0].Value!; + break; + case 2: + major = (byte) attributeData.ConstructorArguments [0].Value!; + minor = (byte) attributeData.ConstructorArguments [1].Value!; + break; + case 3: + major = (byte) attributeData.ConstructorArguments [0].Value!; + minor = (byte) attributeData.ConstructorArguments [1].Value!; + subminor = (byte) attributeData.ConstructorArguments [2].Value!; + break; + default: + // 0 should not be an option.. + return false; + } + + data = (major, minor, subminor) switch { + (_, null, null) => new (platform, new ($"{major}")), + (_, not null, null) => new (platform, new (major, minor.Value)), + (_, not null, not null) => new (platform, new (major, minor.Value, subminor.Value)), + _ => throw new ArgumentOutOfRangeException ("Could not parse the version") + }; + return true; + } + + public static bool TryParseUnsupportedOSData (string attributeName, AttributeData attributeData, + [NotNullWhen (true)] out UnsupportedOSPlatformData? data) + { + data = null; + if (!unsupportedAttributes.TryGetValue (attributeName, out var platform)) { + // not a supported attribute + return false; + } + + data = new UnsupportedOSPlatformData (platform); + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs b/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs new file mode 100644 index 000000000000..9d69de6b7fa0 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#pragma warning disable format +using Microsoft.Macios.Transformer.Attributes; +using Microsoft.Macios.Transformer.Generator; + +namespace Microsoft.Macios.Transformer; + +static class AttributesNames { + + /// + /// The [Abstract] attribute can be applied to either methods or properties and causes the generator to flag the + /// generated member as abstract and the class to be an abstract class. + /// + [BindingFlag (AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Interface)] + public const string AbstractAttribute = "AbstractAttribute"; + + [BindingFlag] + public const string AdvancedAttribute = "AdvancedAttribute"; + public const string AdviceAttribute = "Foundation.AdviceAttribute"; + + /// + /// The [Appearance] attribute can be applied to any method or property that participate in the + /// UIAppearance framework + /// + [BindingFlag (AttributeTargets.Property | AttributeTargets.Method)] + public const string AppearanceAttribute = "AppearanceAttribute"; + + /// + /// Use the [AutoReleaseAttribute] on methods and properties to wrap the method + /// invocation to the method in an NSAutoReleasePool. + /// + [BindingFlag (AttributeTargets.Method | AttributeTargets.Property)] + public const string AutoreleaseAttribute = "AutoreleaseAttribute"; + + [BindingAttribute(typeof(AsyncData), AttributeTargets.Method)] + public const string AsyncAttribute = "AsyncAttribute"; + + [BindingAttribute(typeof(BackingFieldTypeData), AttributeTargets.Enum)] + public const string BackingFieldTypeAttribute = "BackingFieldTypeAttribute"; + public const string BaseTypeAttribute = "BaseTypeAttribute"; + [BindingAttribute(typeof(BindData), AttributeTargets.Method )] + public const string BindAttribute = "BindAttribute"; + + [BindingAttribute(typeof(BindAsData), AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter)] + public const string BindAsAttribute = "ObjCRuntime.BindAsAttribute"; + + /// + /// Use this attribute on a type definition to bind Objective-C categories and to expose those as C# extension + /// methods to mirror the way Objective-C exposes the functionality. + /// + [BindingFlag (AttributeTargets.Interface)] + public const string CategoryAttribute = "CategoryAttribute"; + + [BindingFlag] + public const string CheckDisposedAttribute = "CheckDisposedAttribute"; + + [BindingAttribute(typeof(CoreImageFilterData), AttributeTargets.Interface)] + public const string CoreImageFilterAttribute = "CoreImageFilterAttribute"; + + [BindingAttribute(typeof(CoreImageFilterPropertyData), AttributeTargets.Property)] + public const string CoreImageFilterPropertyAttribute = "CoreImageFilterPropertyAttribute"; + + [BindingFlag (AttributeTargets.Interface)] + public const string DefaultCtorVisibilityAttribute = "DefaultCtorVisibilityAttribute"; + + [BindingFlag (AttributeTargets.Field)] + public const string DefaultEnumValueAttribute = "DefaultEnumValueAttribute"; + public const string DeprecatedAttribute = "DeprecatedAttribute"; + + [BindingFlag (AttributeTargets.Interface)] + public const string DesignatedDefaultCtorAttribute = "DesignatedDefaultCtorAttribute"; + + [BindingFlag (AttributeTargets.Constructor | AttributeTargets.Method)] + public const string DesignatedInitializerAttribute = "DesignatedInitializerAttribute"; + + /// + /// When this attribute is applied to the interface definition it will prevent the generator from producing + /// the default constructor. + /// + [BindingFlag (AttributeTargets.Interface)] + public const string DisableDefaultCtorAttribute = "DisableDefaultCtorAttribute"; + + /// + /// This attribute is applied to string parameters or string properties and instructs the code generator to not + /// use the zero-copy string marshaling for this parameter, and instead create a new NSString instance from the C# string + /// + [BindingFlag (AttributeTargets.Parameter | AttributeTargets.Property)] + public const string DisableZeroCopyAttribute = "DisableZeroCopyAttribute"; + + /// + /// Code to run from a generated Dispose method, before any generated code is executed + /// Adding this attribute will, by default, make the method non-optimizable by the SDK tools + /// + [BindingAttribute(typeof(ErrorDomainData), AttributeTargets.Interface | AttributeTargets.Class)] + public const string DisposeAttribute = "DisposeAttribute"; + + public const string EditorBrowsableAttribute = "System.ComponentModel.EditorBrowsableAttribute"; + + [BindingAttribute(typeof(ErrorDomainData), AttributeTargets.Enum)] + public const string ErrorDomainAttribute = "ErrorDomainAttribute"; + + public const string ExperimentalAttribute = "System.Diagnostics.CodeAnalysis.ExperimentalAttribute"; + + [BindingAttribute(typeof(ExportData), AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] + public const string ExportAttribute = "Foundation.ExportAttribute"; + + [BindingFlag] + public const string FactoryAttribute = "FactoryAttribute"; + + [BindingAttribute(typeof(FieldData), AttributeTargets.Field | AttributeTargets.Property)] + public const string FieldAttribute = "Foundation.FieldAttribute"; + + [BindingFlag (AttributeTargets.Enum)] + public const string FlagsAttribute = "System.FlagsAttribute"; + + /// + /// Sometimes it makes sense not to expose an event or delegate property from a Model class into the host class so + /// adding this attribute will instruct the generator to avoid the generation of any method decorated with it. + /// + [BindingFlag (AttributeTargets.Method | AttributeTargets.Property)] + public const string IgnoredInDelegateAttribute = "IgnoredInDelegateAttribute"; + + /// + /// The [Internal] attribute can be applied to methods or properties and it has the effect of flagging the + /// generated code with the internal C# keyword making the code only accessible to code in the generated assembly. + /// + [BindingFlag (AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] + public const string InternalAttribute = "InternalAttribute"; + + public const string IntroducedAttribute = "IntroducedAttribute"; + + /// + /// This attribute flags the backing field for a property to be annotated with the .NET [ThreadStatic] attribute. + /// This is useful if the field is a thread static variable. + /// + [BindingFlag (AttributeTargets.Property)] + public const string IsThreadStaticAttribute = "IsThreadStaticAttribute"; + + public const string MacAttribute = "ObjCRuntime.MacAttribute"; + public const string MacCatalystAttribute = "MacCatalystAttribute"; + + /// + /// Use this attribute if some definitions are required at definition-compile + /// time but when you need the final binding assembly to include your own + /// custom implementation + /// + [BindingFlag (AttributeTargets.Method | AttributeTargets.Property)] + public const string ManualAttribute = "ManualAttribute"; + + [BindingFlag] + public const string MarshalNativeExceptionsAttribute = "MarshalNativeExceptionsAttribute"; + + /// + /// Mark a class or interface to be a model. + /// + [BindingFlag (AttributeTargets.Class | AttributeTargets.Interface)] + public const string ModelAttribute = "Foundation.ModelAttribute"; + [BindingAttribute(typeof(NativeData), AttributeTargets.Enum)] + public const string NativeAttribute = "ObjCRuntime.NativeAttribute"; + [BindingAttribute(typeof(NativeData), AttributeTargets.Enum | AttributeTargets.Struct)] + public const string NativeNameAttribute = "ObjCRuntime.NativeNameAttribute"; + + /// + /// This attribute is applied to methods and properties to have the generator generate the new keyword in front + /// of the declaration. + /// + [BindingFlag (AttributeTargets.Method | AttributeTargets.Property)] + public const string NewAttribute = "NewAttribute"; + + /// + /// Specifies that the method on the model does not provide a default return value. + /// + [BindingFlag (AttributeTargets.Method)] + public const string NoDefaultValueAttribute = "NoDefaultValueAttribute"; + + public const string NoMacAttribute = "NoMacAttribute"; + public const string NoMacCatalystAttribute = "NoMacCatalystAttribute"; + + /// + /// This prevents the generator from generating the managed proxy to + /// the method being called, this is done when we are interested in + /// the side effects of the binding of the method, rather than the + /// method itself + /// + [BindingFlag (AttributeTargets.Method)] + public const string NoMethodAttribute = "NoMethodAttribute"; + + /// + /// When applied, flags the [Flags] as a notification and generates the + /// code to strongly type the notification. + /// + [BindingAttribute(typeof(NotificationData), AttributeTargets.Property)] + public const string NotificationAttribute = "NotificationAttribute"; + + public const string NoTVAttribute = "NoTVAttribute"; + public const string NoiOSAttribute = "NoiOSAttribute"; + + /// + /// When this is applied to a property it flags the property as allowing the value null to be assigned to it. + /// This is only valid for reference types. + /// When this is applied to a parameter in a method signature it indicates that the specified parameter can + /// be null and that no check should be performed for passing null values. + /// + [BindingFlag (AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] + public const string NullAllowedAttribute = "NullAllowedAttribute"; + + public const string ObsoleteAttribute = "System.ObsoleteAttribute"; + public const string ObsoletedAttribute = "ObsoletedAttribute"; + + /// + /// When this attribtue is applied to a property, currently it merely adds + /// a DebuggerBrowsable(Never) to the property, to prevent a family of crashes + /// + [BindingFlag (AttributeTargets.Property)] + public const string OptionalImplementationAttribute = "OptionalImplementationAttribute"; + + /// + /// Use this attribute to instruct the binding generator that the binding for this particular method should be + /// flagged with an override keyword. + /// + [BindingFlag (AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)] + public const string OverrideAttribute = "OverrideAttribute"; + + /// + /// Indicates that this array should be turned into a params + /// + [BindingFlag (AttributeTargets.Parameter)] + public const string ParamsAttribute = "ParamsAttribute"; + + /// + /// When applied to a type generate a partial class even if the type does not subclass NSObject + /// useful for Core* types that declare Fields + /// + [BindingFlag (AttributeTargets.Interface)] + public const string PartialAttribute = "PartialAttribute"; + + [BindingFlag] + public const string PlainStringAttribute = "PlainStringAttribute"; + + /// + /// PostSnippet code is inserted before returning, before paramters are disposed/released + /// Adding this attribute will, by default, make the method non-optimizable by the SDK tools + /// + [BindingAttribute (typeof(SnippetData), AttributeTargets.Method | AttributeTargets.Property)] + public const string PostSnippetAttribute = "PostSnippetAttribute"; + + /// + /// PreSnippet code is inserted after the parameters have been validated/marshalled + /// Adding this attribute will, by default, make the method non-optimizable by the SDK tools + /// + [BindingAttribute (typeof(SnippetData), AttributeTargets.Method | AttributeTargets.Property)] + public const string PreSnippetAttribute = "PreSnippetAttribute"; + + /// + /// When this attribute is applied to the interface definition it will flag the default constructor as private. + /// + [BindingFlag (AttributeTargets.Interface)] + public const string PrivateDefaultCtorAttribute = "PrivateDefaultCtorAttribute"; + + [BindingFlag (AttributeTargets.Property)] + public const string ProbePresenceAttribute = "ProbePresenceAttribute"; + + /// + /// PrologueSnippet code is inserted before any code is generated + /// Adding this attribute will, by default, make the method non-optimizable by the SDK tools + /// + [BindingAttribute (typeof(SnippetData), AttributeTargets.Method | AttributeTargets.Property)] + public const string PrologueSnippetAttribute = "PrologueSnippetAttribute"; + + /// + /// Use this attribute to instruct the binding generator that the binding for this particular method should be + /// flagged with an protected keyword. + /// + [BindingFlag (AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)] + public const string ProtectedAttribute = "ProtectedAttribute"; + + [BindingFlag (AttributeTargets.Interface | AttributeTargets.Class)] + public const string ProtocolAttribute = "Foundation.ProtocolAttribute"; + + /// + /// This attribute is applied to return values to flag them as being proxy objects + /// + [BindingFlag (AttributeTargets.ReturnValue)] + public const string ProxyAttribute = "ProxyAttribute"; + + /// + /// Use the [AutoReleaseAttribute] on methods and properties to wrap the method invocation to the method + /// in an NSAutoReleasePool + /// + [BindingFlag (AttributeTargets.ReturnValue)] + public const string ReleaseAttribute = "ReleaseAttribute"; + + /// + /// Instructs the generator to flag the generated method as sealed + /// + [BindingFlag (AttributeTargets.Method | AttributeTargets.Property)] + public const string SealedAttribute = "SealedAttribute"; + + /// + /// When this attribute is applied to a class it will just generate a static class, one that does not derive + /// from NSObject. + /// + [BindingFlag (AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property)] + public const string StaticAttribute = "StaticAttribute"; + + /// + /// When this attribute is applied to an interface, it directs the generator to + /// create a strongly typed DictionaryContainer for the specified fields. + /// + [BindingAttribute(typeof(StrongDictionaryData), AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Property)] + public const string StrongDictionaryAttribute = "StrongDictionaryAttribute"; + + /// + /// Used to mark if a type is not a wrapper type. + /// + [BindingFlag (AttributeTargets.Class | AttributeTargets.Interface)] + public const string SyntheticAttribute = "SyntheticAttribute"; + public const string TVAttribute = "TVAttribute"; + + /// + /// hen applied, instructs the generator to use this object as the + /// target, instead of the implicit Handle + /// + [BindingFlag (AttributeTargets.Class | AttributeTargets.Interface)] + public const string TargetAttribute = "TargetAttribute"; + + /// + /// Flags the object as being thread safe. + /// + [BindingAttribute(typeof(BackingFieldTypeData), AttributeTargets.All)] + public const string ThreadSafeAttribute = "ThreadSafeAttribute"; + + /// + /// If this attribute is applied to a property, we do not generate a + /// backing field. + /// + [BindingFlag (AttributeTargets.Property)] + public const string TransientAttribute = "TransientAttribute"; + public const string UnavailableAttribute = "UnavailableAttribute"; + + [BindingFlag (AttributeTargets.Assembly | AttributeTargets.Method | AttributeTargets.Interface)] + public const string ZeroCopyStringsAttribute = "ZeroCopyStringsAttribute"; + public const string iOSAttribute = "ObjCRuntime.iOSAttribute"; +} diff --git a/src/rgen/Microsoft.Macios.Transformer/CompilationResult.cs b/src/rgen/Microsoft.Macios.Transformer/CompilationResult.cs new file mode 100644 index 000000000000..379906bf36b7 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/CompilationResult.cs @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer; + +/// +/// Holds the result of a compilation. This is a helper record to make code cleaner in the transformer. +/// +/// The platform the compilation targeted. +/// The compilation result. +/// All compilation errors. +record CompilationResult (ApplePlatform Platform, Compilation Compilation, ImmutableArray Errors) { + + public (ApplePlatform Platform, Compilation compilation) ToTuple () + => (Platform, Compilation); +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Accessor.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Accessor.Transformer.cs new file mode 100644 index 000000000000..2d1ce21acc9c --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Accessor.Transformer.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Transformer.Attributes; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Accessor { + + readonly ExportData? overrideExportData; + + /// + /// The data of the field attribute used to mark the value as a property binding. + /// + public ExportData? ExportPropertyData { + get => overrideExportData ?? ExportAttribute; + init => overrideExportData = value; + } + + /// + /// State if we should marshal native exceptions when generating the accessor. + /// + public bool MarshalNativeExceptions => HasMarshalNativeExceptionsFlag; + + public Accessor (AccessorKind accessorKind, + SymbolAvailability symbolAvailability, + Dictionary> attributes) + { + Kind = accessorKind; + SymbolAvailability = symbolAvailability; + AttributesDictionary = attributes; + + // we trust the modifiers of the property itself + Modifiers = []; + } + + /// + public override string ToString () + { + var sb = new StringBuilder ($"{{ Kind: {Kind}, "); + sb.Append ($"Supported Platforms: {SymbolAvailability}, "); + sb.Append ($"ExportData: {ExportPropertyData?.ToString () ?? "null"} Modifiers: ["); + sb.AppendJoin (",", Modifiers.Select (x => x.Text)); + sb.Append ("] }"); + return sb.ToString (); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs new file mode 100644 index 000000000000..e25a468c5528 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.DataModel; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Binding { + + /// + /// Represents the type of binding that the code changes are for. + /// + public BindingType BindingType => BindingInfo.BindingType; + + /// + /// Returhs the binding data of the binding for the given code changes. + /// + public BindingInfo BindingInfo { get; init; } + + /// + /// Internal constructor added for testing purposes. + /// + /// The name of the named type that created the code change. + /// The namespace that contains the named type. + /// The fully qualified name of the symbol. + /// the binding info struct. + /// The platform availability of the named symbol. + /// The dictioanary with the attributes the user used with the binding. + internal Binding (string symbolName, + ImmutableArray @namespace, + string fullyQualifiedSymbol, + BindingInfo info, + SymbolAvailability symbolAvailability, + Dictionary> attributes) + { + name = symbolName; + namespaces = @namespace; + availability = symbolAvailability; + AttributesDictionary = attributes; + BindingInfo = info; + FullyQualifiedSymbol = fullyQualifiedSymbol; + } + + internal Binding (EnumDeclarationSyntax enumDeclaration, ISymbol symbol, RootContext context) + { + SemanticModelExtensions.GetSymbolData ( + symbol: symbol, + name: out name, + baseClass: out baseClass, + interfaces: out interfaces, + namespaces: out namespaces, + symbolAvailability: out availability); + BindingInfo = new BindingInfo (null, BindingType.SmartEnum); + FullyQualifiedSymbol = enumDeclaration.GetFullyQualifiedIdentifier (); + UsingDirectives = enumDeclaration.SyntaxTree.CollectUsingStatements (); + // smart enums are expected to be public, we might need to change this in the future + Modifiers = [Token (SyntaxKind.PublicKeyword)]; + var bucket = ImmutableArray.CreateBuilder (); + var enumValueDeclarations = enumDeclaration.Members.OfType (); + foreach (var enumValueDeclaration in enumValueDeclarations) { + if (context.SemanticModel.GetDeclaredSymbol (enumValueDeclaration) is not IFieldSymbol enumValueSymbol) { + continue; + } + var fieldData = enumValueSymbol.GetFieldData (); + // try and compute the library for this enum member + if (fieldData is null || !context.TryComputeLibraryName (fieldData.Value.LibraryName, Namespace [^1], + out string? libraryName, out string? libraryPath)) + // could not calculate the library for the enum, do not add it + continue; + var enumMember = new EnumMember ( + name: enumValueDeclaration.Identifier.ToFullString ().Trim (), + libraryName: libraryName, + libraryPath: libraryPath, + fieldData: enumValueSymbol.GetFieldData (), + symbolAvailability: enumValueSymbol.GetAvailabilityForSymbol () // no parent availability, just the symbol + ); + bucket.Add (enumMember); + } + + EnumMembers = bucket.ToImmutable (); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/BindingInfo.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/BindingInfo.cs new file mode 100644 index 000000000000..e050277acc3c --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/BindingInfo.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Transformer.Attributes; + +namespace Microsoft.Macios.Transformer.DataModel; + +/// +/// This struct works as a union to store the possible BindingTypeData that can be present in the bindings. +/// +readonly record struct BindingInfo { + public BaseTypeData? BaseTypeData { get; init; } + public BindingType BindingType { get; init; } + + public BindingInfo (BaseTypeData? baseTypeData, BindingType bindingType) + { + // we have to calculate the type of the binding based on the attributes that the user provided + BaseTypeData = baseTypeData; + BindingType = bindingType; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Constructor.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Constructor.Transformer.cs new file mode 100644 index 000000000000..62a8d2f153e7 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Constructor.Transformer.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Constructor { + + + /// + /// Create a constructor from a method signature. + /// + /// The method to be used to create the constructor. + public Constructor (in Method method) + { + Type = method.Type; + SymbolAvailability = method.SymbolAvailability; + Attributes = method.Attributes; + Parameters = method.Parameters; + AttributesDictionary = method.AttributesDictionary; + + // modifiers cannot only be copied, we do not have a virtual/override constructor, it is either + // public, private or internal. + var modifierBuilder = ImmutableArray.CreateBuilder (); + SyntaxKind modifier = SyntaxKind.PublicKeyword; + foreach (var methodModifier in method.Modifiers) { + var modifierKind = methodModifier.Kind (); + if (modifierKind is + SyntaxKind.PublicKeyword or SyntaxKind.ProtectedKeyword or SyntaxKind.InternalKeyword or SyntaxKind.PrivateKeyword) { + modifier = modifierKind; + } + } + + modifierBuilder.Add (Token (modifier)); + // We will be adding partial because is part of the new API + modifierBuilder.Add (Token (SyntaxKind.PartialKeyword)); + Modifiers = modifierBuilder.ToImmutable (); + + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/EnumMember.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/EnumMember.Transformer.cs new file mode 100644 index 000000000000..3ed58cbc6a82 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/EnumMember.Transformer.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Transformer.Attributes; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct EnumMember { + + /// + /// The data of the field attribute used to mark the value as a binding. + /// + public FieldInfo? FieldInfo { get; init; } + + public EnumMember (string name, + string libraryName, + string? libraryPath, + SymbolAvailability symbolAvailability, + Dictionary> attributes) + { + Name = name; + SymbolAvailability = symbolAvailability; + AttributesDictionary = attributes; + FieldInfo = FieldAttribute is null ? null : new FieldInfo (FieldAttribute.Value, libraryName, libraryPath); + } + + public EnumMember (string name, + string libraryName, + string? libraryPath, + FieldData? fieldData, + SymbolAvailability symbolAvailability) + { + Name = name; + SymbolAvailability = symbolAvailability; + FieldInfo = new (fieldData, libraryName, libraryPath); + } + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/FieldInfo.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/FieldInfo.cs new file mode 100644 index 000000000000..15f6d9473b65 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/FieldInfo.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.Macios.Transformer.Attributes; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly record struct FieldInfo { + + /// + /// Name of the library that contains the smart enum definition. + /// + public string LibraryName { get; } + + /// + /// Path of the library that contains the smart enum definition. + /// + public string? LibraryPath { get; } + + /// + /// The data of the field attribute used to mark the value as a binding. + /// + public FieldData? FieldData { get; } + + public FieldInfo (FieldData? fieldData, string libraryName, string? libraryPath = null) + { + FieldData = fieldData; + LibraryName = libraryName; + LibraryPath = libraryPath; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs new file mode 100644 index 000000000000..08d9cc6689ab --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Method { + + readonly ExportData? overrideExportData; + + /// + /// The data of the export attribute used to mark the value as a property binding. + /// + public ExportData? ExportMethodData { + get => overrideExportData ?? ExportAttribute; + init => overrideExportData = value; + } + + /// + /// Returns the bind from data if present in the binding. + /// + public BindAsData? BindAs => BindAsAttribute; + + /// + /// True if the method was exported with the MarshalNativeExceptions flag allowing it to support native exceptions. + /// + public bool MarshalNativeExceptions => HasMarshalNativeExceptionsFlag; + + const string constructorName = "Constructor"; + /// + /// True if the method is considered to be a constructor in the old bindings. + /// + public bool IsConstructor => Name == constructorName; + + public Method (string type, + string name, + TypeInfo returnType, + SymbolAvailability symbolAvailability, + Dictionary> attributes, + ImmutableArray parameters) + { + Type = type; + Name = name; + AttributesDictionary = attributes; + ReturnType = returnType; + SymbolAvailability = symbolAvailability; + Parameters = parameters; + + // create a helper struct to retrieve the modifiers + var flags = new ModifiersFlags (HasAbstractFlag, HasInternalFlag, HasNewFlag, HasOverrideFlag, HasStaticFlag); + Modifiers = flags.ToModifiersArray (); + } + + public static bool TryCreate (MethodDeclarationSyntax declaration, RootContext context, + [NotNullWhen (true)] out Method? change) + { + if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IMethodSymbol method) { + change = null; + return false; + } + var parametersBucket = ImmutableArray.CreateBuilder (); + // loop over the parameters of the construct since changes on those implies a change in the generated code + foreach (var parameter in method.Parameters) { + var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal]; + if (!Parameter.TryCreate (parameter, parameterDeclaration, context.SemanticModel, out var parameterChange)) + continue; + parametersBucket.Add (parameterChange.Value); + } + // get the attributes of the method, this are used for two reasons: + // 1. The attributes might have flags such as [Internal] or [Abstract] that we need to set in the modifiers + // 2. The attributes might have return attributes that we need to set in the return type + var attributes = method.GetAttributeData (); + change = new ( + type: method.ContainingSymbol.ToDisplayString ().Trim (), // we want the full name + name: method.Name, + returnType: new TypeInfo (method.ReturnType, attributes), + symbolAvailability: method.GetAvailabilityForSymbol (), // special case, in the transformer we only translate, we do not merge + attributes: attributes, + parameters: parametersBucket.ToImmutableArray ()); + return true; + } + + /// + /// Return the constructor representation of the method if it is a constructor in the bindings. + /// + /// A constructor data model if the method is one in the bindings or null otherwise. + public Constructor? ToConstructor () + => IsConstructor ? new Constructor (this) : null; + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs new file mode 100644 index 000000000000..0d09de4b2e65 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Generator.DataModel; + +/// +/// Helper class to store the modifiers flags. It also provides a method that will +/// return the correct modifiers according to the flags; +/// +readonly record struct ModifiersFlags { + + public bool HasAbstractFlag { get; } + public bool HasInternalFlag { get; } + public bool HasNewFlag { get; } + public bool HasOverrideFlag { get; } + public bool HasStaticFlag { get; } + + /// + /// Create a new structure with the provided flags. + /// + /// The state of the abstract flag. + /// The state of the internal flag. + /// The state of the new flag. + /// The state of the override flag. + /// The state of the static flag. + public ModifiersFlags (bool hasAbstractFlag, bool hasInternalFlag, bool hasNewFlag, bool hasOverrideFlag, bool hasStaticFlag) + { + HasAbstractFlag = hasAbstractFlag; + HasInternalFlag = hasInternalFlag; + HasNewFlag = hasNewFlag; + HasOverrideFlag = hasOverrideFlag; + HasStaticFlag = hasStaticFlag; + } + + /// + /// Returns the list of modifiers to be used with the provided set of flags. + /// + /// The list of modifiers to use to write the transformed method/property. + public ImmutableArray ToModifiersArray () + { +#pragma warning disable format + // Modifiers are special because we might be dealing with several flags that the user has set in the method. + // We have to add the partial keyword so that we can have the partial implementation of the method later generated + // by the roslyn code generator + return this switch { + // internal static partial + { HasNewFlag: false, HasStaticFlag: true, HasInternalFlag: true } + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // public static partial + { HasNewFlag: false, HasStaticFlag: true, HasInternalFlag: false } + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // internal new static partial + { HasNewFlag: true, HasStaticFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // public new static partial + { HasNewFlag: true, HasStaticFlag: true, HasInternalFlag: false } + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // public new virtual partial + { HasNewFlag: true, HasStaticFlag: false, HasAbstractFlag: false, HasInternalFlag: false } + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)], + + // internal new virtual partial + { HasNewFlag: true, HasStaticFlag: false, HasAbstractFlag: false, HasInternalFlag: true } + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)], + + // public new abstract + { HasNewFlag: true, HasAbstractFlag: true, HasInternalFlag: false} + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.AbstractKeyword)], + + // internal new abstract + { HasNewFlag: true, HasAbstractFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.AbstractKeyword)], + + // public override partial + { HasNewFlag: false, HasOverrideFlag: true, HasInternalFlag: false} + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.OverrideKeyword), Token (SyntaxKind.PartialKeyword)], + + // internal override partial + { HasNewFlag: false, HasOverrideFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.OverrideKeyword), Token (SyntaxKind.PartialKeyword)], + + // public abstract + { HasAbstractFlag: true, HasInternalFlag: false} + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.AbstractKeyword)], + + // internal abstract + { HasAbstractFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.AbstractKeyword)], + + // general case, but internal + { HasInternalFlag: true} => + [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.VirtualKeyword)], + + // general case + _ => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)] + }; +#pragma warning restore format + } + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Parameter.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Parameter.Transformer.cs new file mode 100644 index 000000000000..e7bc181a1d99 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Parameter.Transformer.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.Macios.Transformer.Attributes; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Parameter { + + /// + /// Returns the bind from data if present in the binding. + /// + public BindAsData? BindAs => BindAsAttribute; + + public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declaration, SemanticModel semanticModel, + [NotNullWhen (true)] out Parameter? parameter) + { + DelegateInfo? delegateInfo = null; + if (symbol.Type is INamedTypeSymbol namedTypeSymbol + && namedTypeSymbol.DelegateInvokeMethod is not null) { + DelegateInfo.TryCreate (namedTypeSymbol.DelegateInvokeMethod, out delegateInfo); + } + + // retrieve the parameter attributes because those might affect the parameter type, for example, the + // NullAllowed attribute can change the parameter type to be nullable. + var parameterAttrs = symbol.GetAttributeData (); + parameter = new (symbol.Ordinal, new (symbol.Type, parameterAttrs), symbol.Name) { + IsOptional = symbol.IsOptional, + IsParams = symbol.IsParams, + IsThis = symbol.IsThis, + DefaultValue = (symbol.HasExplicitDefaultValue) ? symbol.ExplicitDefaultValue?.ToString () : null, + ReferenceKind = symbol.RefKind.ToReferenceKind (), + Delegate = delegateInfo, + Attributes = declaration.GetAttributeCodeChanges (semanticModel), + AttributesDictionary = parameterAttrs, + }; + return true; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs new file mode 100644 index 000000000000..7e9d95085f4b --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct Property { + + readonly FieldData? overrideFieldData; + + /// + /// The data of the field attribute used to mark the value as a field binding. + /// + public FieldData? ExportFieldData { + get => overrideFieldData ?? FieldAttribute; + init => overrideFieldData = value; + } + + /// + /// True if the property represents a Objc field. + /// + [MemberNotNullWhen (true, nameof (ExportFieldData))] + public bool IsField => ExportFieldData is not null; + + /// + /// Returns if the field was marked as a notification. + /// + public bool IsNotification => HasNotificationAttribute; + + + readonly ExportData? overrideExportData; + + /// + /// The data of the field attribute used to mark the value as a property binding. + /// + public ExportData? ExportPropertyData { + get => overrideExportData ?? ExportAttribute; + init => overrideExportData = value; + } + + /// + /// True if the property represents a Objc property. + /// + [MemberNotNullWhen (true, nameof (ExportPropertyData))] + public bool IsProperty => ExportPropertyData is not null; + + /// + /// True if the method was exported with the MarshalNativeExceptions flag allowing it to support native exceptions. + /// + public bool MarshalNativeExceptions => HasMarshalNativeExceptionsFlag; + + /// + /// True if the property should be generated without a backing field. + /// + public bool IsTransient => IsProperty && HasTransientFlag; + + /// + /// Returns the bind from data if present in the binding. + /// + public BindAsData? BindAs => BindAsAttribute; + + /// + public bool Equals (Property other) => CoreEquals (other); + + internal Property (string name, + TypeInfo returnType, + SymbolAvailability symbolAvailability, + Dictionary> attributes, + ImmutableArray accessors) + { + Name = name; + BackingField = $"_{Name}"; + ReturnType = returnType; + SymbolAvailability = symbolAvailability; + AttributesDictionary = attributes; + Accessors = accessors; + + // the modifiers depend on whether we are talking about a field or a property. If we are talking + // about a field, we always have the same modifiers, public static. With a property we need to + // respect the flags that are set in the attributes. + if (IsField) { + // public static partial + Modifiers = [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)]; + } else { + // create a helper struct to retrieve the modifiers + var flags = new ModifiersFlags (HasAbstractFlag, HasInternalFlag, HasNewFlag, HasOverrideFlag, HasStaticFlag); + Modifiers = flags.ToModifiersArray (); + } + } + + public static bool TryCreate (PropertyDeclarationSyntax declaration, RootContext context, + [NotNullWhen (true)] out Property? property) + { + var memberName = declaration.Identifier.ToFullString ().Trim (); + // get the symbol from the property declaration + if (context.SemanticModel.GetDeclaredSymbol (declaration) is not IPropertySymbol propertySymbol) { + property = null; + return false; + } + + var propertySupportedPlatforms = propertySymbol.GetAvailabilityForSymbol (); + ImmutableArray accessors = []; + if (declaration.AccessorList is not null && declaration.AccessorList.Accessors.Count > 0) { + // calculate any possible changes in the accessors of the property + var accessorsBucket = ImmutableArray.CreateBuilder (); + foreach (var accessorDeclaration in declaration.AccessorList.Accessors) { + if (context.SemanticModel.GetDeclaredSymbol (accessorDeclaration) is not ISymbol accessorSymbol) + continue; + var kind = accessorDeclaration.Kind ().ToAccessorKind (); + accessorsBucket.Add (new ( + accessorKind: kind, + // just for the current symbol, not the parents etc.. + symbolAvailability: accessorSymbol.GetAvailabilityForSymbol (), + attributes: accessorSymbol.GetAttributeData () + )); + } + + accessors = accessorsBucket.ToImmutable (); + } + + var propertyAttributes = propertySymbol.GetAttributeData (); + property = new ( + name: memberName, + returnType: new (propertySymbol.Type, propertyAttributes), + symbolAvailability: propertySupportedPlatforms, + attributes: propertyAttributes, + accessors: accessors); + return true; + } + + /// + public override string ToString () + { + var sb = new StringBuilder ($"Name: '{Name}', Type: {ReturnType}, "); + sb.Append ($"Supported Platforms: {SymbolAvailability}, "); + sb.Append ($"ExportFieldData: '{ExportFieldData?.ToString () ?? "null"}', "); + sb.Append ($"ExportPropertyData: '{ExportPropertyData?.ToString () ?? "null"}' Attributes: ["); + sb.AppendJoin (",", Attributes); + sb.Append ("], Modifiers: ["); + sb.AppendJoin (",", Modifiers.Select (x => x.Text)); + sb.Append ("], Accessors: ["); + sb.AppendJoin (",", Accessors); + sb.Append (']'); + return sb.ToString (); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/TypeInfo.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/TypeInfo.Transformer.cs new file mode 100644 index 000000000000..5e9a7e3f40c4 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/TypeInfo.Transformer.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer; +using Microsoft.Macios.Transformer.Extensions; + +namespace Microsoft.Macios.Generator.DataModel; + +readonly partial struct TypeInfo { + + internal TypeInfo (ITypeSymbol symbol, Dictionary> attributes) : + this ( + symbol is IArrayTypeSymbol arrayTypeSymbol + ? arrayTypeSymbol.ElementType.ToDisplayString () + : symbol.ToDisplayString ().Trim ('?', '[', ']'), + symbol.SpecialType) + { + IsNullable = attributes.HasNullAllowedFlag (); + // special case, the old bindings might not have the ? operator but will have the attr + IsBlittable = symbol.IsBlittable () && !IsNullable; + IsSmartEnum = symbol.IsSmartEnum (); + IsReferenceType = symbol.IsReferenceType; + IsStruct = symbol.TypeKind == TypeKind.Struct; + IsInterface = symbol.TypeKind == TypeKind.Interface; + IsNativeIntegerType = symbol.IsNativeIntegerType; + IsNativeEnum = symbol.HasAttribute (AttributesNames.NativeAttribute); + + // data that we can get from the symbol without being INamedType + symbol.GetInheritance ( + isNSObject: out isNSObject, + isNativeObject: out isINativeObject, + isDictionaryContainer: out isDictionaryContainer, + parents: out parents, + interfaces: out interfaces); + IsArray = symbol is IArrayTypeSymbol; + + // try to get the named type symbol to have more educated decisions + var namedTypeSymbol = symbol as INamedTypeSymbol; + + // store the enum special type, useful when generate code that needs to cast + EnumUnderlyingType = namedTypeSymbol?.EnumUnderlyingType?.SpecialType; + MetadataName = SpecialType is SpecialType.None or SpecialType.System_Void + ? null : symbol.MetadataName; + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineArgumentsExtensions.cs b/src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineArgumentsExtensions.cs new file mode 100644 index 000000000000..70bc016d9eef --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineArgumentsExtensions.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Microsoft.Macios.Transformer.Extensions; + +public static class CSharpCommandLineArgumentsExtensions { + public static ImmutableArray GetReferences (this CSharpCommandLineArguments self, + string workingDirectory, string sdkDirectory) + { + var rspReferences = self.MetadataReferences.Select (r => { + var path = Path.IsPathRooted (r.Reference) + ? r.Reference + : Path.Combine (workingDirectory, r.Reference); + return path; + }); + var sdkReferences = Directory.GetFiles (sdkDirectory, "*.dll"); ; + + return rspReferences + .Union (sdkReferences) + .Distinct () + .Select (p => MetadataReference.CreateFromFile (p)) + .ToImmutableArray (); + } + + public static ImmutableArray GetSourceFiles (this CSharpCommandLineArguments self, + CSharpParseOptions options) + { + var sources = self.SourceFiles.Select (s => s.Path) + .ToImmutableArray (); + return sources.Select ( + s => CSharpSyntaxTree.ParseText (File.ReadAllText (s), options, s)) + .ToImmutableArray (); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineParserExtensions.cs b/src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineParserExtensions.cs new file mode 100644 index 000000000000..504617e94a69 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Extensions/CSharpCommandLineParserExtensions.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Reflection; +using System.Text; +using Microsoft.CodeAnalysis.CSharp; + +namespace Microsoft.Macios.Transformer.Extensions; + +static class CSharpCommandLineParserExtensions { + + public static CSharpCommandLineArguments ParseRsp (this CSharpCommandLineParser self, string rspFile, string workingDirectory, string? sdkDirectory) + { + var args = new [] { $"@{rspFile}" }; + var parseResult = self.Parse ( + args: args, + baseDirectory: workingDirectory, + sdkDirectory: sdkDirectory + ); + + if (parseResult.Errors.Length > 0) { + var sb = new StringBuilder (); + foreach (var resultError in parseResult.Errors) { + sb.AppendLine (resultError.ToString ()); + } + throw new Exception ($"Error parsing the RSP file {sb}"); + } + + return parseResult; + } + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Extensions/FieldSymbolExtensions.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/Extensions/FieldSymbolExtensions.Transformer.cs new file mode 100644 index 000000000000..39a03dda9de4 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Extensions/FieldSymbolExtensions.Transformer.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Transformer; +using Microsoft.Macios.Transformer.Attributes; + +namespace Microsoft.Macios.Generator.Extensions; + +static partial class FieldSymbolExtensions { + + /// + /// Retrieve the FieldData from the field symbol, usually used for enum values. + /// + /// The symbol under query. + /// The data of the FieldAttribute that was used on the symbol or null if it is not present. + public static FieldData? GetFieldData (this IFieldSymbol fieldSymbol) + => GetFieldData (fieldSymbol, AttributesNames.FieldAttribute, FieldData.TryParse); +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Extensions/TypeSymbolExtensions.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/Extensions/TypeSymbolExtensions.Transformer.cs new file mode 100644 index 000000000000..67d9ec26cb21 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Extensions/TypeSymbolExtensions.Transformer.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Transformer; +using Microsoft.Macios.Transformer.Attributes; +using Microsoft.Macios.Transformer.Extensions; +using Xamarin.Utils; + +namespace Microsoft.Macios.Generator.Extensions; + +static partial class TypeSymbolExtensions { + + /// + /// List of supported platforms by the transformer. + /// + static readonly ImmutableArray allSupportedPlatforms = [ + ApplePlatform.iOS, + ApplePlatform.TVOS, + ApplePlatform.MacOSX, + ApplePlatform.MacCatalyst + ]; + + /// + /// Return the symbol availability WITHOUT taking into account the parent symbols availability. + /// + /// The symbols whose availability attributes we want to retrieve. + /// The symbol availability WITHOUT taking into account the parent symbols. + /// This is a helper method, you probably don't want to use it. + internal static SymbolAvailability GetAvailabilityForSymbol (this ISymbol symbol) + { + //get the attribute of the symbol and look for the Supported and Unsupported attributes and + // add the different platforms to the result hashsets + var builder = SymbolAvailability.CreateBuilder (); + var boundAttributes = symbol.GetAttributes (); + + foreach (var attributeData in boundAttributes) { + var attrName = attributeData.AttributeClass?.ToDisplayString (); + if (string.IsNullOrEmpty (attrName)) + continue; + + if (XamarinAvailabilityData.TryParseSupportedOSData (attrName, attributeData, out var availabilityData)) { + builder.Add (availabilityData.Value); + } + + if (XamarinAvailabilityData.TryParseUnsupportedOSData (attrName, attributeData, + out var unsupportedOsPlatformData)) { + builder.Add (unsupportedOsPlatformData.Value); + } + } + + // if a platform was not ignore or had a specific version, then it is supported, loop over what we got + // and add the missing platforms with the default version + var supportedPlatforms = builder.PlatformAvailabilities.ToArray () + .Select (a => a.Platform); + + // add data to all not added platforms + foreach (var platform in allSupportedPlatforms.Except (supportedPlatforms)) { + builder.Add (new SupportedOSPlatformData (platform, new Version ())); + } + + return builder.ToImmutable (); + } + + /// + /// Return if a symbol represents a smart enum in the old Xamarin bidings. + /// + /// The symbol under query. + /// True if the symbol represents a smart enum. + public static bool IsSmartEnum (this ITypeSymbol symbol) + { + // smart enums in the classic bindings are a little more complicated to detect since we need + // to find AT LEAST one enum field that contains the Field attribute. + if (symbol.TypeKind != TypeKind.Enum) + return false; + + foreach (var member in symbol.GetMembers ()) { + if (member is not IFieldSymbol field || !field.IsConst) + continue; + + // try to get the Field attribute from the current member, if we found it, then we have a smart enum + var attributeData = field.GetAttributeData (); + if (attributeData.HasFieldAttribute ()) + return true; + } + + return false; + } + + /// + /// Returns the BaseTypeAttribute data that was used for a given symbol. + /// + /// The symbol under query. + /// The BaseTypeAttribute data if it was found, null otherwise. + public static BaseTypeData? GetBaseTypeData (this ISymbol symbol) + => GetAttribute (symbol, AttributesNames.BaseTypeAttribute, BaseTypeData.TryParse); +} diff --git a/src/rgen/Microsoft.Macios.Transformer/IO/TabbedStreamWriter.cs b/src/rgen/Microsoft.Macios.Transformer/IO/TabbedStreamWriter.cs new file mode 100644 index 000000000000..4b1b644c6b23 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/IO/TabbedStreamWriter.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Macios.Generator.IO; + +class TabbedStreamWriter : TabbedWriter { + readonly string path; + TabbedStreamWriter? parent; + + TabbedStreamWriter (string filePath, FileMode mode, FileAccess access, FileShare share, + int currentCount = 0, bool block = false) + : base (new StreamWriter (new FileStream (filePath, mode, access, share)), currentCount, block) + { + // keep track of the path we are writing to + path = filePath; + } + + public TabbedStreamWriter (string filePath, int currentCount = 0, bool block = false) + : this (filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, currentCount, block) { } + + public override TabbedWriter CreateBlock (string line, bool block) + { + // when we create a new block, the first thing we want to do is make sure that + // we flush the current writer, so we do not mix the current block with the new one + if (!string.IsNullOrEmpty (line)) { + Writer.WriteLine (line); + } + Writer.Flush (); + + // the issue now is that on the dispose method we are going to close and flush the writer, which means that + // we cannot use the writer of the parent, else we will have problems because the parent object will be closed. + // This means that in this method, it is safe to assume that we are create the tile stream as a read/write stream + // in append mode. If the file does not exist, we are ok with an exception. + var newBlock = new TabbedStreamWriter (path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, Writer.Indent, + block); + // set the parent to point to this stream, this way when we are closed, we can tell it to move fwd + newBlock.parent = this; + return newBlock; + } + + public void Flush () + { + Writer.Flush (); + } + + public async Task FlushAsync () + { + await Writer.FlushAsync (); + } + + void SyncParent () + { + // if we have a parent, move the stream to the end + parent?.InnerWriter.BaseStream.Seek (0, SeekOrigin.End); + parent = null; + } + + public override void Close () + { + base.Close (); + // if we have a parent, move the stream to the end + SyncParent (); + } + + public override async Task CloseAsync () + { + await base.CloseAsync (); + SyncParent (); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Main.cs b/src/rgen/Microsoft.Macios.Transformer/Main.cs index fb08b1498f9d..2774134b00b4 100644 --- a/src/rgen/Microsoft.Macios.Transformer/Main.cs +++ b/src/rgen/Microsoft.Macios.Transformer/Main.cs @@ -1,15 +1,189 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. using System.CommandLine; -using System.CommandLine.Builder; -using System.CommandLine.Parsing; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.Macios.Transformer; +using Serilog; +using Serilog.Core; +using Serilog.Events; +using Serilog.Templates; +using Xamarin.Utils; +using static System.Console; +public class Program { + static internal readonly LoggingLevelSwitch LogLevelSwitch = new (LogEventLevel.Information); + public static ILogger logger = Log.ForContext (); -//TODO: logging infra -// add cli header stuff -var parser = new CommandLineBuilder (new TransformCommand ()) - .UseDefaults () - .Build (); + public static int Main (string [] args) + { + // Create options + var rspOption = new Option ( + new [] { "--response-file", "--rsp" }, + "Path to the RSP file" + ); -return await parser.InvokeAsync (args).ConfigureAwait (false); + var destinationOption = new Option ( + new [] { "--destination", "-d" }, + "Path to the destination directory" + ); + + var forceOption = new Option ( + new [] { "--force", "-f" }, + "Erase the destination directory if it exists" + ); + + var workingDirectoryOption = new Option ( + new [] { "--working-directory", "-w" }, + "Absolute path to an existing working directory" + ); + + var sdkPathOption = new Option ( + new [] { "--sdk", "-s" }, + "Absolute path to the sdk directory" + ); + + var verbosityOption = new Option (["--verbosity", "-v"], + getDefaultValue: () => Verbosity.Normal) { + IsRequired = false, + Arity = ArgumentArity.ZeroOrOne, + Description = "Set the verbosity level" + }; + + // Create root command and add options + var rootCmd = new RootCommand ("command to convert outdated bindings to be rgen compatible") { + rspOption, + destinationOption, + forceOption, + workingDirectoryOption, + sdkPathOption, + verbosityOption + }; + + // If no arguments, show help and exit + if (args.Length == 0) { + rootCmd.InvokeAsync (["--help"]).Wait (); + return 0; + } + + // Set handler for parsing and executing + rootCmd.SetHandler (async (rspPlatformPaths, destPath, workingDirectory, sdkPath, force, verbosity) => { + WriteLine ( + $"Microsoft.Macios.Transformer v{typeof (Program).Assembly.GetName ().Version}, (c) Microsoft Corporation. All rights reserved.\n"); + + // Convert local to absolute, expand ~ + workingDirectory = ToAbsolutePath (workingDirectory); + destPath = ToAbsolutePath (destPath); + sdkPath = ToAbsolutePath (sdkPath); + + ValidateRsp (rspPlatformPaths, out var rspFiles); + ValidateSdk (sdkPath); + ValidateWorkingDirectory (workingDirectory); + ValidateVerbosity (verbosity); + PrepareDestination (destPath, force); + + // logging options + Log.Logger = new LoggerConfiguration () + .MinimumLevel.ControlledBy (LogLevelSwitch) + .Enrich.WithThreadName () + .Enrich.WithThreadId () + .Enrich.FromLogContext () + .WriteTo.Console (new ExpressionTemplate ( + "[{@t:HH:mm:ss} {@l:u3} {Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)} (Thread: {ThreadId})] {@m}\n")) + .CreateLogger (); + + await Transformer.Execute ( + destinationDirectory: destPath, + rspFiles: rspFiles, + workingDirectory: workingDirectory, + sdkDirectory: sdkPath + ); + }, + rspOption, destinationOption, workingDirectoryOption, sdkPathOption, forceOption, verbosityOption + ); + + // Invoke command + return rootCmd.InvokeAsync (args).Result; + } + + static string ToAbsolutePath (string path) + { + var absolutePath = path.Replace ("~", Environment.GetFolderPath (Environment.SpecialFolder.UserProfile)); + if (!Path.IsPathRooted (absolutePath)) + absolutePath = Path.GetFullPath (absolutePath); + return absolutePath; + } + + static void ValidateRsp (string [] paths, out List<(ApplePlatform Platform, string RspPath)> rspFiles) + { + rspFiles = []; + // loop over all the strings, split them by the ':' and retrieve the platform and path. Then + // validate the path + foreach (var cmdPath in paths) { + var parts = cmdPath.Split (':'); + if (parts.Length != 2) + throw new Exception ("Invalid RSP format. Expected platform:path"); + ApplePlatform platform; + var rspPath = ToAbsolutePath (parts [1]); + switch (parts [0]) { + case "ios": + platform = ApplePlatform.iOS; + break; + case "tvos": + platform = ApplePlatform.TVOS; + break; + case "macos": + platform = ApplePlatform.MacOSX; + break; + case "maccatalys": + platform = ApplePlatform.MacCatalyst; + break; + default: + platform = ApplePlatform.None; + break; + } + + if (platform == ApplePlatform.None) + throw new Exception ("Invalid platform in RSP file."); + + if (string.IsNullOrWhiteSpace (rspPath) || !File.Exists (rspPath)) + throw new FileNotFoundException ($"RSP '{rspPath}' file not found."); + if ((File.GetAttributes (rspPath) & FileAttributes.Directory) == FileAttributes.Directory) + throw new Exception ($"RSP {rspPath} is a directory."); + using var stream = File.OpenRead (rspPath); // validate readability + logger.Debug ("Adding RSP file {RspPath} for platform {Platform}", rspPath, platform); + rspFiles.Add ((platform, rspPath)); + } + } + + static void ValidateWorkingDirectory (string path) + { + if (string.IsNullOrWhiteSpace (path) || !Directory.Exists (path)) + throw new DirectoryNotFoundException ("Working directory does not exist."); + } + + static void ValidateSdk (string path) + { + if (string.IsNullOrWhiteSpace (path) || !Directory.Exists (path)) + throw new DirectoryNotFoundException ("Working directory does not exist."); + } + + static void ValidateVerbosity (Verbosity verbosity) + { + LogLevelSwitch.MinimumLevel = verbosity switch { + Verbosity.Quiet => LogEventLevel.Error, + Verbosity.Minimal => LogEventLevel.Error, + Verbosity.Normal => LogEventLevel.Information, + Verbosity.Detailed => LogEventLevel.Verbose, + Verbosity.Diagnostic => LogEventLevel.Verbose, + _ => LogEventLevel.Information, + }; + } + + static void PrepareDestination (string path, bool force) + { + if (Directory.Exists (path)) { + if (force) + Directory.Delete (path, true); + } + + Directory.CreateDirectory (path); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj index cfb93fbb09a0..32cbe4391228 100644 --- a/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj +++ b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj @@ -6,17 +6,114 @@ enable enable true + + true + + - - - + + + + + + + + + + + + + + + <_Parameter1>Microsoft.Macios.Transformer.Tests + + + + + + DictionaryComparer.cs + + + CollectionComparer.cs + + + IO/TabbedWriter.cs + + + IO/TabbedStringBuilder.cs + + + Attributes/ObsoletedOSPlatformData.cs + + + Attributes/SupportedOSPlatformData.cs + + + Attributes/UnsupportedOSPlatformData.cs + + + Availability/*.cs + + + Context/RootContext.cs + + + Extensions/ApplePlatformExtensions.cs + + + Extensions/BaseTypeDeclarationSyntaxExtensions.cs + + + Extensions/CompilationExtensions.cs + + + Extensions/Delegates.cs + + + Extensions/FieldSymbolExtensions.cs + + + Extensions/ParameterSyntaxExtensions.cs + + + Extensions/SemanticModelExtensions.cs + + + Extensions/SpecialTypeExtensions.cs + + + Extensions/StringExtensions.cs + + + Extensions/SyntaxTreeExtensions.cs + + + Extensions/TypeSymbolExtensions.Core.cs + + + external\PlatformNameExtensions.cs + + + + + + DataModel/*.cs + + + + + + + + + - - + + diff --git a/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.sln b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.sln new file mode 100644 index 000000000000..74ffba247e0c --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.sln @@ -0,0 +1,24 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.2.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Transformer", "Microsoft.Macios.Transformer.csproj", "{8D4FAA36-675C-5F33-92D7-A6440828B2BC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8D4FAA36-675C-5F33-92D7-A6440828B2BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8D4FAA36-675C-5F33-92D7-A6440828B2BC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8D4FAA36-675C-5F33-92D7-A6440828B2BC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8D4FAA36-675C-5F33-92D7-A6440828B2BC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {81DFC821-B8E9-42DE-8D1A-08C4BE248FE8} + EndGlobalSection +EndGlobal diff --git a/src/rgen/Microsoft.Macios.Transformer/TransformCommand.cs b/src/rgen/Microsoft.Macios.Transformer/TransformCommand.cs deleted file mode 100644 index 20c51b813c94..000000000000 --- a/src/rgen/Microsoft.Macios.Transformer/TransformCommand.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -using System.CommandLine; - -namespace Microsoft.Macios.Transformer; - -public class TransformCommand : Command { - - public TransformCommand () : base ("rgen-transform", "command to convert outdated bindings to be rgen compatible") - { - var input = new Option (["--input", "-i"], "input directory to search for bgen bindings") { - //single file support? - IsRequired = true - }; - AddOption (input); - - var output = new Option (["--output", "-o"], "output directory to write rgen bindings") { - IsRequired = true - }; - AddOption (output); - - AddValidator (result => { - if (!Directory.Exists (result.GetValueForOption (input))) { - result.ErrorMessage = "Input directory does not exist"; - } - if (!Directory.Exists (result.GetValueForOption (output))) { - Directory.CreateDirectory (result.GetValueForOption (output)!); - } - }); - // this.AddOption (new Option (new string [] { "--verbose", "-v" }, "verbose output")); - - this.SetHandler (Execute); - } - - public async Task Execute () - { - // placeholder for loading/parsing/transforming/writing components - await Task.CompletedTask; - } -} diff --git a/src/rgen/Microsoft.Macios.Transformer/Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/Transformer.cs new file mode 100644 index 000000000000..cea8cb384373 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Transformer.cs @@ -0,0 +1,281 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Marille; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Extensions; +using Microsoft.Macios.Transformer.Workers; +using Serilog; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer; + +/// +/// Main class that performs the transformation of the bindings. This class will set all the necessary wiring +/// to be able to process the different transformations per binding type. +/// +class Transformer { + readonly static ILogger logger = Log.ForContext (); + readonly string destinationDirectory; + readonly ImmutableArray<(ApplePlatform Platform, Compilation Compilation)> compilations; + readonly HashSet? namespaceFilter; + readonly Dictionary> transformers = new (); + + internal Transformer (string destination, + ImmutableArray<(ApplePlatform Platform, Compilation Compilation)> compilationsResult, + IEnumerable? namespaces = null) + { + destinationDirectory = destination; + compilations = compilationsResult; + if (namespaces is not null) + namespaceFilter = new HashSet (namespaces); + + ITransformer<(string Path, string SymbolName)> [] defaultTransformers = [ + new CategoryTransformer (destinationDirectory), + new ClassTransformer (destinationDirectory), + new ProtocolTransformer (destinationDirectory), + new SmartEnumTransformer (destinationDirectory), + new StrongDictionaryTransformer (destinationDirectory), + new CopyTransformer (destinationDirectory), + new ErrorDomainTransformer (destinationDirectory), + ]; + // init the dict of transformers to access them via the name of the class + foreach (var transformer in defaultTransformers) { + transformers.Add (transformer.GetType ().Name, transformer); + } + } + + internal async Task CreateHub () + { + // create the hub that will manage the channels + var hub = new Hub (); + + // use as many threads as the system allows + var configuration = new TopicConfiguration { Mode = ChannelDeliveryMode.AtLeastOnceSync }; + foreach (var (topicName, transformer) in transformers) { + await hub.CreateAsync (topicName, configuration, transformer, transformer); + logger.Information ("Created new topic '{TopicName}'", topicName); + } + + return hub; + } + + internal static string? SelectTopic (INamedTypeSymbol symbol) + { + // get the attrs, based on those return the correct topic to use + var attrs = symbol.GetAttributeData (); + logger.Debug ("Symbol '{SymbolName}' has [{Attributes}] attributes", symbol.Name, + string.Join (", ", attrs.Keys)); + logger.Debug ("Symbol '{SymbolName}' kind is '{SymbolKind}'", symbol.Name, symbol.TypeKind); + + if (symbol.TypeKind == TypeKind.Enum) { + // simplest case, an error domain + if (attrs.ContainsKey (AttributesNames.ErrorDomainAttribute)) { + logger.Debug ("Symbol '{SymbolName}' is an error domain", symbol.Name); + return nameof (ErrorDomainTransformer); + } + + // in this case, we need to check if the enum is a smart enum. + // Smart enum: One of the enum members contains a FieldAttribute. Does NOT have to be ALL + var enumMembers = symbol.GetMembers ().OfType ().ToArray (); + foreach (var enumField in enumMembers) { + var fieldAttrs = enumField.GetAttributeData (); + if (fieldAttrs.ContainsKey (AttributesNames.FieldAttribute)) { + logger.Debug ("Symbol '{SymbolName}' is a smart enum", symbol.Name); + return nameof (SmartEnumTransformer); + } + } + + // we have either a native enum of a regular enum, we will use the copy worker + logger.Debug ("Symbol '{SymbolName}' is a regular enum", symbol.Name); + return nameof (CopyTransformer); + } + + if (attrs.ContainsKey (AttributesNames.BaseTypeAttribute)) { + // if can be a class or a protocol, check if the protocol attribute is present + if (attrs.ContainsKey (AttributesNames.ProtocolAttribute) || + attrs.ContainsKey (AttributesNames.ModelAttribute)) { + logger.Debug ("Symbol '{SymbolName}' is a protocol", symbol.Name); + return nameof (ProtocolTransformer); + } + + if (attrs.ContainsKey (AttributesNames.CategoryAttribute)) { + logger.Debug ("Symbol '{SymbolName}' is a category", symbol.Name); + return nameof (CategoryTransformer); + } + + logger.Debug ("Symbol '{SymbolName}' is a class", symbol.Name); + return nameof (ClassTransformer); + } + + if (attrs.ContainsKey (AttributesNames.StrongDictionaryAttribute)) { + logger.Debug ("Symbol '{SymbolName}' is a strong dictionary", symbol.Name); + return nameof (StrongDictionaryTransformer); + } + + logger.Warning ("Symbol '{SymbolName}' could not be matched to a transformer", symbol.Name); + return null; + } + + internal bool Skip (SyntaxTree syntaxTree, ISymbol symbol, [NotNullWhen (false)] out string? outputDirectory) + { + outputDirectory = null; + var symbolNamespace = symbol.ContainingNamespace.ToString (); + if (symbolNamespace is null) + // skip we could not retrieve the namespace + return true; + + if (namespaceFilter is not null && !namespaceFilter.Contains (symbolNamespace)) { + // TODO we could do this better by looking at the tree + logger.Information ("Skipping '{SymbolName}' because namespace it was not included in the transformation", + symbol.Name, symbolNamespace); + // filtered out + return true; + } + + outputDirectory = Path.Combine (destinationDirectory, symbolNamespace); + // If the syntax tree comes from the output directory, we skip it because this is a manual binding + return syntaxTree.FilePath.StartsWith (outputDirectory); + } + + internal async Task Execute () + { + // few things to do here: + // 1. Ignore the syntax trees that either have a path ending with the extension of the generator since that + // is generated code. + // 2. Ignore the syntax trees that are not from the namespace if that filter was added. The simplest way + // to get the namespace is to get the symbol that is related to the tree, since we are doing that + // operation, we keep the symbol and use it to create our data mode. + // 3. Create the data model for the transformation. + // 4. Base on the data model push the data model object to a channel to be consumed. + + // create the hub that will manage the channels + var hub = await CreateHub (); + + // with the hub created, loop over the syntax trees and create the messages to be sent to the hub + // TODO: this is a temporary nested loop to exercise the channels, this will be removed + foreach (var (platform, compilation) in compilations) { + foreach (var tree in compilation.SyntaxTrees) { + var model = compilation.GetSemanticModel (tree); + // the bindings have A LOT of interfaces, we cannot get a symbol for the entire tree + var declarations = (await tree.GetRootAsync ()) + .DescendantNodes () + .OfType ().ToArray (); + + logger.Debug ("Found '{Declarations}' interfaces in '{FilePath}'", declarations.Length, tree.FilePath); + + // loop over the declarations and send them to the hub + foreach (var declaration in declarations) { + var symbol = model.GetDeclaredSymbol (declaration); + if (symbol is null) { + // skip the transformation because the symbol is null + logger.Warning ("Could not get the symbol for '{Declaration}'", declaration.Identifier); + continue; + } + + if (Skip (tree, symbol, out var outputDirectory)) { + // matched the filter + logger.Information ("Skipping '{SymbolName}' because it was filtered out", symbol.Name); + continue; + } + + // create the destination directory if needed, this is the only location we should be creating directories + Directory.CreateDirectory (outputDirectory); + + var topicName = SelectTopic (symbol); + if (topicName is not null && transformers.TryGetValue (topicName, out var transformer)) { + await hub.PublishAsync (topicName, transformer.CreateMessage (tree, symbol)); + logger.Information ("Published '{SymbolName}' to '{TopicName}'", symbol.Name, topicName); + } + } + } + } + + // all messages have been sent, wait for them to be consumed, at that point all transformations have been + // completed + await hub.CloseAllAsync (); + } + + static Task + CreateCompilationAsync (ApplePlatform platform, string rspFile, string workingDirectory, string sdkDirectory) + => Task.Run (() => { + logger.Debug ("Executing compilation for '{Platform}'", platform); + return CreateCompilation (platform, rspFile, workingDirectory, sdkDirectory); + }); + + static CompilationResult CreateCompilation ( + ApplePlatform platform, string rspFile, string workingDirectory, string sdkDirectory) + { + // perform the compilation on a background thread, that way we can have several of them at the same time + var parseResult = CSharpCommandLineParser.Default.ParseRsp ( + rspFile, workingDirectory, sdkDirectory); + logger.Information ("Rsp file {RspFile} parsed with {ParseErrors} errors", rspFile, parseResult.Errors.Length); + + // add NET to the preprocessor directives + var preprocessorDirectives = parseResult.ParseOptions.PreprocessorSymbolNames.ToList (); + preprocessorDirectives.Add ("NET"); + + // fixing the parsing options, we must have an issue in the rsp + var updatedParseOptions = parseResult.ParseOptions + .WithLanguageVersion (LanguageVersion.Latest) + .WithPreprocessorSymbols (preprocessorDirectives) + .WithDocumentationMode (DocumentationMode.None); + + var references = parseResult.GetReferences (workingDirectory, sdkDirectory); + logger.Information ("References {References}", references.Length); + var parsedSource = parseResult.GetSourceFiles (updatedParseOptions); + logger.Information ("Parsed {Files} files", parsedSource.Length); + + var compilation = CSharpCompilation.Create ( + assemblyName: $"{parseResult.CompilationName}-transformer", + syntaxTrees: parsedSource, + references: references, + options: parseResult.CompilationOptions); + var errors = compilation.GetDiagnostics () + .Where (d => d.Severity == DiagnosticSeverity.Error) + .ToImmutableArray (); + return new (platform, compilation, errors); + } + + public static async Task Execute (string destinationDirectory, + List<(ApplePlatform Platform, string RspPath)> rspFiles, string workingDirectory, + string sdkDirectory) + { + logger.Information ("Executing transformation"); + // use the async method to run several compilations in parallel, that way we do not block on eachother + var compilationTasks = new List> (); + foreach (var (platform, rspPath) in rspFiles) { + compilationTasks.Add (CreateCompilationAsync (platform, rspPath, workingDirectory, sdkDirectory)); + } + + var compilations = await Task.WhenAll (compilationTasks); + + // verify we have no errors in the compilations + foreach (var (platform, api, errors) in compilations) { + if (errors.Length == 0) + continue; + + logger.Error ("Compilation failed from {Platform} with {ErrorCount} errors", platform, errors.Length); + var sb = new StringBuilder (); + foreach (var error in errors) { + sb.AppendLine (error.ToString ()); + } + + throw new Exception (sb.ToString ()); + } + + ImmutableArray<(ApplePlatform Platform, Compilation Compilation)> compilationTuples = [ + .. compilations + .Select (c => c.ToTuple ()) + ]; + // create a new transformer with the compilation result and the syntax trees + var transformer = new Transformer (destinationDirectory, compilationTuples); + await transformer.Execute (); + } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Verbosity.cs b/src/rgen/Microsoft.Macios.Transformer/Verbosity.cs new file mode 100644 index 000000000000..d453a840bd68 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Verbosity.cs @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Macios.Transformer; + +enum Verbosity { + Quiet, + Minimal, + Normal, + Detailed, + Diagnostic +} + diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/CategoryTransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/CategoryTransformer.cs new file mode 100644 index 000000000000..8c2a86dbaa53 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/CategoryTransformer.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; +using Serilog; + +namespace Microsoft.Macios.Transformer.Workers; + +public class CategoryTransformer (string destinationDirectory) : ITransformer<(string Path, string SymbolName)> { + + readonly static ILogger logger = Log.ForContext (); + public bool UseBackgroundThread { get => true; } + + public Task ConsumeAsync ((string Path, string SymbolName) message, CancellationToken token = new ()) + { + logger.Information ("Transforming {SymbolName} for path {Path} to {DestinationDirectory}", + message.SymbolName, message.Path, destinationDirectory); + return Task.Delay (10); + } + + public Task ConsumeAsync ((string Path, string SymbolName) message, Exception exception, + CancellationToken token = new CancellationToken ()) + { + logger.Error (exception, "Error transforming {SymbolName} for path {Path} to {DestinationDirectory}:", + message.SymbolName, message.Path, destinationDirectory); + return Task.CompletedTask; + } + + public (string Path, string SymbolName) CreateMessage (SyntaxTree treeNode, ISymbol symbol) + { + return (treeNode.FilePath, symbol.Name); + } + + public void Dispose () { } + + public ValueTask DisposeAsync () => ValueTask.CompletedTask; + + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/ClassTransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/ClassTransformer.cs new file mode 100644 index 000000000000..911308705dbd --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/ClassTransformer.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; +using Serilog; + +namespace Microsoft.Macios.Transformer.Workers; + +public class ClassTransformer (string destinationDirectory) : ITransformer<(string Path, string SymbolName)> { + + readonly static ILogger logger = Log.ForContext (); + public ValueTask DisposeAsync () => ValueTask.CompletedTask; + public Task ConsumeAsync ((string Path, string SymbolName) message, CancellationToken token = new ()) + { + logger.Information ("Transforming {SymbolName} for path {Path} to {DestinationDirectory}", + message.SymbolName, message.Path, destinationDirectory); + return Task.Delay (10); + } + + public Task ConsumeAsync ((string Path, string SymbolName) message, Exception exception, + CancellationToken token = new CancellationToken ()) + { + logger.Error (exception, "Error transforming {SymbolName} for path {Path} to {DestinationDirectory}:", + message.SymbolName, message.Path, destinationDirectory); + return Task.CompletedTask; + } + + public (string Path, string SymbolName) CreateMessage (SyntaxTree treeNode, ISymbol symbol) + { + return (treeNode.FilePath, symbol.Name); + } + + public void Dispose () { } + + + public bool UseBackgroundThread { get => true; } +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/CopyTransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/CopyTransformer.cs new file mode 100644 index 000000000000..a175af989eb2 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/CopyTransformer.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; +using Serilog; + +namespace Microsoft.Macios.Transformer.Workers; + +public class CopyTransformer (string destinationDirectory) : ITransformer<(string Path, string SymbolName)> { + + readonly static ILogger logger = Log.ForContext (); + public bool UseBackgroundThread { get => true; } + + public Task ConsumeAsync ((string Path, string SymbolName) message, CancellationToken token = new ()) + { + logger.Information ("Transforming {SymbolName} for path {Path} to {DestinationDirectory}", + message.SymbolName, message.Path, destinationDirectory); + return Task.Delay (10); + } + + public Task ConsumeAsync ((string Path, string SymbolName) message, Exception exception, + CancellationToken token = new CancellationToken ()) + { + logger.Error (exception, "Error transforming {SymbolName} for path {Path} to {DestinationDirectory}:", + message.SymbolName, message.Path, destinationDirectory); + return Task.CompletedTask; + } + + public (string Path, string SymbolName) CreateMessage (SyntaxTree treeNode, ISymbol symbol) + { + return (treeNode.FilePath, symbol.Name); + } + + public void Dispose () { } + + public ValueTask DisposeAsync () => ValueTask.CompletedTask; + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/ErrorDomainTransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/ErrorDomainTransformer.cs new file mode 100644 index 000000000000..3b58d9799423 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/ErrorDomainTransformer.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; +using Serilog; + +namespace Microsoft.Macios.Transformer.Workers; + + +public class ErrorDomainTransformer (string destinationDirectory) : ITransformer<(string Path, string SymbolName)> { + + readonly static ILogger logger = Log.ForContext (); + public bool UseBackgroundThread { get => true; } + + public Task ConsumeAsync ((string Path, string SymbolName) message, CancellationToken token = new ()) + { + logger.Information ("Transforming {SymbolName} for path {Path} to {DestinationDirectory}", + message.SymbolName, message.Path, destinationDirectory); + return Task.Delay (10); + } + + public Task ConsumeAsync ((string Path, string SymbolName) message, Exception exception, + CancellationToken token = new CancellationToken ()) + { + logger.Error (exception, "Error transforming {SymbolName} for path {Path} to {DestinationDirectory}:", + message.SymbolName, message.Path, destinationDirectory); + return Task.CompletedTask; + } + + public (string Path, string SymbolName) CreateMessage (SyntaxTree treeNode, ISymbol symbol) + { + return (treeNode.FilePath, symbol.Name); + } + + public void Dispose () { } + + public ValueTask DisposeAsync () => ValueTask.CompletedTask; + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/ITransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/ITransformer.cs new file mode 100644 index 000000000000..9f586727759d --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/ITransformer.cs @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Workers; + +interface ITransformer : IWorker, IErrorWorker where T : struct { + + T CreateMessage (SyntaxTree treeNode, ISymbol symbol); +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/ProtocolTransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/ProtocolTransformer.cs new file mode 100644 index 000000000000..9cac73144b97 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/ProtocolTransformer.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; +using Serilog; + +namespace Microsoft.Macios.Transformer.Workers; + +public class ProtocolTransformer (string destinationDirectory) : ITransformer<(string Path, string SymbolName)> { + + readonly static ILogger logger = Log.ForContext (); + public bool UseBackgroundThread { get => true; } + public Task ConsumeAsync ((string Path, string SymbolName) message, CancellationToken token = new ()) + { + logger.Information ("Transforming {SymbolName} for path {Path} to {DestinationDirectory}", + message.SymbolName, message.Path, destinationDirectory); + return Task.Delay (10); + } + + public Task ConsumeAsync ((string Path, string SymbolName) message, Exception exception, + CancellationToken token = new CancellationToken ()) + { + logger.Error (exception, "Error transforming {SymbolName} for path {Path} to {DestinationDirectory}:", + message.SymbolName, message.Path, destinationDirectory); + return Task.CompletedTask; + } + + public (string Path, string SymbolName) CreateMessage (SyntaxTree treeNode, ISymbol symbol) + { + return (treeNode.FilePath, symbol.Name); + } + + public void Dispose () { } + + public ValueTask DisposeAsync () => ValueTask.CompletedTask; + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/SmartEnumTransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/SmartEnumTransformer.cs new file mode 100644 index 000000000000..f9b51ade9e62 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/SmartEnumTransformer.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; +using Serilog; + +namespace Microsoft.Macios.Transformer.Workers; + +public class SmartEnumTransformer (string destinationDirectory) : ITransformer<(string Path, string SymbolName)> { + + readonly static ILogger logger = Log.ForContext (); + public bool UseBackgroundThread { get => true; } + + public Task ConsumeAsync ((string Path, string SymbolName) message, CancellationToken token = new ()) + { + logger.Information ("Transforming {SymbolName} for path {Path} to {DestinationDirectory}", + message.SymbolName, message.Path, destinationDirectory); + return Task.Delay (10); + } + + public Task ConsumeAsync ((string Path, string SymbolName) message, Exception exception, + CancellationToken token = new CancellationToken ()) + { + logger.Error (exception, "Error transforming {SymbolName} for path {Path} to {DestinationDirectory}:", + message.SymbolName, message.Path, destinationDirectory); + return Task.CompletedTask; + } + + public (string Path, string SymbolName) CreateMessage (SyntaxTree treeNode, ISymbol symbol) + { + return (treeNode.FilePath, symbol.Name); + } + + public void Dispose () { } + + public ValueTask DisposeAsync () => ValueTask.CompletedTask; + +} diff --git a/src/rgen/Microsoft.Macios.Transformer/Workers/StrongDictionaryTransformer.cs b/src/rgen/Microsoft.Macios.Transformer/Workers/StrongDictionaryTransformer.cs new file mode 100644 index 000000000000..7af1ac02761d --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/Workers/StrongDictionaryTransformer.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Marille; +using Microsoft.CodeAnalysis; +using Serilog; + +namespace Microsoft.Macios.Transformer.Workers; + +public class StrongDictionaryTransformer (string destinationDirectory) : ITransformer<(string Path, string SymbolName)> { + + readonly static ILogger logger = Log.ForContext (); + public bool UseBackgroundThread { get => true; } + public Task ConsumeAsync ((string Path, string SymbolName) message, CancellationToken token = new ()) + { + logger.Information ("Transforming {SymbolName} for path {Path} to {DestinationDirectory}", + message.SymbolName, message.Path, destinationDirectory); + return Task.Delay (10); + } + + public Task ConsumeAsync ((string Path, string SymbolName) message, Exception exception, + CancellationToken token = new CancellationToken ()) + { + logger.Error (exception, "Error transforming {SymbolName} for path {Path} to {DestinationDirectory}:", + message.SymbolName, message.Path, destinationDirectory); + return Task.CompletedTask; + } + + public (string Path, string SymbolName) CreateMessage (SyntaxTree treeNode, ISymbol symbol) + { + return (treeNode.FilePath, symbol.Name); + } + + public void Dispose () { } + + public ValueTask DisposeAsync () => ValueTask.CompletedTask; + +} diff --git a/src/rgen/rgen.sln b/src/rgen/rgen.sln index 12549b0432a6..a1d7eb8923b2 100644 --- a/src/rgen/rgen.sln +++ b/src/rgen/rgen.sln @@ -1,6 +1,6 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# +# Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Generator", "Microsoft.Macios.Generator\Microsoft.Macios.Generator.csproj", "{8E9CF45D-E836-447E-9290-03A9CACE2704}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Generator.Sample", "Microsoft.Macios.Generator.Sample\Microsoft.Macios.Generator.Sample.csproj", "{AD0A1FDC-350F-47E2-AA9D-A6F32793C130}" @@ -18,10 +18,13 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Transformer", "Microsoft.Macios.Transformer\Microsoft.Macios.Transformer.csproj", "{D05D2AAA-71C9-49C9-B344-2F8C251E60DB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Transformer.Tests", "..\..\tests\rgen\Microsoft.Macios.Transformer.Tests\Microsoft.Macios.Transformer.Tests.csproj", "{BE23E467-7971-4439-BEE8-220B77F40027}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Bindings.CodeFixers", "Microsoft.Macios.Bindings.CodeFixers\Microsoft.Macios.Bindings.CodeFixers.csproj", "{4986D2E4-89B0-43A3-9879-93ED236C265D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Bindings.CodeFixers.Tests", "..\..\tests\rgen\Microsoft.Macios.Bindings.CodeFixers.Tests\Microsoft.Macios.Bindings.CodeFixers.Tests.csproj", "{E7928D64-8E45-40BF-B393-732FF20D35E7}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Macios.Transformer.Generator", "Microsoft.Macios.Transformer.Generator\Microsoft.Macios.Transformer.Generator\Microsoft.Macios.Transformer.Generator.csproj", "{F961C35E-51DA-483A-BE85-781F90EC21DA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -72,5 +75,9 @@ Global {E7928D64-8E45-40BF-B393-732FF20D35E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {E7928D64-8E45-40BF-B393-732FF20D35E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {E7928D64-8E45-40BF-B393-732FF20D35E7}.Release|Any CPU.Build.0 = Release|Any CPU + {F961C35E-51DA-483A-BE85-781F90EC21DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F961C35E-51DA-483A-BE85-781F90EC21DA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F961C35E-51DA-483A-BE85-781F90EC21DA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F961C35E-51DA-483A-BE85-781F90EC21DA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/src/scenekit.cs b/src/scenekit.cs index ed14e0b6e0a4..dc58ba55938a 100644 --- a/src/scenekit.cs +++ b/src/scenekit.cs @@ -4063,7 +4063,7 @@ interface SCNAction : NSCopying, NSSecureCoding { [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] #if NET - Func TimingFunction { get; set; } + Func TimingFunction { get; set; } #else Func TimingFunction2 { get; set; } #endif diff --git a/src/sharedwithyou.cs b/src/sharedwithyou.cs index 0d92484412c3..47b631dc0ee3 100644 --- a/src/sharedwithyou.cs +++ b/src/sharedwithyou.cs @@ -19,12 +19,12 @@ #if MONOMAC using AppKit; -using UIViewController = AppKit.NSViewController; -using UIView = AppKit.NSView; -using UIMenu = AppKit.NSMenu; -using UIImage = AppKit.NSImage; -using ICloudSharingControllerDelegate = AppKit.INSCloudSharingServiceDelegate; -using UIWindow = AppKit.NSWindow; +using UIViewController=AppKit.NSViewController; +using UIView=AppKit.NSView; +using UIMenu=AppKit.NSMenu; +using UIImage=AppKit.NSImage; +using ICloudSharingControllerDelegate=AppKit.INSCloudSharingServiceDelegate; +using UIWindow=AppKit.NSWindow; #else using UIKit; using ICloudSharingControllerDelegate = UIKit.IUICloudSharingControllerDelegate; diff --git a/src/soundanalysis.cs b/src/soundanalysis.cs index 2b723ba87212..997463167641 100644 --- a/src/soundanalysis.cs +++ b/src/soundanalysis.cs @@ -210,7 +210,7 @@ interface SNTimeDurationConstraint /* privately conforms to NSCoding, NSCopying, SNTimeDurationConstraintType Type { get; } #if NET - [BindAs (typeof (CMTime []))] + [BindAs (typeof (CMTime[]))] #endif [Export ("enumeratedDurations", ArgumentSemantic.Strong)] NSValue [] EnumeratedDurations { get; } diff --git a/src/spritekit.cs b/src/spritekit.cs index f832ac4342d9..13fb0d316acb 100644 --- a/src/spritekit.cs +++ b/src/spritekit.cs @@ -21,7 +21,6 @@ using SceneKit; using Metal; -#if NET using MatrixFloat2x2 = global::CoreGraphics.NMatrix2; using MatrixFloat3x3 = global::CoreGraphics.NMatrix3; using MatrixFloat4x4 = global::CoreGraphics.NMatrix4; @@ -30,19 +29,6 @@ using Vector4 = global::System.Numerics.Vector4; using VectorFloat3 = global::CoreGraphics.NVector3; using Quaternion = global::System.Numerics.Quaternion; -#else -using Matrix2 = global::OpenTK.Matrix2; -using Matrix3 = global::OpenTK.Matrix3; -using Matrix4 = global::OpenTK.Matrix4; -using MatrixFloat2x2 = global::OpenTK.NMatrix2; -using MatrixFloat3x3 = global::OpenTK.NMatrix3; -using MatrixFloat4x4 = global::OpenTK.NMatrix4; -using Vector2 = global::OpenTK.Vector2; -using Vector3 = global::OpenTK.Vector3; -using Vector4 = global::OpenTK.Vector4; -using VectorFloat3 = global::OpenTK.NVector3; -using Quaternion = global::OpenTK.Quaternion; -#endif #if MONOMAC using AppKit; @@ -50,22 +36,12 @@ using UIImage = global::AppKit.NSImage; using UIView = global::AppKit.NSView; using UITouch = Foundation.NSObject; -#if NET -using pfloat = System.Runtime.InteropServices.NFloat; -#else -using pfloat = System.nfloat; -#endif #else using UIKit; using NSLineBreakMode = global::UIKit.UILineBreakMode; -using pfloat = System.Single; using NSEvent = System.Object; #endif -#if !NET -using NativeHandle = System.IntPtr; -#endif - namespace SpriteKit { /// The delegate that acts as the enumeration handler for . delegate void SKNodeChildEnumeratorHandler (SKNode node, out bool stop); @@ -133,3386 +109,3266 @@ interface SK3DNode { [MacCatalyst (13, 1)] #if MONOMAC [BaseType (typeof (NSResponder))] - partial interface SKNode : NSSecureCoding, NSCopying { -#elif IOS || TVOS - [BaseType (typeof (UIResponder))] - partial interface SKNode : NSSecureCoding, NSCopying, UIFocusItem, UIFocusItemContainer, UICoordinateSpace { #else -#error Unknown platform + [BaseType (typeof (UIResponder))] #endif - [DesignatedInitializer] - [Export ("init")] - NativeHandle Constructor (); - - [Static, Export ("node")] - SKNode Create (); - - [MacCatalyst (13, 1)] - [Static] - [Export ("nodeWithFileNamed:")] - [return: NullAllowed] - SKNode Create (string filename); - - [MacCatalyst (13, 1)] - [Internal] - [Static] - [Export ("nodeWithFileNamed:securelyWithClasses:andError:")] - [return: NullAllowed] - SKNode Create (string filename, IntPtr classesPtr, out NSError error); - - [Export ("frame")] + partial interface SKNode : NSSecureCoding, NSCopying +#if IOS || TVOS + , UIFocusItem, UIFocusItemContainer, UICoordinateSpace +#endif + { + [DesignatedInitializer] + [Export ("init")] + NativeHandle Constructor (); + + [Static, Export ("node")] + SKNode Create (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("nodeWithFileNamed:")] + [return: NullAllowed] + SKNode Create (string filename); + + [MacCatalyst (13, 1)] + [Internal] + [Static] + [Export ("nodeWithFileNamed:securelyWithClasses:andError:")] + [return: NullAllowed] + SKNode Create (string filename, IntPtr classesPtr, out NSError error); + + [Export ("frame")] #if !MONOMAC - // For iOS+tvOS we also get this property from the UIFocusItem protocol, but we redefine it here to get the right availability attributes. - new + // For iOS+tvOS we also get this property from the UIFocusItem protocol, but we redefine it here to get the right availability attributes. + new #endif - CGRect Frame { get; } + CGRect Frame { get; } - [Export ("calculateAccumulatedFrame")] - CGRect CalculateAccumulatedFrame (); + [Export ("calculateAccumulatedFrame")] + CGRect CalculateAccumulatedFrame (); - [Export ("position")] - CGPoint Position { get; set; } + [Export ("position")] + CGPoint Position { get; set; } - [Export ("zPosition")] - nfloat ZPosition { get; set; } + [Export ("zPosition")] + nfloat ZPosition { get; set; } - [Export ("zRotation")] - nfloat ZRotation { get; set; } + [Export ("zRotation")] + nfloat ZRotation { get; set; } - [Export ("xScale")] - nfloat XScale { get; set; } + [Export ("xScale")] + nfloat XScale { get; set; } - [Export ("yScale")] - nfloat YScale { get; set; } + [Export ("yScale")] + nfloat YScale { get; set; } - [Export ("speed")] - nfloat Speed { get; set; } + [Export ("speed")] + nfloat Speed { get; set; } - [Export ("alpha")] - nfloat Alpha { get; set; } + [Export ("alpha")] + nfloat Alpha { get; set; } - [Export ("paused")] - bool Paused { [Bind ("isPaused")] get; set; } + [Export ("paused")] + bool Paused { [Bind ("isPaused")] get; set; } - [Export ("hidden")] - bool Hidden { [Bind ("isHidden")] get; set; } + [Export ("hidden")] + bool Hidden { [Bind ("isHidden")] get; set; } - [Export ("userInteractionEnabled")] - bool UserInteractionEnabled { [Bind ("isUserInteractionEnabled")] get; set; } + [Export ("userInteractionEnabled")] + bool UserInteractionEnabled { [Bind ("isUserInteractionEnabled")] get; set; } - [NoMac] - [MacCatalyst (13, 1)] - [Export ("focusBehavior", ArgumentSemantic.Assign)] - SKNodeFocusBehavior FocusBehavior { get; set; } + [NoMac] + [MacCatalyst (13, 1)] + [Export ("focusBehavior", ArgumentSemantic.Assign)] + SKNodeFocusBehavior FocusBehavior { get; set; } - [Export ("parent")] - [NullAllowed] - SKNode Parent { get; } + [Export ("parent")] + [NullAllowed] + SKNode Parent { get; } - [Export ("children")] - SKNode [] Children { get; } + [Export ("children")] + SKNode [] Children { get; } - [NullAllowed] // by default this property is null - [Export ("name", ArgumentSemantic.Copy)] - string Name { get; set; } + [NullAllowed] // by default this property is null + [Export ("name", ArgumentSemantic.Copy)] + string Name { get; set; } - [Export ("scene")] - [NullAllowed] - SKScene Scene { get; } + [Export ("scene")] + [NullAllowed] + SKScene Scene { get; } - [Export ("physicsBody", ArgumentSemantic.Retain), NullAllowed] - SKPhysicsBody PhysicsBody { get; set; } + [Export ("physicsBody", ArgumentSemantic.Retain), NullAllowed] + SKPhysicsBody PhysicsBody { get; set; } - [NullAllowed] // by default this property is null - [Export ("userData", ArgumentSemantic.Retain)] - NSMutableDictionary UserData { get; set; } + [NullAllowed] // by default this property is null + [Export ("userData", ArgumentSemantic.Retain)] + NSMutableDictionary UserData { get; set; } - [Export ("setScale:")] - void SetScale (nfloat scale); + [Export ("setScale:")] + void SetScale (nfloat scale); - [Export ("addChild:")] - [PostGet ("Children")] - void AddChild (SKNode node); + [Export ("addChild:")] + [PostGet ("Children")] + void AddChild (SKNode node); - [Export ("insertChild:atIndex:")] - [PostGet ("Children")] - void InsertChild (SKNode node, nint index); + [Export ("insertChild:atIndex:")] + [PostGet ("Children")] + void InsertChild (SKNode node, nint index); - [Export ("removeChildrenInArray:")] - [PostGet ("Children")] - void RemoveChildren (SKNode [] nodes); + [Export ("removeChildrenInArray:")] + [PostGet ("Children")] + void RemoveChildren (SKNode [] nodes); - [Export ("removeAllChildren")] - [PostGet ("Children")] - void RemoveAllChildren (); + [Export ("removeAllChildren")] + [PostGet ("Children")] + void RemoveAllChildren (); - [Export ("removeFromParent")] - void RemoveFromParent (); + [Export ("removeFromParent")] + void RemoveFromParent (); - [Export ("childNodeWithName:")] - [return: NullAllowed] - SKNode GetChildNode (string name); + [Export ("childNodeWithName:")] + [return: NullAllowed] + SKNode GetChildNode (string name); - [Export ("enumerateChildNodesWithName:usingBlock:")] - void EnumerateChildNodes (string name, SKNodeChildEnumeratorHandler enumerationHandler); + [Export ("enumerateChildNodesWithName:usingBlock:")] + void EnumerateChildNodes (string name, SKNodeChildEnumeratorHandler enumerationHandler); - [Export ("runAction:")] - void RunAction (SKAction action); + [Export ("runAction:")] + void RunAction (SKAction action); - [Async] - [Export ("runAction:completion:")] - void RunAction (SKAction action, Action completionHandler); + [Async] + [Export ("runAction:completion:")] + void RunAction (SKAction action, Action completionHandler); - [Export ("runAction:withKey:")] - void RunAction (SKAction action, string key); + [Export ("runAction:withKey:")] + void RunAction (SKAction action, string key); - [Export ("hasActions")] - bool HasActions { get; } + [Export ("hasActions")] + bool HasActions { get; } - [Export ("actionForKey:")] - [return: NullAllowed] - SKAction GetActionForKey (string key); + [Export ("actionForKey:")] + [return: NullAllowed] + SKAction GetActionForKey (string key); - [Export ("removeActionForKey:")] - void RemoveActionForKey (string key); + [Export ("removeActionForKey:")] + void RemoveActionForKey (string key); - [Export ("removeAllActions")] - void RemoveAllActions (); + [Export ("removeAllActions")] + void RemoveAllActions (); - [Export ("containsPoint:")] - bool ContainsPoint (CGPoint point); + [Export ("containsPoint:")] + bool ContainsPoint (CGPoint point); - [Export ("nodeAtPoint:")] - SKNode GetNodeAtPoint (CGPoint point); + [Export ("nodeAtPoint:")] + SKNode GetNodeAtPoint (CGPoint point); - [Export ("nodesAtPoint:")] - SKNode [] GetNodesAtPoint (CGPoint point); + [Export ("nodesAtPoint:")] + SKNode [] GetNodesAtPoint (CGPoint point); - [Export ("convertPoint:fromNode:")] - CGPoint ConvertPointFromNode (CGPoint point, SKNode sourceNode); + [Export ("convertPoint:fromNode:")] + CGPoint ConvertPointFromNode (CGPoint point, SKNode sourceNode); - [Export ("convertPoint:toNode:")] - CGPoint ConvertPointToNode (CGPoint point, SKNode sourceNode); + [Export ("convertPoint:toNode:")] + CGPoint ConvertPointToNode (CGPoint point, SKNode sourceNode); - [Export ("intersectsNode:")] - bool IntersectsNode (SKNode node); + [Export ("intersectsNode:")] + bool IntersectsNode (SKNode node); - [MacCatalyst (13, 1)] - [Export ("isEqualToNode:")] - bool IsEqual (SKNode node); + [MacCatalyst (13, 1)] + [Export ("isEqualToNode:")] + bool IsEqual (SKNode node); - [Export ("inParentHierarchy:")] - bool InParentHierarchy (SKNode node); + [Export ("inParentHierarchy:")] + bool InParentHierarchy (SKNode node); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("reachConstraints", ArgumentSemantic.Copy)] - SKReachConstraints ReachConstraints { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("reachConstraints", ArgumentSemantic.Copy)] + SKReachConstraints ReachConstraints { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("constraints", ArgumentSemantic.Copy)] - SKConstraint [] Constraints { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("constraints", ArgumentSemantic.Copy)] + SKConstraint [] Constraints { get; set; } + + [MacCatalyst (13, 1)] + [Export ("objectForKeyedSubscript:")] + SKNode GetObjectsMatching (string nameExpression); + + [MacCatalyst (13, 1)] + [Export ("moveToParent:")] + void MoveToParent (SKNode parent); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodeBounds:")] + GKPolygonObstacle [] ObstaclesFromNodeBounds (SKNode [] nodes); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodePhysicsBodies:")] + GKPolygonObstacle [] ObstaclesFromNodePhysicsBodies (SKNode [] nodes); + + // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromSpriteTextures:accuracy:")] + GKPolygonObstacle [] ObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); + + // Extensions from GameplayKit, inlined to avoid ugly static extension syntax + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromSpriteTextures:accuracy:")] + GKPolygonObstacle [] GetObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); + + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodeBounds:")] + GKPolygonObstacle [] GetObstaclesFromNodeBounds (SKNode [] nodes); + + [MacCatalyst (13, 1)] + [Static] + [Export ("obstaclesFromNodePhysicsBodies:")] + GKPolygonObstacle [] GetObstaclesFromNodePhysicsBodies (SKNode [] nodes); + } - [MacCatalyst (13, 1)] - [Export ("objectForKeyedSubscript:")] - SKNode GetObjectsMatching (string nameExpression); + [NoiOS] + [NoTV] + [NoMacCatalyst] + [Category, BaseType (typeof (NSEvent))] + partial interface SKNodeEvent_NSEvent { - [MacCatalyst (13, 1)] - [Export ("moveToParent:")] - void MoveToParent (SKNode parent); + [Export ("locationInNode:")] + CGPoint LocationInNode (SKNode node); + } - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 + /// Extension methods for that aide with conversion to Sprite Kit coordinates. + [NoMac] [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodeBounds:")] - GKPolygonObstacle [] ObstaclesFromNodeBounds (SKNode [] nodes); + [Category, BaseType (typeof (UITouch))] + partial interface SKNodeTouches_UITouch { - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodePhysicsBodies:")] - GKPolygonObstacle [] ObstaclesFromNodePhysicsBodies (SKNode [] nodes); + [Export ("locationInNode:")] + CGPoint LocationInNode (SKNode node); - // Moved from SpriteKit to GameplayKit header in iOS 10 beta 1 - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromSpriteTextures:accuracy:")] - GKPolygonObstacle [] ObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); - -#if !NET - [Deprecated (PlatformName.iOS, 10, 0, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] - [Deprecated (PlatformName.MacOSX, 10, 12, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } - - [Deprecated (PlatformName.iOS, 10, 0, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] - [Deprecated (PlatformName.MacOSX, 10, 12, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); - - [Deprecated (PlatformName.iOS, 10, 0, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] - [Deprecated (PlatformName.MacOSX, 10, 12, message: "Attributes are only available for node classes supporting SKShader (see SKSpriteNode etc.).")] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -#endif + [Export ("previousLocationInNode:")] + CGPoint PreviousLocationInNode (SKNode node); + } - // Extensions from GameplayKit, inlined to avoid ugly static extension syntax + /// An that applies a Core Graphics to its output. + /// + /// Application developers should ensure that is . + /// Note that is a subclass of . + /// + /// Apple documentation for SKEffectNode [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromSpriteTextures:accuracy:")] - GKPolygonObstacle [] GetObstaclesFromSpriteTextures (SKNode [] sprites, float accuracy); + [BaseType (typeof (SKNode))] + partial interface SKEffectNode : SKWarpable { - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodeBounds:")] - GKPolygonObstacle [] GetObstaclesFromNodeBounds (SKNode [] nodes); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("filter", ArgumentSemantic.Retain)] + CIFilter Filter { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("obstaclesFromNodePhysicsBodies:")] - GKPolygonObstacle [] GetObstaclesFromNodePhysicsBodies (SKNode [] nodes); -} + [Export ("shouldCenterFilter")] + bool ShouldCenterFilter { get; set; } -[NoiOS] -[NoTV] -[NoMacCatalyst] -[Category, BaseType (typeof (NSEvent))] -partial interface SKNodeEvent_NSEvent { + [Export ("shouldEnableEffects")] + bool ShouldEnableEffects { get; set; } - [Export ("locationInNode:")] - CGPoint LocationInNode (SKNode node); -} + [Export ("shouldRasterize")] + bool ShouldRasterize { get; set; } -/// Extension methods for that aide with conversion to Sprite Kit coordinates. -[NoMac] -[MacCatalyst (13, 1)] -[Category, BaseType (typeof (UITouch))] -partial interface SKNodeTouches_UITouch { + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [Export ("locationInNode:")] - CGPoint LocationInNode (SKNode node); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - [Export ("previousLocationInNode:")] - CGPoint PreviousLocationInNode (SKNode node); -} + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } -/// An that applies a Core Graphics to its output. -/// -/// Application developers should ensure that is . -/// Note that is a subclass of . -/// -/// Apple documentation for SKEffectNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKEffectNode : SKWarpable { + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("filter", ArgumentSemantic.Retain)] - CIFilter Filter { get; set; } + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } - [Export ("shouldCenterFilter")] - bool ShouldCenterFilter { get; set; } + /// A method that derives a force by applying the physics of a field to a body that is within the field. + delegate Vector3 SKFieldForceEvaluator (/* vector_float3 */ Vector4 position, /* vector_float3 */ Vector4 velocity, float /* float, not CGFloat */ mass, float /* float, not CGFloat */ charge, double time); - [Export ("shouldEnableEffects")] - bool ShouldEnableEffects { get; set; } + /// Applies physics effects within a portion of a scene. + /// + /// Apple documentation for SKFieldNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + interface SKFieldNode { + [Export ("region", ArgumentSemantic.Retain)] + [NullAllowed] + SKRegion Region { get; set; } - [Export ("shouldRasterize")] - bool ShouldRasterize { get; set; } + [Export ("strength")] + float Strength { get; set; } /* float, not CGFloat */ - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [Export ("falloff")] + float Falloff { get; set; } /* float, not CGFloat */ - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [Export ("minimumRadius")] - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + float MinimumRadius { get; set; } /* float, not CGFloat */ - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [Export ("enabled")] + bool Enabled { [Bind ("isEnabled")] get; set; } - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} + [Export ("exclusive")] + bool Exclusive { [Bind ("isExclusive")] get; set; } -/// A method that derives a force by applying the physics of a field to a body that is within the field. -delegate Vector3 SKFieldForceEvaluator (/* vector_float3 */ Vector4 position, /* vector_float3 */ Vector4 velocity, float /* float, not CGFloat */ mass, float /* float, not CGFloat */ charge, double time); + [Export ("categoryBitMask")] + uint CategoryBitMask { get; set; } /* uint32_t */ -/// Applies physics effects within a portion of a scene. -/// -/// Apple documentation for SKFieldNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKFieldNode { - [Export ("region", ArgumentSemantic.Retain)] - [NullAllowed] - SKRegion Region { get; set; } + [Export ("direction")] + /* This was typed as Vector4 since sizeof the native type (vector_float3) = 16 */ + Vector4 Direction { + [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] + set; + } - [Export ("strength")] - float Strength { get; set; } /* float, not CGFloat */ + [Export ("smoothness")] + float Smoothness { get; set; } /* float, not CGFloat */ - [Export ("falloff")] - float Falloff { get; set; } /* float, not CGFloat */ + [Export ("animationSpeed")] + float AnimationSpeed { get; set; } /* float, not CGFloat */ - [Export ("minimumRadius")] + [Export ("texture", ArgumentSemantic.Retain)] + [NullAllowed] + SKTexture Texture { get; set; } - float MinimumRadius { get; set; } /* float, not CGFloat */ + [Static, Export ("dragField")] + SKFieldNode CreateDragField (); - [Export ("enabled")] - bool Enabled { [Bind ("isEnabled")] get; set; } + [Static, Export ("vortexField")] + SKFieldNode CreateVortexField (); - [Export ("exclusive")] - bool Exclusive { [Bind ("isExclusive")] get; set; } + [Static, Export ("radialGravityField")] + SKFieldNode CreateRadialGravityField (); - [Export ("categoryBitMask")] - uint CategoryBitMask { get; set; } /* uint32_t */ + [Static, Export ("linearGravityFieldWithVector:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKFieldNode CreateLinearGravityField (/* vector_float3 */ Vector4 direction); - [Export ("direction")] - /* This was typed as Vector4 since sizeof the native type (vector_float3) = 16 */ - Vector4 Direction { - [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_vector_float3__", Library = "__Internal")] - set; - } + [Static, Export ("velocityFieldWithVector:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKFieldNode CreateVelocityField (/* vector_float3 */ Vector4 direction); - [Export ("smoothness")] - float Smoothness { get; set; } /* float, not CGFloat */ + [Static, Export ("velocityFieldWithTexture:")] + SKFieldNode CreateVelocityField (SKTexture velocityTexture); - [Export ("animationSpeed")] - float AnimationSpeed { get; set; } /* float, not CGFloat */ + [Static, Export ("noiseFieldWithSmoothness:animationSpeed:")] + SKFieldNode CreateNoiseField (nfloat smoothness, nfloat speed); - [Export ("texture", ArgumentSemantic.Retain)] - [NullAllowed] - SKTexture Texture { get; set; } + [Static, Export ("turbulenceFieldWithSmoothness:animationSpeed:")] + SKFieldNode CreateTurbulenceField (nfloat smoothness, nfloat speed); - [Static, Export ("dragField")] - SKFieldNode CreateDragField (); + [Static, Export ("springField")] + SKFieldNode CreateSpringField (); - [Static, Export ("vortexField")] - SKFieldNode CreateVortexField (); + [Static, Export ("electricField")] + SKFieldNode CreateElectricField (); - [Static, Export ("radialGravityField")] - SKFieldNode CreateRadialGravityField (); + [Static, Export ("magneticField")] + SKFieldNode CreateMagneticField (); - [Static, Export ("linearGravityFieldWithVector:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKFieldNode CreateLinearGravityField (/* vector_float3 */ Vector4 direction); + [Static, Export ("customFieldWithEvaluationBlock:")] + SKFieldNode CreateCustomField (SKFieldForceEvaluator evaluator); + } - [Static, Export ("velocityFieldWithVector:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKFieldNode CreateVelocityField (/* vector_float3 */ Vector4 direction); + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (SKEffectNode))] + interface SKScene + : GKSceneRootNodeType { + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [Static, Export ("velocityFieldWithTexture:")] - SKFieldNode CreateVelocityField (SKTexture velocityTexture); + [Static, Export ("sceneWithSize:")] + SKScene FromSize (CGSize size); - [Static, Export ("noiseFieldWithSmoothness:animationSpeed:")] - SKFieldNode CreateNoiseField (nfloat smoothness, nfloat speed); + [MacCatalyst (13, 1)] + [Export ("sceneDidLoad")] + void SceneDidLoad (); - [Static, Export ("turbulenceFieldWithSmoothness:animationSpeed:")] - SKFieldNode CreateTurbulenceField (nfloat smoothness, nfloat speed); + [Export ("size")] + CGSize Size { get; set; } - [Static, Export ("springField")] - SKFieldNode CreateSpringField (); + [Export ("scaleMode")] + SKSceneScaleMode ScaleMode { get; set; } - [Static, Export ("electricField")] - SKFieldNode CreateElectricField (); + [Export ("backgroundColor", ArgumentSemantic.Retain)] + UIColor BackgroundColor { get; set; } - [Static, Export ("magneticField")] - SKFieldNode CreateMagneticField (); + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } - [Static, Export ("customFieldWithEvaluationBlock:")] - SKFieldNode CreateCustomField (SKFieldForceEvaluator evaluator); -} + [Export ("physicsWorld")] + SKPhysicsWorld PhysicsWorld { get; } -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (SKEffectNode))] -interface SKScene - : GKSceneRootNodeType { - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [MacCatalyst (13, 1)] + [Export ("convertPointFromView:")] + CGPoint ConvertPointFromView (CGPoint point); - [Static, Export ("sceneWithSize:")] - SKScene FromSize (CGSize size); + [MacCatalyst (13, 1)] + [Export ("convertPointToView:")] + CGPoint ConvertPointToView (CGPoint point); - [MacCatalyst (13, 1)] - [Export ("sceneDidLoad")] - void SceneDidLoad (); + [MacCatalyst (13, 1)] + [Export ("view", ArgumentSemantic.Weak)] + [NullAllowed] + SKView View { get; } - [Export ("size")] - CGSize Size { get; set; } + [Export ("update:")] + void Update (double currentTime); - [Export ("scaleMode")] - SKSceneScaleMode ScaleMode { get; set; } + [Export ("didEvaluateActions")] + void DidEvaluateActions (); - [Export ("backgroundColor", ArgumentSemantic.Retain)] - UIColor BackgroundColor { get; set; } + [Export ("didSimulatePhysics")] + void DidSimulatePhysics (); - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } + [MacCatalyst (13, 1)] + [Export ("didMoveToView:")] + void DidMoveToView (SKView view); - [Export ("physicsWorld")] - SKPhysicsWorld PhysicsWorld { get; } + [MacCatalyst (13, 1)] + [Export ("willMoveFromView:")] + void WillMoveFromView (SKView view); - [MacCatalyst (13, 1)] - [Export ("convertPointFromView:")] - CGPoint ConvertPointFromView (CGPoint point); + [Export ("didChangeSize:")] + void DidChangeSize (CGSize oldSize); - [MacCatalyst (13, 1)] - [Export ("convertPointToView:")] - CGPoint ConvertPointToView (CGPoint point); + [MacCatalyst (13, 1)] + [Export ("didApplyConstraints")] + void DidApplyConstraints (); - [MacCatalyst (13, 1)] - [Export ("view", ArgumentSemantic.Weak)] - [NullAllowed] - SKView View { get; } + [MacCatalyst (13, 1)] + [Export ("didFinishUpdate")] + void DidFinishUpdate (); - [Export ("update:")] - void Update (double currentTime); + [MacCatalyst (13, 1)] + [Export ("delegate", ArgumentSemantic.Weak), NullAllowed] + NSObject WeakDelegate { get; set; } - [Export ("didEvaluateActions")] - void DidEvaluateActions (); + [MacCatalyst (13, 1)] + [Wrap ("WeakDelegate")] + ISKSceneDelegate Delegate { get; set; } - [Export ("didSimulatePhysics")] - void DidSimulatePhysics (); + [MacCatalyst (13, 1)] + [Export ("audioEngine", ArgumentSemantic.Retain)] + AVAudioEngine AudioEngine { get; } - [MacCatalyst (13, 1)] - [Export ("didMoveToView:")] - void DidMoveToView (SKView view); + [MacCatalyst (13, 1)] + [NullAllowed, Export ("camera", ArgumentSemantic.Weak)] + SKCameraNode Camera { get; set; } - [MacCatalyst (13, 1)] - [Export ("willMoveFromView:")] - void WillMoveFromView (SKView view); - - [Export ("didChangeSize:")] - void DidChangeSize (CGSize oldSize); + [MacCatalyst (13, 1)] + [NullAllowed, Export ("listener", ArgumentSemantic.Weak)] + SKNode Listener { get; set; } + } - [MacCatalyst (13, 1)] - [Export ("didApplyConstraints")] - void DidApplyConstraints (); + /// Interface representing the required methods (if any) of the protocol . + /// + /// This interface contains the required methods (if any) from the protocol defined by . + /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. + /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. + /// + interface ISKSceneDelegate { } + /// Delegate object for SKScene objects. Provides methods relating to animation events. + /// + /// Apple documentation for SKSceneDelegate [MacCatalyst (13, 1)] - [Export ("didFinishUpdate")] - void DidFinishUpdate (); + [Protocol, Model] + [BaseType (typeof (NSObject))] + interface SKSceneDelegate { + [Export ("update:forScene:")] + void Update (double currentTime, SKScene scene); - [MacCatalyst (13, 1)] - [Export ("delegate", ArgumentSemantic.Weak), NullAllowed] - NSObject WeakDelegate { get; set; } + [Export ("didEvaluateActionsForScene:")] + void DidEvaluateActions (SKScene scene); - [MacCatalyst (13, 1)] - [Wrap ("WeakDelegate")] - ISKSceneDelegate Delegate { get; set; } + [Export ("didSimulatePhysicsForScene:")] + void DidSimulatePhysics (SKScene scene); - [MacCatalyst (13, 1)] - [Export ("audioEngine", ArgumentSemantic.Retain)] - AVAudioEngine AudioEngine { get; } + [Export ("didApplyConstraintsForScene:")] + void DidApplyConstraints (SKScene scene); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("camera", ArgumentSemantic.Weak)] - SKCameraNode Camera { get; set; } + [Export ("didFinishUpdateForScene:")] + void DidFinishUpdate (SKScene scene); + } + /// An OpenGL ES fragment shader. + /// + /// Apple documentation for SKShader [MacCatalyst (13, 1)] - [NullAllowed, Export ("listener", ArgumentSemantic.Weak)] - SKNode Listener { get; set; } -} + [BaseType (typeof (NSObject))] + interface SKShader : NSCopying, NSSecureCoding { + [Export ("initWithSource:")] + NativeHandle Constructor (string shaderSourceCode); -/// Interface representing the required methods (if any) of the protocol . -/// -/// This interface contains the required methods (if any) from the protocol defined by . -/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. -/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. -/// -interface ISKSceneDelegate { } - -/// Delegate object for SKScene objects. Provides methods relating to animation events. -/// -/// Apple documentation for SKSceneDelegate -[MacCatalyst (13, 1)] -[Protocol, Model] -[BaseType (typeof (NSObject))] -interface SKSceneDelegate { - [Export ("update:forScene:")] - void Update (double currentTime, SKScene scene); - - [Export ("didEvaluateActionsForScene:")] - void DidEvaluateActions (SKScene scene); - - [Export ("didSimulatePhysicsForScene:")] - void DidSimulatePhysics (SKScene scene); - - [Export ("didApplyConstraintsForScene:")] - void DidApplyConstraints (SKScene scene); - - [Export ("didFinishUpdateForScene:")] - void DidFinishUpdate (SKScene scene); -} - -/// An OpenGL ES fragment shader. -/// -/// Apple documentation for SKShader -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKShader : NSCopying, NSSecureCoding { - [Export ("initWithSource:")] - NativeHandle Constructor (string shaderSourceCode); + [Export ("initWithSource:uniforms:")] + NativeHandle Constructor (string sharedSourceCode, SKUniform [] uniforms); - [Export ("initWithSource:uniforms:")] - NativeHandle Constructor (string sharedSourceCode, SKUniform [] uniforms); + [NullAllowed] // by default this property is null + [Export ("source")] + string Source { get; set; } - [NullAllowed] // by default this property is null - [Export ("source")] - string Source { get; set; } + // @property (copy) NSArray * uniforms; + [Export ("uniforms", ArgumentSemantic.Copy)] + SKUniform [] Uniforms { get; set; } - // @property (copy) NSArray * uniforms; - [Export ("uniforms", ArgumentSemantic.Copy)] - SKUniform [] Uniforms { get; set; } + // @required + (instancetype)shader; + [Static, Export ("shader")] + SKShader Create (); - // @required + (instancetype)shader; - [Static, Export ("shader")] - SKShader Create (); + [Static, Export ("shaderWithSource:")] + SKShader FromShaderSourceCode (string source); - [Static, Export ("shaderWithSource:")] - SKShader FromShaderSourceCode (string source); + [Static, Export ("shaderWithSource:uniforms:")] + SKShader FromShaderSourceCode (string source, SKUniform [] uniforms); - [Static, Export ("shaderWithSource:uniforms:")] - SKShader FromShaderSourceCode (string source, SKUniform [] uniforms); + [Static, Export ("shaderWithFileNamed:")] + SKShader FromFile (string name); - [Static, Export ("shaderWithFileNamed:")] - SKShader FromFile (string name); + [Export ("addUniform:")] + void AddUniform (SKUniform uniform); - [Export ("addUniform:")] - void AddUniform (SKUniform uniform); + [Export ("uniformNamed:")] + [return: NullAllowed] + SKUniform GetUniform (string uniformName); - [Export ("uniformNamed:")] - [return: NullAllowed] - SKUniform GetUniform (string uniformName); + [Export ("removeUniformNamed:")] + void RemoveUniform (string uniforName); - [Export ("removeUniformNamed:")] - void RemoveUniform (string uniforName); + [MacCatalyst (13, 1)] + [Export ("attributes", ArgumentSemantic.Copy)] + SKAttribute [] Attributes { get; set; } + } + /// A that displays a textured, colored sprite. + /// + /// Apple documentation for SKSpriteNode [MacCatalyst (13, 1)] - [Export ("attributes", ArgumentSemantic.Copy)] - SKAttribute [] Attributes { get; set; } -} + [BaseType (typeof (SKNode))] + partial interface SKSpriteNode : SKWarpable { -/// A that displays a textured, colored sprite. -/// -/// Apple documentation for SKSpriteNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKSpriteNode : SKWarpable { + [Static, Export ("spriteNodeWithTexture:size:")] + SKSpriteNode FromTexture ([NullAllowed] SKTexture texture, CGSize size); - [Static, Export ("spriteNodeWithTexture:size:")] - SKSpriteNode FromTexture ([NullAllowed] SKTexture texture, CGSize size); + [Static, Export ("spriteNodeWithTexture:")] + SKSpriteNode FromTexture ([NullAllowed] SKTexture texture); - [Static, Export ("spriteNodeWithTexture:")] - SKSpriteNode FromTexture ([NullAllowed] SKTexture texture); + [Static, Export ("spriteNodeWithImageNamed:")] + SKSpriteNode FromImageNamed (string name); - [Static, Export ("spriteNodeWithImageNamed:")] - SKSpriteNode FromImageNamed (string name); + [Static, Export ("spriteNodeWithColor:size:")] + SKSpriteNode FromColor (UIColor color, CGSize size); - [Static, Export ("spriteNodeWithColor:size:")] - SKSpriteNode FromColor (UIColor color, CGSize size); + [DesignatedInitializer] + [Export ("initWithTexture:color:size:")] + NativeHandle Constructor ([NullAllowed] SKTexture texture, UIColor color, CGSize size); - [DesignatedInitializer] - [Export ("initWithTexture:color:size:")] - NativeHandle Constructor ([NullAllowed] SKTexture texture, UIColor color, CGSize size); + [Export ("initWithTexture:")] + NativeHandle Constructor ([NullAllowed] SKTexture texture); - [Export ("initWithTexture:")] - NativeHandle Constructor ([NullAllowed] SKTexture texture); + // can't be null -> crash + [Export ("initWithImageNamed:")] + NativeHandle Constructor (string name); - // can't be null -> crash - [Export ("initWithImageNamed:")] - NativeHandle Constructor (string name); + [Export ("initWithColor:size:")] + NativeHandle Constructor (UIColor color, CGSize size); - [Export ("initWithColor:size:")] - NativeHandle Constructor (UIColor color, CGSize size); + [Export ("texture", ArgumentSemantic.Retain)] + [NullAllowed] + SKTexture Texture { get; set; } - [Export ("texture", ArgumentSemantic.Retain)] - [NullAllowed] - SKTexture Texture { get; set; } + [Export ("centerRect")] + CGRect CenterRect { get; set; } - [Export ("centerRect")] - CGRect CenterRect { get; set; } + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + [Export ("color", ArgumentSemantic.Retain)] + [NullAllowed] // it's actually null-resetable (see unit tests) + UIColor Color { get; set; } - [Export ("color", ArgumentSemantic.Retain)] - [NullAllowed] // it's actually null-resetable (see unit tests) - UIColor Color { get; set; } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } + [Export ("size")] + CGSize Size { get; set; } - [Export ("size")] - CGSize Size { get; set; } + // + // iOS 8 + // - // - // iOS 8 - // + [MacCatalyst (13, 1)] + [Static, Export ("spriteNodeWithTexture:normalMap:")] + SKSpriteNode Create ([NullAllowed] SKTexture texture, [NullAllowed] SKTexture normalMap); - [MacCatalyst (13, 1)] - [Static, Export ("spriteNodeWithTexture:normalMap:")] - SKSpriteNode Create ([NullAllowed] SKTexture texture, [NullAllowed] SKTexture normalMap); + [MacCatalyst (13, 1)] + [Static, Export ("spriteNodeWithImageNamed:normalMapped:")] + SKSpriteNode Create (string imageName, bool generateNormalMap); - [MacCatalyst (13, 1)] - [Static, Export ("spriteNodeWithImageNamed:normalMapped:")] - SKSpriteNode Create (string imageName, bool generateNormalMap); + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("normalTexture", ArgumentSemantic.Retain)] + SKTexture NormalTexture { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("normalTexture", ArgumentSemantic.Retain)] - SKTexture NormalTexture { get; set; } + [MacCatalyst (13, 1)] + [Export ("lightingBitMask")] + uint LightingBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("lightingBitMask")] - uint LightingBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("shadowCastBitMask")] + uint ShadowCastBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("shadowCastBitMask")] - uint ShadowCastBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("shadowedBitMask")] + uint ShadowedBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Export ("shadowedBitMask")] - uint ShadowedBitMask { get; set; } /* uint32_t */ + [MacCatalyst (13, 1)] + [Export ("shader", ArgumentSemantic.Retain), NullAllowed] + SKShader Shader { get; set; } - [MacCatalyst (13, 1)] - [Export ("shader", ArgumentSemantic.Retain), NullAllowed] - SKShader Shader { get; set; } + [MacCatalyst (13, 1)] + [Export ("scaleToSize:")] + void ScaleTo (CGSize size); - [MacCatalyst (13, 1)] - [Export ("scaleToSize:")] - void ScaleTo (CGSize size); + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } + /// An object that can control the properties of particles emitted by a . + /// + /// The total time of the sequence is normalized from 0.0 to 1.0. + /// + /// + /// + /// + /// + /// Apple documentation for SKKeyframeSequence [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} - -/// An object that can control the properties of particles emitted by a . -/// -/// The total time of the sequence is normalized from 0.0 to 1.0. -/// -/// -/// -/// -/// -/// Apple documentation for SKKeyframeSequence -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -partial interface SKKeyframeSequence : NSSecureCoding, NSCopying { - - [DesignatedInitializer] - [Export ("initWithKeyframeValues:times:")] - [Internal] - NativeHandle Constructor ([NullAllowed] NSObject [] values, [NullAllowed] NSArray times); + [BaseType (typeof (NSObject))] + partial interface SKKeyframeSequence : NSSecureCoding, NSCopying { - [Export ("initWithCapacity:")] - NativeHandle Constructor (nuint numItems); - - [Export ("count")] - nuint Count { get; } + [DesignatedInitializer] + [Export ("initWithKeyframeValues:times:")] + [Internal] + NativeHandle Constructor ([NullAllowed] NSObject [] values, [NullAllowed] NSArray times); - [Export ("addKeyframeValue:time:")] - void AddKeyframeValue (NSObject value, nfloat time); + [Export ("initWithCapacity:")] + NativeHandle Constructor (nuint numItems); - [Export ("removeLastKeyframe")] - void RemoveLastKeyframe (); + [Export ("count")] + nuint Count { get; } - [Export ("removeKeyframeAtIndex:")] - void RemoveKeyframe (nuint index); + [Export ("addKeyframeValue:time:")] + void AddKeyframeValue (NSObject value, nfloat time); - [Export ("setKeyframeValue:forIndex:")] - void SetKeyframeValue (NSObject value, nuint index); + [Export ("removeLastKeyframe")] + void RemoveLastKeyframe (); - [Export ("setKeyframeTime:forIndex:")] - void SetKeyframeTime (nfloat time, nuint index); + [Export ("removeKeyframeAtIndex:")] + void RemoveKeyframe (nuint index); - [Export ("setKeyframeValue:time:forIndex:")] - void SetKeyframeValue (NSObject value, nfloat time, nuint index); + [Export ("setKeyframeValue:forIndex:")] + void SetKeyframeValue (NSObject value, nuint index); - [Export ("getKeyframeValueForIndex:")] - NSObject GetKeyframeValue (nuint index); + [Export ("setKeyframeTime:forIndex:")] + void SetKeyframeTime (nfloat time, nuint index); - [Export ("getKeyframeTimeForIndex:")] - nfloat GetKeyframeTime (nuint index); + [Export ("setKeyframeValue:time:forIndex:")] + void SetKeyframeValue (NSObject value, nfloat time, nuint index); - [Export ("sampleAtTime:")] - [return: NullAllowed] - NSObject SampleAtTime (nfloat time); + [Export ("getKeyframeValueForIndex:")] + NSObject GetKeyframeValue (nuint index); - [Export ("interpolationMode")] - SKInterpolationMode InterpolationMode { get; set; } + [Export ("getKeyframeTimeForIndex:")] + nfloat GetKeyframeTime (nuint index); - [Export ("repeatMode")] - SKRepeatMode RepeatMode { get; set; } -} + [Export ("sampleAtTime:")] + [return: NullAllowed] + NSObject SampleAtTime (nfloat time); -/// A that produces colored and textured particles. -/// -/// Emitted particles are not directly accessible to the application developer; their behavior can be controlled either via the creation parameters configurable in or by a . -/// -/// Apple documentation for SKEmitterNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKEmitterNode { + [Export ("interpolationMode")] + SKInterpolationMode InterpolationMode { get; set; } - [Export ("advanceSimulationTime:")] - void AdvanceSimulationTime (double sec); + [Export ("repeatMode")] + SKRepeatMode RepeatMode { get; set; } + } - [Export ("resetSimulation")] - void ResetSimulation (); + /// A that produces colored and textured particles. + /// + /// Emitted particles are not directly accessible to the application developer; their behavior can be controlled either via the creation parameters configurable in or by a . + /// + /// Apple documentation for SKEmitterNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + partial interface SKEmitterNode { - [NullAllowed] // by default this property is null - [Export ("particleTexture", ArgumentSemantic.Retain)] - SKTexture ParticleTexture { get; set; } + [Export ("advanceSimulationTime:")] + void AdvanceSimulationTime (double sec); - [Export ("particleZPosition")] - nfloat ParticleZPosition { get; set; } + [Export ("resetSimulation")] + void ResetSimulation (); - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 8, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("particleZPositionRange")] - nfloat ParticleZPositionRange { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleTexture", ArgumentSemantic.Retain)] + SKTexture ParticleTexture { get; set; } - [Export ("particleBlendMode")] - SKBlendMode ParticleBlendMode { get; set; } + [Export ("particleZPosition")] + nfloat ParticleZPosition { get; set; } - [Export ("particleColor", ArgumentSemantic.Retain)] - UIColor ParticleColor { get; set; } + [Deprecated (PlatformName.iOS, 8, 0)] + [Deprecated (PlatformName.TvOS, 8, 0)] + [Deprecated (PlatformName.MacOSX, 10, 10)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("particleZPositionRange")] + nfloat ParticleZPositionRange { get; set; } - [Export ("particleColorRedRange")] - nfloat ParticleColorRedRange { get; set; } + [Export ("particleBlendMode")] + SKBlendMode ParticleBlendMode { get; set; } - [Export ("particleColorGreenRange")] - nfloat ParticleColorGreenRange { get; set; } + [Export ("particleColor", ArgumentSemantic.Retain)] + UIColor ParticleColor { get; set; } - [Export ("particleColorBlueRange")] - nfloat ParticleColorBlueRange { get; set; } + [Export ("particleColorRedRange")] + nfloat ParticleColorRedRange { get; set; } - [Export ("particleColorAlphaRange")] - nfloat ParticleColorAlphaRange { get; set; } + [Export ("particleColorGreenRange")] + nfloat ParticleColorGreenRange { get; set; } - [Export ("particleColorRedSpeed")] - nfloat ParticleColorRedSpeed { get; set; } + [Export ("particleColorBlueRange")] + nfloat ParticleColorBlueRange { get; set; } - [Export ("particleColorGreenSpeed")] - nfloat ParticleColorGreenSpeed { get; set; } + [Export ("particleColorAlphaRange")] + nfloat ParticleColorAlphaRange { get; set; } - [Export ("particleColorBlueSpeed")] - nfloat ParticleColorBlueSpeed { get; set; } + [Export ("particleColorRedSpeed")] + nfloat ParticleColorRedSpeed { get; set; } - [Export ("particleColorAlphaSpeed")] - nfloat ParticleColorAlphaSpeed { get; set; } + [Export ("particleColorGreenSpeed")] + nfloat ParticleColorGreenSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleColorSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleColorSequence { get; set; } + [Export ("particleColorBlueSpeed")] + nfloat ParticleColorBlueSpeed { get; set; } - [Export ("particleColorBlendFactor")] - nfloat ParticleColorBlendFactor { get; set; } + [Export ("particleColorAlphaSpeed")] + nfloat ParticleColorAlphaSpeed { get; set; } - [Export ("particleColorBlendFactorRange")] - nfloat ParticleColorBlendFactorRange { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleColorSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleColorSequence { get; set; } - [Export ("particleColorBlendFactorSpeed")] - nfloat ParticleColorBlendFactorSpeed { get; set; } + [Export ("particleColorBlendFactor")] + nfloat ParticleColorBlendFactor { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleColorBlendFactorSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleColorBlendFactorSequence { get; set; } + [Export ("particleColorBlendFactorRange")] + nfloat ParticleColorBlendFactorRange { get; set; } - [Export ("particlePosition")] - CGPoint ParticlePosition { get; set; } + [Export ("particleColorBlendFactorSpeed")] + nfloat ParticleColorBlendFactorSpeed { get; set; } - [Export ("particlePositionRange")] - CGVector ParticlePositionRange { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleColorBlendFactorSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleColorBlendFactorSequence { get; set; } - [Export ("particleSpeed")] - nfloat ParticleSpeed { get; set; } + [Export ("particlePosition")] + CGPoint ParticlePosition { get; set; } - [Export ("particleSpeedRange")] - nfloat ParticleSpeedRange { get; set; } + [Export ("particlePositionRange")] + CGVector ParticlePositionRange { get; set; } - [Export ("emissionAngle")] - nfloat EmissionAngle { get; set; } + [Export ("particleSpeed")] + nfloat ParticleSpeed { get; set; } - [Export ("emissionAngleRange")] - nfloat EmissionAngleRange { get; set; } + [Export ("particleSpeedRange")] + nfloat ParticleSpeedRange { get; set; } - [Export ("xAcceleration")] - nfloat XAcceleration { get; set; } + [Export ("emissionAngle")] + nfloat EmissionAngle { get; set; } - [Export ("yAcceleration")] - nfloat YAcceleration { get; set; } + [Export ("emissionAngleRange")] + nfloat EmissionAngleRange { get; set; } - [Export ("particleBirthRate")] - nfloat ParticleBirthRate { get; set; } + [Export ("xAcceleration")] + nfloat XAcceleration { get; set; } - [Export ("numParticlesToEmit")] - nuint NumParticlesToEmit { get; set; } + [Export ("yAcceleration")] + nfloat YAcceleration { get; set; } - [Export ("particleLifetime")] - nfloat ParticleLifetime { get; set; } + [Export ("particleBirthRate")] + nfloat ParticleBirthRate { get; set; } - [Export ("particleLifetimeRange")] - nfloat ParticleLifetimeRange { get; set; } + [Export ("numParticlesToEmit")] + nuint NumParticlesToEmit { get; set; } - [Export ("particleRotation")] - nfloat ParticleRotation { get; set; } + [Export ("particleLifetime")] + nfloat ParticleLifetime { get; set; } - [Export ("particleRotationRange")] - nfloat ParticleRotationRange { get; set; } + [Export ("particleLifetimeRange")] + nfloat ParticleLifetimeRange { get; set; } - [Export ("particleRotationSpeed")] - nfloat ParticleRotationSpeed { get; set; } + [Export ("particleRotation")] + nfloat ParticleRotation { get; set; } - [Export ("particleSize")] - CGSize ParticleSize { get; set; } + [Export ("particleRotationRange")] + nfloat ParticleRotationRange { get; set; } - [Export ("particleScale")] - nfloat ParticleScale { get; set; } + [Export ("particleRotationSpeed")] + nfloat ParticleRotationSpeed { get; set; } - [Export ("particleScaleRange")] - nfloat ParticleScaleRange { get; set; } + [Export ("particleSize")] + CGSize ParticleSize { get; set; } - [Export ("particleScaleSpeed")] - nfloat ParticleScaleSpeed { get; set; } + [Export ("particleScale")] + nfloat ParticleScale { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleScaleSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleScaleSequence { get; set; } + [Export ("particleScaleRange")] + nfloat ParticleScaleRange { get; set; } - [Export ("particleAlpha")] - nfloat ParticleAlpha { get; set; } + [Export ("particleScaleSpeed")] + nfloat ParticleScaleSpeed { get; set; } - [Export ("particleAlphaRange")] - nfloat ParticleAlphaRange { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleScaleSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleScaleSequence { get; set; } - [Export ("particleAlphaSpeed")] - nfloat ParticleAlphaSpeed { get; set; } + [Export ("particleAlpha")] + nfloat ParticleAlpha { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleAlphaSequence", ArgumentSemantic.Retain)] - SKKeyframeSequence ParticleAlphaSequence { get; set; } + [Export ("particleAlphaRange")] + nfloat ParticleAlphaRange { get; set; } - [NullAllowed] // by default this property is null - [Export ("particleAction", ArgumentSemantic.Copy)] - SKAction ParticleAction { get; set; } + [Export ("particleAlphaSpeed")] + nfloat ParticleAlphaSpeed { get; set; } - [NullAllowed] // by default this property is null - [Export ("targetNode", ArgumentSemantic.Weak)] - SKNode TargetNode { get; set; } + [NullAllowed] // by default this property is null + [Export ("particleAlphaSequence", ArgumentSemantic.Retain)] + SKKeyframeSequence ParticleAlphaSequence { get; set; } - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Export ("fieldBitMask")] - uint FieldBitMask { get; set; } /* uint32_t */ + [NullAllowed] // by default this property is null + [Export ("particleAction", ArgumentSemantic.Copy)] + SKAction ParticleAction { get; set; } - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 8, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("particleZPositionSpeed")] - nfloat ParticleZPositionSpeed { get; set; } + [NullAllowed] // by default this property is null + [Export ("targetNode", ArgumentSemantic.Weak)] + SKNode TargetNode { get; set; } + + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("fieldBitMask")] + uint FieldBitMask { get; set; } /* uint32_t */ + + [Deprecated (PlatformName.iOS, 8, 0)] + [Deprecated (PlatformName.TvOS, 8, 0)] + [Deprecated (PlatformName.MacOSX, 10, 10)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("particleZPositionSpeed")] + nfloat ParticleZPositionSpeed { get; set; } + + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + [MacCatalyst (13, 1)] + [Export ("particleRenderOrder", ArgumentSemantic.Assign)] + SKParticleRenderOrder ParticleRenderOrder { get; set; } - [MacCatalyst (13, 1)] - [Export ("particleRenderOrder", ArgumentSemantic.Assign)] - SKParticleRenderOrder ParticleRenderOrder { get; set; } + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } + /// A defined by a Core Graphics . + /// + /// Apple documentation for SKShapeNode [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} - -/// A defined by a Core Graphics . -/// -/// Apple documentation for SKShapeNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKShapeNode { + [BaseType (typeof (SKNode))] + partial interface SKShapeNode { - [NullAllowed] - [Export ("path")] - CGPath Path { get; set; } + [NullAllowed] + [Export ("path")] + CGPath Path { get; set; } - [Export ("strokeColor", ArgumentSemantic.Retain)] - UIColor StrokeColor { get; set; } + [Export ("strokeColor", ArgumentSemantic.Retain)] + UIColor StrokeColor { get; set; } - [Export ("fillColor", ArgumentSemantic.Retain)] - UIColor FillColor { get; set; } + [Export ("fillColor", ArgumentSemantic.Retain)] + UIColor FillColor { get; set; } - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } - [Export ("antialiased")] - bool Antialiased { [Bind ("isAntialiased")] get; set; } + [Export ("antialiased")] + bool Antialiased { [Bind ("isAntialiased")] get; set; } - [Export ("lineWidth")] - nfloat LineWidth { get; set; } + [Export ("lineWidth")] + nfloat LineWidth { get; set; } - [Export ("glowWidth")] - nfloat GlowWidth { get; set; } + [Export ("glowWidth")] + nfloat GlowWidth { get; set; } - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("fillTexture", ArgumentSemantic.Retain)] - SKTexture FillTexture { get; set; } + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("fillTexture", ArgumentSemantic.Retain)] + SKTexture FillTexture { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("fillShader", ArgumentSemantic.Retain)] - SKShader FillShader { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("fillShader", ArgumentSemantic.Retain)] + SKShader FillShader { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("strokeTexture", ArgumentSemantic.Retain)] - SKTexture StrokeTexture { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("strokeTexture", ArgumentSemantic.Retain)] + SKTexture StrokeTexture { get; set; } - [MacCatalyst (13, 1)] - [NullAllowed] // by default this property is null - [Export ("strokeShader", ArgumentSemantic.Retain)] - SKShader StrokeShader { get; set; } + [MacCatalyst (13, 1)] + [NullAllowed] // by default this property is null + [Export ("strokeShader", ArgumentSemantic.Retain)] + SKShader StrokeShader { get; set; } + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPath:")] + SKShapeNode FromPath (CGPath path); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPath:centered:")] + SKShapeNode FromPath (CGPath path, bool centered); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRect:")] + SKShapeNode FromRect (CGRect rect); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRectOfSize:")] + SKShapeNode FromRect (CGSize size); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRect:cornerRadius:")] + SKShapeNode FromRect (CGRect rect, nfloat cornerRadius); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithRectOfSize:cornerRadius:")] + SKShapeNode FromRect (CGSize size, nfloat cornerRadius); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithCircleOfRadius:")] + SKShapeNode FromCircle (nfloat radius); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithEllipseInRect:")] + SKShapeNode FromEllipse (CGRect rect); + + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithEllipseOfSize:")] + SKShapeNode FromEllipse (CGSize size); + + // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 + [Internal] + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithPoints:count:")] + SKShapeNode FromPoints (ref CGPoint points, nuint numPoints); + + // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 + [Internal] + [MacCatalyst (13, 1)] + [Static, Export ("shapeNodeWithSplinePoints:count:")] + SKShapeNode FromSplinePoints (ref CGPoint points, nuint numPoints); + + [MacCatalyst (13, 1)] + [Export ("lineCap")] + CGLineCap LineCap { get; set; } + + [MacCatalyst (13, 1)] + [Export ("lineJoin")] + CGLineJoin LineJoin { get; set; } + + [MacCatalyst (13, 1)] + [Export ("miterLimit")] + nfloat MiterLimit { get; set; } + + [MacCatalyst (13, 1)] + [Export ("lineLength")] + nfloat LineLength { get; } + + [MacCatalyst (13, 1)] + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } + + [MacCatalyst (13, 1)] + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); + + [MacCatalyst (13, 1)] + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } + /// A range of motion used with inverse kinematics. + /// + /// Apple documentation for SKReachConstraints [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPath:")] - SKShapeNode FromPath (CGPath path); + [BaseType (typeof (NSObject))] + interface SKReachConstraints : NSSecureCoding { + [DesignatedInitializer] + [Export ("initWithLowerAngleLimit:upperAngleLimit:")] + NativeHandle Constructor (nfloat lowerAngleLimit, nfloat upperAngleLimit); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPath:centered:")] - SKShapeNode FromPath (CGPath path, bool centered); + [Export ("lowerAngleLimit", ArgumentSemantic.UnsafeUnretained)] + nfloat LowerAngleLimit { get; set; } - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRect:")] - SKShapeNode FromRect (CGRect rect); + [Export ("upperAngleLimit", ArgumentSemantic.UnsafeUnretained)] + nfloat UpperAngleLimit { get; set; } + } + /// A path-defined area. Typically used for hit-testing and physics-field extents. + /// + /// Apple documentation for SKRegion [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRectOfSize:")] - SKShapeNode FromRect (CGSize size); + [BaseType (typeof (NSObject))] + interface SKRegion : NSCopying, NSSecureCoding { + [Export ("initWithRadius:")] + NativeHandle Constructor (float /* float, not CGFloat */ radius); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRect:cornerRadius:")] - SKShapeNode FromRect (CGRect rect, nfloat cornerRadius); + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithRectOfSize:cornerRadius:")] - SKShapeNode FromRect (CGSize size, nfloat cornerRadius); + [Export ("initWithPath:")] + NativeHandle Constructor (CGPath path); - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithCircleOfRadius:")] - SKShapeNode FromCircle (nfloat radius); + [Export ("path")] + [NullAllowed] + CGPath Path { get; } - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithEllipseInRect:")] - SKShapeNode FromEllipse (CGRect rect); + [Static, Export ("infiniteRegion")] + SKRegion InfiniteRegion { get; } - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithEllipseOfSize:")] - SKShapeNode FromEllipse (CGSize size); + [Export ("inverseRegion")] + SKRegion InverseRegion (); - // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 - [Internal] - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithPoints:count:")] - SKShapeNode FromPoints (ref CGPoint points, nuint numPoints); + [Export ("regionByUnionWithRegion:")] + SKRegion CreateUnion (SKRegion region); - // Hide this ugly api fixes https://bugzilla.xamarin.com/show_bug.cgi?id=39706 - [Internal] - [MacCatalyst (13, 1)] - [Static, Export ("shapeNodeWithSplinePoints:count:")] - SKShapeNode FromSplinePoints (ref CGPoint points, nuint numPoints); + [Export ("regionByDifferenceFromRegion:")] + SKRegion CreateDifference (SKRegion region); - [MacCatalyst (13, 1)] - [Export ("lineCap")] - CGLineCap LineCap { get; set; } + [Export ("regionByIntersectionWithRegion:")] + SKRegion CreateIntersection (SKRegion region); - [MacCatalyst (13, 1)] - [Export ("lineJoin")] - CGLineJoin LineJoin { get; set; } + [Export ("containsPoint:")] + bool ContainsPoint (CGPoint point); + } + /// A that displays a string. + /// + /// Apple documentation for SKLabelNode [MacCatalyst (13, 1)] - [Export ("miterLimit")] - nfloat MiterLimit { get; set; } + [BaseType (typeof (SKNode))] + partial interface SKLabelNode { - [MacCatalyst (13, 1)] - [Export ("lineLength")] - nfloat LineLength { get; } + [Static, Export ("labelNodeWithFontNamed:")] + SKLabelNode FromFont ([NullAllowed] string fontName); - [MacCatalyst (13, 1)] - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } + [Export ("initWithFontNamed:")] + NativeHandle Constructor ([NullAllowed] string fontName); - [MacCatalyst (13, 1)] - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); + [MacCatalyst (13, 1)] + [Static, Export ("labelNodeWithText:")] + SKLabelNode FromText ([NullAllowed] string text); - [MacCatalyst (13, 1)] - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} - -/// A range of motion used with inverse kinematics. -/// -/// Apple documentation for SKReachConstraints -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKReachConstraints : NSSecureCoding { - [DesignatedInitializer] - [Export ("initWithLowerAngleLimit:upperAngleLimit:")] - NativeHandle Constructor (nfloat lowerAngleLimit, nfloat upperAngleLimit); - - [Export ("lowerAngleLimit", ArgumentSemantic.UnsafeUnretained)] - nfloat LowerAngleLimit { get; set; } - - [Export ("upperAngleLimit", ArgumentSemantic.UnsafeUnretained)] - nfloat UpperAngleLimit { get; set; } -} - -/// A path-defined area. Typically used for hit-testing and physics-field extents. -/// -/// Apple documentation for SKRegion -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKRegion : NSCopying, NSSecureCoding { - [Export ("initWithRadius:")] - NativeHandle Constructor (float /* float, not CGFloat */ radius); + [MacCatalyst (13, 1)] + [Static] + [Export ("labelNodeWithAttributedText:")] + SKLabelNode FromText ([NullAllowed] NSAttributedString attributedText); - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [Export ("verticalAlignmentMode")] + SKLabelVerticalAlignmentMode VerticalAlignmentMode { get; set; } - [Export ("initWithPath:")] - NativeHandle Constructor (CGPath path); + [Export ("horizontalAlignmentMode")] + SKLabelHorizontalAlignmentMode HorizontalAlignmentMode { get; set; } - [Export ("path")] - [NullAllowed] - CGPath Path { get; } + [MacCatalyst (13, 1)] + [Export ("numberOfLines")] + nint NumberOfLines { get; set; } - [Static, Export ("infiniteRegion")] - SKRegion InfiniteRegion { get; } + [MacCatalyst (13, 1)] + [Export ("lineBreakMode", ArgumentSemantic.Assign)] + NSLineBreakMode LineBreakMode { get; set; } - [Export ("inverseRegion")] - SKRegion InverseRegion (); + [MacCatalyst (13, 1)] + [Export ("preferredMaxLayoutWidth")] + nfloat PreferredMaxLayoutWidth { get; set; } - [Export ("regionByUnionWithRegion:")] - SKRegion CreateUnion (SKRegion region); + [Export ("fontName", ArgumentSemantic.Copy)] + [NullAllowed] + string FontName { get; set; } - [Export ("regionByDifferenceFromRegion:")] - SKRegion CreateDifference (SKRegion region); + [Export ("text", ArgumentSemantic.Copy)] + [NullAllowed] // nullable in Xcode7 headers and caught by introspection tests + string Text { get; set; } - [Export ("regionByIntersectionWithRegion:")] - SKRegion CreateIntersection (SKRegion region); + [MacCatalyst (13, 1)] + [NullAllowed, Export ("attributedText", ArgumentSemantic.Copy)] + NSAttributedString AttributedText { get; set; } - [Export ("containsPoint:")] - bool ContainsPoint (CGPoint point); -} + [Export ("fontSize")] + nfloat FontSize { get; set; } -/// A that displays a string. -/// -/// Apple documentation for SKLabelNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKLabelNode { + [Export ("fontColor", ArgumentSemantic.Retain)] + [NullAllowed] + UIColor FontColor { get; set; } - [Static, Export ("labelNodeWithFontNamed:")] - SKLabelNode FromFont ([NullAllowed] string fontName); + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("initWithFontNamed:")] - NativeHandle Constructor ([NullAllowed] string fontName); + [NullAllowed] // by default this property is null + [Export ("color", ArgumentSemantic.Retain)] + UIColor Color { get; set; } - [MacCatalyst (13, 1)] - [Static, Export ("labelNodeWithText:")] - SKLabelNode FromText ([NullAllowed] string text); + [Export ("blendMode")] + SKBlendMode BlendMode { get; set; } + } + /// A node that creates a lighting effect within a scene. + /// + /// Apple documentation for SKLightNode [MacCatalyst (13, 1)] - [Static] - [Export ("labelNodeWithAttributedText:")] - SKLabelNode FromText ([NullAllowed] NSAttributedString attributedText); - - [Export ("verticalAlignmentMode")] - SKLabelVerticalAlignmentMode VerticalAlignmentMode { get; set; } - - [Export ("horizontalAlignmentMode")] - SKLabelHorizontalAlignmentMode HorizontalAlignmentMode { get; set; } + [BaseType (typeof (SKNode))] + interface SKLightNode { + [Export ("enabled")] + bool Enabled { [Bind ("isEnabled")] get; set; } - [MacCatalyst (13, 1)] - [Export ("numberOfLines")] - nint NumberOfLines { get; set; } + [Export ("lightColor")] + UIColor LightColor { get; set; } - [MacCatalyst (13, 1)] - [Export ("lineBreakMode", ArgumentSemantic.Assign)] - NSLineBreakMode LineBreakMode { get; set; } + [Export ("ambientColor")] + UIColor AmbientColor { get; set; } - [MacCatalyst (13, 1)] - [Export ("preferredMaxLayoutWidth")] - nfloat PreferredMaxLayoutWidth { get; set; } + [Export ("shadowColor")] + UIColor ShadowColor { get; set; } - [Export ("fontName", ArgumentSemantic.Copy)] - [NullAllowed] - string FontName { get; set; } + [Export ("falloff")] + nfloat Falloff { get; set; } - [Export ("text", ArgumentSemantic.Copy)] - [NullAllowed] // nullable in Xcode7 headers and caught by introspection tests - string Text { get; set; } + [Export ("categoryBitMask")] + uint CategoryBitMask { get; set; } /* uint32_t */ + } + /// A that displays video. + /// + /// Apple documentation for SKVideoNode [MacCatalyst (13, 1)] - [NullAllowed, Export ("attributedText", ArgumentSemantic.Copy)] - NSAttributedString AttributedText { get; set; } - - [Export ("fontSize")] - nfloat FontSize { get; set; } - - [Export ("fontColor", ArgumentSemantic.Retain)] - [NullAllowed] - UIColor FontColor { get; set; } - - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } - - [NullAllowed] // by default this property is null - [Export ("color", ArgumentSemantic.Retain)] - UIColor Color { get; set; } - - [Export ("blendMode")] - SKBlendMode BlendMode { get; set; } -} - -/// A node that creates a lighting effect within a scene. -/// -/// Apple documentation for SKLightNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKLightNode { - [Export ("enabled")] - bool Enabled { [Bind ("isEnabled")] get; set; } - - [Export ("lightColor")] - UIColor LightColor { get; set; } - - [Export ("ambientColor")] - UIColor AmbientColor { get; set; } - - [Export ("shadowColor")] - UIColor ShadowColor { get; set; } - - [Export ("falloff")] - nfloat Falloff { get; set; } - - [Export ("categoryBitMask")] - uint CategoryBitMask { get; set; } /* uint32_t */ -} + [BaseType (typeof (SKNode))] + partial interface SKVideoNode { + [Static, Export ("videoNodeWithAVPlayer:")] + SKVideoNode FromPlayer (AVPlayer player); -/// A that displays video. -/// -/// Apple documentation for SKVideoNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKVideoNode { - [Static, Export ("videoNodeWithAVPlayer:")] - SKVideoNode FromPlayer (AVPlayer player); + [Static, Export ("videoNodeWithVideoFileNamed:"), Internal] + SKVideoNode VideoNodeWithVideoFileNamed (string videoFile); - [Static, Export ("videoNodeWithVideoFileNamed:"), Internal] - SKVideoNode VideoNodeWithVideoFileNamed (string videoFile); + [Static, Export ("videoNodeWithFileNamed:"), Internal] + SKVideoNode VideoNodeWithFileNamed (string videoFile); - [Static, Export ("videoNodeWithFileNamed:"), Internal] - SKVideoNode VideoNodeWithFileNamed (string videoFile); + [Static, Export ("videoNodeWithVideoURL:"), Internal] + SKVideoNode VideoNodeWithVideoURL (NSUrl videoURL); - [Static, Export ("videoNodeWithVideoURL:"), Internal] - SKVideoNode VideoNodeWithVideoURL (NSUrl videoURL); + [Static, Export ("videoNodeWithURL:"), Internal] + SKVideoNode VideoNodeWithURL (NSUrl videoURL); - [Static, Export ("videoNodeWithURL:"), Internal] - SKVideoNode VideoNodeWithURL (NSUrl videoURL); + [DesignatedInitializer] + [Export ("initWithAVPlayer:")] + NativeHandle Constructor (AVPlayer player); - [DesignatedInitializer] - [Export ("initWithAVPlayer:")] - NativeHandle Constructor (AVPlayer player); + [Export ("initWithVideoFileNamed:"), Internal] + IntPtr InitWithVideoFileNamed (string videoFile); - [Export ("initWithVideoFileNamed:"), Internal] - IntPtr InitWithVideoFileNamed (string videoFile); + [Export ("initWithFileNamed:"), Internal] + IntPtr InitWithFileNamed (string videoFile); - [Export ("initWithFileNamed:"), Internal] - IntPtr InitWithFileNamed (string videoFile); + [Export ("initWithVideoURL:"), Internal] + IntPtr InitWithVideoURL (NSUrl url); - [Export ("initWithVideoURL:"), Internal] - IntPtr InitWithVideoURL (NSUrl url); + [Export ("initWithURL:"), Internal] + IntPtr InitWithURL (NSUrl url); - [Export ("initWithURL:"), Internal] - IntPtr InitWithURL (NSUrl url); + [Export ("play")] + void Play (); - [Export ("play")] - void Play (); + [Export ("pause")] + void Pause (); - [Export ("pause")] - void Pause (); + [Export ("size")] + CGSize Size { get; set; } - [Export ("size")] - CGSize Size { get; set; } + [Export ("anchorPoint")] + CGPoint AnchorPoint { get; set; } + } - [Export ("anchorPoint")] - CGPoint AnchorPoint { get; set; } -} + /// Mathematical constraint on a node's position or orientation. + /// + /// Apple documentation for SKConstraint + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKConstraint : NSSecureCoding, NSCopying { + [Export ("enabled")] + bool Enabled { get; set; } -/// Mathematical constraint on a node's position or orientation. -/// -/// Apple documentation for SKConstraint -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKConstraint : NSSecureCoding, NSCopying { - [Export ("enabled")] - bool Enabled { get; set; } + [NullAllowed] // by default this property is null + [Export ("referenceNode", ArgumentSemantic.Retain)] + SKNode ReferenceNode { get; set; } - [NullAllowed] // by default this property is null - [Export ("referenceNode", ArgumentSemantic.Retain)] - SKNode ReferenceNode { get; set; } + [Static, Export ("positionX:")] + SKConstraint CreateXRestriction (SKRange range); - [Static, Export ("positionX:")] - SKConstraint CreateXRestriction (SKRange range); + [Static, Export ("positionY:")] + SKConstraint CreateYRestriction (SKRange range); - [Static, Export ("positionY:")] - SKConstraint CreateYRestriction (SKRange range); + [Static, Export ("positionX:Y:")] + SKConstraint CreateRestriction (SKRange xRange, SKRange yRange); - [Static, Export ("positionX:Y:")] - SKConstraint CreateRestriction (SKRange xRange, SKRange yRange); + [Static, Export ("distance:toNode:")] + SKConstraint CreateDistance (SKRange range, SKNode node); - [Static, Export ("distance:toNode:")] - SKConstraint CreateDistance (SKRange range, SKNode node); + [Static, Export ("distance:toPoint:")] + SKConstraint CreateDistance (SKRange range, CGPoint point); - [Static, Export ("distance:toPoint:")] - SKConstraint CreateDistance (SKRange range, CGPoint point); + [Static, Export ("distance:toPoint:inNode:")] + SKConstraint CreateDistance (SKRange range, CGPoint point, SKNode node); - [Static, Export ("distance:toPoint:inNode:")] - SKConstraint CreateDistance (SKRange range, CGPoint point, SKNode node); + [Static, Export ("zRotation:")] + SKConstraint CreateZRotation (SKRange zRange); - [Static, Export ("zRotation:")] - SKConstraint CreateZRotation (SKRange zRange); + [Static, Export ("orientToNode:offset:")] + SKConstraint CreateOrientToNode (SKNode node, SKRange radians); - [Static, Export ("orientToNode:offset:")] - SKConstraint CreateOrientToNode (SKNode node, SKRange radians); + [Static, Export ("orientToPoint:offset:")] + SKConstraint CreateOrientToPoint (CGPoint point, SKRange radians); - [Static, Export ("orientToPoint:offset:")] - SKConstraint CreateOrientToPoint (CGPoint point, SKRange radians); + [Static, Export ("orientToPoint:inNode:offset:")] + SKConstraint CreateOrientToPoint (CGPoint point, SKNode node, SKRange radians); + } - [Static, Export ("orientToPoint:inNode:offset:")] - SKConstraint CreateOrientToPoint (CGPoint point, SKNode node, SKRange radians); -} + /// A node that masks its children's pixels. + /// + /// An masks pixels outside of the area defined by its node. Pixels that fall outside of that area are not passed up towards the root of the . + /// + /// + /// Apple documentation for SKCropNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + partial interface SKCropNode { -/// A node that masks its children's pixels. -/// -/// An masks pixels outside of the area defined by its node. Pixels that fall outside of that area are not passed up towards the root of the . -/// -/// -/// Apple documentation for SKCropNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -partial interface SKCropNode { - - [NullAllowed] // by default this property is null - [Export ("maskNode", ArgumentSemantic.Retain)] - SKNode MaskNode { get; set; } -} + [NullAllowed] // by default this property is null + [Export ("maskNode", ArgumentSemantic.Retain)] + SKNode MaskNode { get; set; } + } -/// A that displays a . -/// -/// Application developers should note the availability of debugging properties, such as . -/// -/// Apple documentation for SKView -[MacCatalyst (13, 1)] -[BaseType (typeof (UIView))] -[DisableDefaultCtor] + /// A that displays a . + /// + /// Application developers should note the availability of debugging properties, such as . + /// + /// Apple documentation for SKView + [MacCatalyst (13, 1)] + [BaseType (typeof (UIView))] + [DisableDefaultCtor] + partial interface SKView #if MONOMAC - partial interface SKView : NSSecureCoding { -#else -partial interface SKView { + : NSSecureCoding #endif - [Export ("initWithFrame:")] - NativeHandle Constructor (CGRect frame); + { + [Export ("initWithFrame:")] + NativeHandle Constructor (CGRect frame); - [Export ("paused")] - bool Paused { [Bind ("isPaused")] get; set; } + [Export ("paused")] + bool Paused { [Bind ("isPaused")] get; set; } - [Export ("showsFPS")] - bool ShowsFPS { get; set; } + [Export ("showsFPS")] + bool ShowsFPS { get; set; } - [Export ("showsDrawCount")] - bool ShowsDrawCount { get; set; } + [Export ("showsDrawCount")] + bool ShowsDrawCount { get; set; } - [Export ("showsNodeCount")] - bool ShowsNodeCount { get; set; } - - [MacCatalyst (13, 1)] - [Export ("showsPhysics")] - bool ShowsPhysics { get; set; } - - [Export ("asynchronous")] - bool Asynchronous { [Bind ("isAsynchronous")] get; set; } - - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("frameInterval")] - nint FrameInterval { get; set; } - - [Export ("presentScene:")] - void PresentScene ([NullAllowed] SKScene scene); - - [Export ("presentScene:transition:")] - void PresentScene (SKScene scene, SKTransition transition); - - [Export ("scene")] - [NullAllowed] - SKScene Scene { get; } - - [Export ("textureFromNode:")] - [return: NullAllowed] - SKTexture TextureFromNode (SKNode node); - - [Export ("convertPoint:toScene:")] - CGPoint ConvertPointToScene (CGPoint point, SKScene scene); - - [Export ("convertPoint:fromScene:")] - CGPoint ConvertPointFromScene (CGPoint point, SKScene scene); - - [Export ("ignoresSiblingOrder")] - bool IgnoresSiblingOrder { get; set; } - - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Export ("allowsTransparency")] - bool AllowsTransparency { get; set; } - - [MacCatalyst (13, 1)] - [Export ("shouldCullNonVisibleNodes")] - bool ShouldCullNonVisibleNodes { get; set; } + [Export ("showsNodeCount")] + bool ShowsNodeCount { get; set; } - [MacCatalyst (13, 1)] - [Export ("showsFields")] - bool ShowsFields { get; set; } + [MacCatalyst (13, 1)] + [Export ("showsPhysics")] + bool ShowsPhysics { get; set; } - [MacCatalyst (13, 1)] - [Export ("showsQuadCount")] - bool ShowsQuadCount { get; set; } + [Export ("asynchronous")] + bool Asynchronous { [Bind ("isAsynchronous")] get; set; } - [MacCatalyst (13, 1)] - [Export ("textureFromNode:crop:")] - [return: NullAllowed] - SKTexture TextureFromNode (SKNode node, CGRect crop); + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("frameInterval")] + nint FrameInterval { get; set; } - [MacCatalyst (13, 1)] - [Export ("preferredFramesPerSecond")] - nint PreferredFramesPerSecond { get; set; } + [Export ("presentScene:")] + void PresentScene ([NullAllowed] SKScene scene); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] - ISKViewDelegate Delegate { get; set; } - - [iOS (14, 0)] - [TV (14, 0)] - [MacCatalyst (14, 0)] - [Export ("disableDepthStencilBuffer")] - bool DisableDepthStencilBuffer { get; set; } -} + [Export ("presentScene:transition:")] + void PresentScene (SKScene scene, SKTransition transition); -/// Interface representing the required methods (if any) of the protocol . -/// -/// This interface contains the required methods (if any) from the protocol defined by . -/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. -/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. -/// -interface ISKViewDelegate { } - -/// Delegate object for objects, allowing the developer to control the frame rate. -/// -/// Apple documentation for SKViewDelegate -[MacCatalyst (13, 1)] -[Protocol, Model] -[BaseType (typeof (NSObject))] -interface SKViewDelegate { - [Export ("view:shouldRenderAtTime:")] - bool ShouldRender (SKView view, double time); -} + [Export ("scene")] + [NullAllowed] + SKScene Scene { get; } -/// Transitions that can be used between s. Used with the method. -/// -/// Apple documentation for SKTransition -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -partial interface SKTransition : NSCopying { + [Export ("textureFromNode:")] + [return: NullAllowed] + SKTexture TextureFromNode (SKNode node); - [Static, Export ("crossFadeWithDuration:")] - SKTransition CrossFadeWithDuration (double sec); + [Export ("convertPoint:toScene:")] + CGPoint ConvertPointToScene (CGPoint point, SKScene scene); - [Static, Export ("fadeWithDuration:")] - SKTransition FadeWithDuration (double sec); + [Export ("convertPoint:fromScene:")] + CGPoint ConvertPointFromScene (CGPoint point, SKScene scene); - [Static, Export ("fadeWithColor:duration:")] - SKTransition FadeWithColor (UIColor color, double sec); + [Export ("ignoresSiblingOrder")] + bool IgnoresSiblingOrder { get; set; } - [Static, Export ("flipHorizontalWithDuration:")] - SKTransition FlipHorizontalWithDuration (double sec); + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("allowsTransparency")] + bool AllowsTransparency { get; set; } - [Static, Export ("flipVerticalWithDuration:")] - SKTransition FlipVerticalWithDuration (double sec); + [MacCatalyst (13, 1)] + [Export ("shouldCullNonVisibleNodes")] + bool ShouldCullNonVisibleNodes { get; set; } - [Static, Export ("revealWithDirection:duration:")] - SKTransition RevealWithDirection (SKTransitionDirection direction, double sec); + [MacCatalyst (13, 1)] + [Export ("showsFields")] + bool ShowsFields { get; set; } - [Static, Export ("moveInWithDirection:duration:")] - SKTransition MoveInWithDirection (SKTransitionDirection direction, double sec); + [MacCatalyst (13, 1)] + [Export ("showsQuadCount")] + bool ShowsQuadCount { get; set; } - [Static, Export ("pushWithDirection:duration:")] - SKTransition PushWithDirection (SKTransitionDirection direction, double sec); + [MacCatalyst (13, 1)] + [Export ("textureFromNode:crop:")] + [return: NullAllowed] + SKTexture TextureFromNode (SKNode node, CGRect crop); - [Static, Export ("doorsOpenHorizontalWithDuration:")] - SKTransition DoorsOpenHorizontalWithDuration (double sec); + [MacCatalyst (13, 1)] + [Export ("preferredFramesPerSecond")] + nint PreferredFramesPerSecond { get; set; } - [Static, Export ("doorsOpenVerticalWithDuration:")] - SKTransition DoorsOpenVerticalWithDuration (double sec); + [MacCatalyst (13, 1)] + [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] + ISKViewDelegate Delegate { get; set; } - [Static, Export ("doorsCloseHorizontalWithDuration:")] - SKTransition DoorsCloseHorizontalWithDuration (double sec); + [iOS (14, 0)] + [TV (14, 0)] + [MacCatalyst (14, 0)] + [Export ("disableDepthStencilBuffer")] + bool DisableDepthStencilBuffer { get; set; } + } - [Static, Export ("doorsCloseVerticalWithDuration:")] - SKTransition DoorsCloseVerticalWithDuration (double sec); + /// Interface representing the required methods (if any) of the protocol . + /// + /// This interface contains the required methods (if any) from the protocol defined by . + /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. + /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. + /// + interface ISKViewDelegate { } - [Static, Export ("doorwayWithDuration:")] - SKTransition DoorwayWithDuration (double sec); + /// Delegate object for objects, allowing the developer to control the frame rate. + /// + /// Apple documentation for SKViewDelegate + [MacCatalyst (13, 1)] + [Protocol, Model] + [BaseType (typeof (NSObject))] + interface SKViewDelegate { + [Export ("view:shouldRenderAtTime:")] + bool ShouldRender (SKView view, double time); + } + /// Transitions that can be used between s. Used with the method. + /// + /// Apple documentation for SKTransition [MacCatalyst (13, 1)] - [Static, Export ("transitionWithCIFilter:duration:")] - SKTransition TransitionWithCIFilter (CIFilter filter, double sec); + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + partial interface SKTransition : NSCopying { - [Export ("pausesIncomingScene")] - bool PausesIncomingScene { get; set; } + [Static, Export ("crossFadeWithDuration:")] + SKTransition CrossFadeWithDuration (double sec); - [Export ("pausesOutgoingScene")] - bool PausesOutgoingScene { get; set; } -} + [Static, Export ("fadeWithDuration:")] + SKTransition FadeWithDuration (double sec); -/// An image that can be used with one or more s and particles. -/// -/// Sprite Kit attempts to be efficient with the memory associated with textures. Textures are lazy-loaded from their source files and in preparation for loading onto the graphics hardware. This lazy-loading can be overridden with the Preload* methods. -/// -/// -/// Apple documentation for SKTexture -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -partial interface SKTexture : NSSecureCoding, NSCopying { + [Static, Export ("fadeWithColor:duration:")] + SKTransition FadeWithColor (UIColor color, double sec); - [Static, Export ("textureWithImageNamed:")] - SKTexture FromImageNamed (string name); + [Static, Export ("flipHorizontalWithDuration:")] + SKTransition FlipHorizontalWithDuration (double sec); - [Static, Export ("textureWithRect:inTexture:")] - SKTexture FromRectangle (CGRect rect, SKTexture texture); + [Static, Export ("flipVerticalWithDuration:")] + SKTransition FlipVerticalWithDuration (double sec); - [Static, Export ("textureWithCGImage:")] - SKTexture FromImage (CGImage image); + [Static, Export ("revealWithDirection:duration:")] + SKTransition RevealWithDirection (SKTransitionDirection direction, double sec); - [Static, Export ("textureWithImage:")] - SKTexture FromImage (UIImage image); + [Static, Export ("moveInWithDirection:duration:")] + SKTransition MoveInWithDirection (SKTransitionDirection direction, double sec); - [Static, Export ("textureWithData:size:")] - SKTexture FromData (NSData pixelData, CGSize size); + [Static, Export ("pushWithDirection:duration:")] + SKTransition PushWithDirection (SKTransitionDirection direction, double sec); - [Static, Export ("textureWithData:size:rowLength:alignment:")] - SKTexture FromData (NSData pixelData, CGSize size, uint /* unsigned int*/ rowLength, uint /* unsigned int */ alignment); + [Static, Export ("doorsOpenHorizontalWithDuration:")] + SKTransition DoorsOpenHorizontalWithDuration (double sec); - [MacCatalyst (13, 1)] - [Export ("textureByApplyingCIFilter:")] - SKTexture TextureByApplyingCIFilter (CIFilter filter); + [Static, Export ("doorsOpenVerticalWithDuration:")] + SKTransition DoorsOpenVerticalWithDuration (double sec); - [Export ("textureRect")] - CGRect TextureRect { get; } + [Static, Export ("doorsCloseHorizontalWithDuration:")] + SKTransition DoorsCloseHorizontalWithDuration (double sec); - [Export ("size")] - CGSize Size { get; } + [Static, Export ("doorsCloseVerticalWithDuration:")] + SKTransition DoorsCloseVerticalWithDuration (double sec); - [Export ("filteringMode")] - SKTextureFilteringMode FilteringMode { get; set; } + [Static, Export ("doorwayWithDuration:")] + SKTransition DoorwayWithDuration (double sec); - [Export ("usesMipmaps")] - bool UsesMipmaps { get; set; } + [MacCatalyst (13, 1)] + [Static, Export ("transitionWithCIFilter:duration:")] + SKTransition TransitionWithCIFilter (CIFilter filter, double sec); - [Static] - [Export ("preloadTextures:withCompletionHandler:")] - [Async] - // note: unlike SKTextureAtlas completion can't be null (or it crash) - void PreloadTextures (SKTexture [] textures, Action completion); + [Export ("pausesIncomingScene")] + bool PausesIncomingScene { get; set; } - [Export ("preloadWithCompletionHandler:")] - [Async] - // note: unlike SKTextureAtlas completion can't be null (or it crash) - void Preload (Action completion); + [Export ("pausesOutgoingScene")] + bool PausesOutgoingScene { get; set; } + } + /// An image that can be used with one or more s and particles. + /// + /// Sprite Kit attempts to be efficient with the memory associated with textures. Textures are lazy-loaded from their source files and in preparation for loading onto the graphics hardware. This lazy-loading can be overridden with the Preload* methods. + /// + /// + /// Apple documentation for SKTexture [MacCatalyst (13, 1)] - [Export ("textureByGeneratingNormalMap")] - SKTexture CreateTextureByGeneratingNormalMap (); + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + partial interface SKTexture : NSSecureCoding, NSCopying { - [MacCatalyst (13, 1)] - [Export ("textureByGeneratingNormalMapWithSmoothness:contrast:")] - SKTexture CreateTextureByGeneratingNormalMap (nfloat smoothness, nfloat contrast); + [Static, Export ("textureWithImageNamed:")] + SKTexture FromImageNamed (string name); - [MacCatalyst (13, 1)] - [Static, Export ("textureVectorNoiseWithSmoothness:size:")] - SKTexture FromTextureVectorNoise (nfloat smoothness, CGSize size); + [Static, Export ("textureWithRect:inTexture:")] + SKTexture FromRectangle (CGRect rect, SKTexture texture); - [MacCatalyst (13, 1)] - [Static, Export ("textureNoiseWithSmoothness:size:grayscale:")] - SKTexture FromTextureNoise (nfloat smoothness, CGSize size, bool grayscale); + [Static, Export ("textureWithCGImage:")] + SKTexture FromImage (CGImage image); - [MacCatalyst (13, 1)] - [Static, Export ("textureWithData:size:flipped:")] - SKTexture FromData (NSData pixelData, CGSize size, bool flipped); + [Static, Export ("textureWithImage:")] + SKTexture FromImage (UIImage image); - [MacCatalyst (13, 1)] - [Export ("CGImage")] - CGImage CGImage { get; } + [Static, Export ("textureWithData:size:")] + SKTexture FromData (NSData pixelData, CGSize size); - // Static Category from GameplayKit - [MacCatalyst (13, 1)] - [Static] - [Export ("textureWithNoiseMap:")] - SKTexture FromNoiseMap (GKNoiseMap noiseMap); -} + [Static, Export ("textureWithData:size:rowLength:alignment:")] + SKTexture FromData (NSData pixelData, CGSize size, uint /* unsigned int*/ rowLength, uint /* unsigned int */ alignment); -/// A method that modifies a texture in place. -delegate void SKTextureModify (IntPtr pixelData, nuint lengthInBytes); + [MacCatalyst (13, 1)] + [Export ("textureByApplyingCIFilter:")] + SKTexture TextureByApplyingCIFilter (CIFilter filter); -/// A texture that can be modified after assignment. -/// -/// Apple documentation for SKMutableTexture -[MacCatalyst (13, 1)] -[BaseType (typeof (SKTexture))] -[DisableDefaultCtor] // cannot be created (like SKTexture) by calling `init` -interface SKMutableTexture { - [Export ("initWithSize:")] - NativeHandle Constructor (CGSize size); + [Export ("textureRect")] + CGRect TextureRect { get; } - [Export ("initWithSize:pixelFormat:")] - NativeHandle Constructor (CGSize size, CVPixelFormatType pixelFormat); + [Export ("size")] + CGSize Size { get; } - [Static, Export ("mutableTextureWithSize:")] - SKMutableTexture Create (CGSize size); + [Export ("filteringMode")] + SKTextureFilteringMode FilteringMode { get; set; } - [Export ("modifyPixelDataWithBlock:")] - void ModifyPixelData (SKTextureModify modifyMethod); -} + [Export ("usesMipmaps")] + bool UsesMipmaps { get; set; } -delegate void SKTextureAtlasLoadCallback (NSError error, SKTextureAtlas foundAtlases); + [Static] + [Export ("preloadTextures:withCompletionHandler:")] + [Async] + // note: unlike SKTextureAtlas completion can't be null (or it crash) + void PreloadTextures (SKTexture [] textures, Action completion); -/// A collection of s that are loaded from a single source. -/// -/// -/// Apple documentation for SKTextureAtlas -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -partial interface SKTextureAtlas : NSSecureCoding { + [Export ("preloadWithCompletionHandler:")] + [Async] + // note: unlike SKTextureAtlas completion can't be null (or it crash) + void Preload (Action completion); - [Static, Export ("atlasNamed:")] - SKTextureAtlas FromName (string name); + [MacCatalyst (13, 1)] + [Export ("textureByGeneratingNormalMap")] + SKTexture CreateTextureByGeneratingNormalMap (); - [Export ("textureNamed:")] - SKTexture TextureNamed (string name); + [MacCatalyst (13, 1)] + [Export ("textureByGeneratingNormalMapWithSmoothness:contrast:")] + SKTexture CreateTextureByGeneratingNormalMap (nfloat smoothness, nfloat contrast); - [Export ("textureNames")] - string [] TextureNames { get; } + [MacCatalyst (13, 1)] + [Static, Export ("textureVectorNoiseWithSmoothness:size:")] + SKTexture FromTextureVectorNoise (nfloat smoothness, CGSize size); - [Static] - [Export ("preloadTextureAtlases:withCompletionHandler:")] - [Async] - // Unfortunate name, should have been PreloadTextureAtlases - void PreloadTextures (SKTextureAtlas [] textures, Action completion); + [MacCatalyst (13, 1)] + [Static, Export ("textureNoiseWithSmoothness:size:grayscale:")] + SKTexture FromTextureNoise (nfloat smoothness, CGSize size, bool grayscale); - [MacCatalyst (13, 1)] - [Static] - [Export ("preloadTextureAtlasesNamed:withCompletionHandler:")] - [Async (ResultTypeName = "SKTextureAtlasLoadResult")] - void PreloadTextureAtlases (string [] atlasNames, SKTextureAtlasLoadCallback completionHandler); + [MacCatalyst (13, 1)] + [Static, Export ("textureWithData:size:flipped:")] + SKTexture FromData (NSData pixelData, CGSize size, bool flipped); - [Export ("preloadWithCompletionHandler:")] - [Async] - void Preload (Action completion); + [MacCatalyst (13, 1)] + [Export ("CGImage")] + CGImage CGImage { get; } - [MacCatalyst (13, 1)] - [Static, Export ("atlasWithDictionary:")] - SKTextureAtlas FromDictionary (NSDictionary properties); + // Static Category from GameplayKit + [MacCatalyst (13, 1)] + [Static] + [Export ("textureWithNoiseMap:")] + SKTexture FromNoiseMap (GKNoiseMap noiseMap); + } -} + /// A method that modifies a texture in place. + delegate void SKTextureModify (IntPtr pixelData, nuint lengthInBytes); -/// Holds shareable uniform data for SKShader objects. -/// -/// Apple documentation for SKUniform -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKUniform : NSCopying, NSSecureCoding { - [Export ("initWithName:")] - NativeHandle Constructor (string name); - - [Export ("initWithName:texture:")] - NativeHandle Constructor (string name, [NullAllowed] SKTexture texture); - - [Export ("initWithName:float:")] - NativeHandle Constructor (string name, float /* float, not CGFloat */ value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] + /// A texture that can be modified after assignment. + /// + /// Apple documentation for SKMutableTexture [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector2:")] - IntPtr InitWithNameFloatVector2 (string name, Vector2 value); + [BaseType (typeof (SKTexture))] + [DisableDefaultCtor] // cannot be created (like SKTexture) by calling `init` + interface SKMutableTexture { + [Export ("initWithSize:")] + NativeHandle Constructor (CGSize size); - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [MarshalNativeExceptions] - [Internal] - IntPtr InitWithNameVectorFloat2 (string name, Vector2 value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector3:")] - IntPtr InitWithNameFloatVector3 (string name, Vector3 value); + [Export ("initWithSize:pixelFormat:")] + NativeHandle Constructor (CGSize size, CVPixelFormatType pixelFormat); - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameVectorFloat3 (string name, Vector3 value); - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithName:floatVector4:")] - IntPtr InitWithNameFloatVector4 (string name, Vector4 value); + [Static, Export ("mutableTextureWithSize:")] + SKMutableTexture Create (CGSize size); - [MacCatalyst (13, 1)] - [Export ("initWithName:vectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameVectorFloat4 (string name, Vector4 value); - -#if !NET - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Export ("initWithName:floatMatrix2:")] - IntPtr InitWithNameFloatMatrix2 (string name, Matrix2 value); -#endif + [Export ("modifyPixelDataWithBlock:")] + void ModifyPixelData (SKTextureModify modifyMethod); + } -#if !NET - [Obsolete ("Use the '(string, MatrixFloat2x2)' overload instead.")] - [Sealed] - [Export ("initWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameMatrixFloat2x2 (string name, Matrix2 value); -#endif // !NET + delegate void SKTextureAtlasLoadCallback (NSError error, SKTextureAtlas foundAtlases); + /// A collection of s that are loaded from a single source. + /// + /// + /// Apple documentation for SKTextureAtlas [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat2x2 value); - -#if !NET - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Export ("initWithName:floatMatrix3:")] - IntPtr InitWithNameFloatMatrix3 (string name, Matrix3 value); - - [Obsolete ("Use the '(string, MatrixFloat3x3)' overload instead.")] - [Sealed] - [Export ("initWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameMatrixFloat3x3 (string name, Matrix3 value); -#endif // !NET + [BaseType (typeof (NSObject))] + partial interface SKTextureAtlas : NSSecureCoding { - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat3x3 value); - -#if !NET - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Export ("initWithName:floatMatrix4:")] - IntPtr InitWithNameFloatMatrix4 (string name, Matrix4 value); -#endif // !NET - -#if !NET - [Obsolete ("Use the '(string, MatrixFloat4x4)' overload instead.")] - [Export ("initWithName:matrixFloat4x4:")] - [Sealed] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [Internal] - IntPtr InitWithNameMatrixFloat4x4 (string name, Matrix4 value); -#endif // !NET + [Static, Export ("atlasNamed:")] + SKTextureAtlas FromName (string name); - [MacCatalyst (13, 1)] - [Export ("initWithName:matrixFloat4x4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - NativeHandle Constructor (string name, MatrixFloat4x4 value); + [Export ("textureNamed:")] + SKTexture TextureNamed (string name); - [Export ("name")] - string Name { get; } + [Export ("textureNames")] + string [] TextureNames { get; } - [Export ("uniformType")] - SKUniformType UniformType { get; } + [Static] + [Export ("preloadTextureAtlases:withCompletionHandler:")] + [Async] + // Unfortunate name, should have been PreloadTextureAtlases + void PreloadTextures (SKTextureAtlas [] textures, Action completion); - [Export ("textureValue")] - [NullAllowed] - SKTexture TextureValue { get; set; } + [MacCatalyst (13, 1)] + [Static] + [Export ("preloadTextureAtlasesNamed:withCompletionHandler:")] + [Async (ResultTypeName = "SKTextureAtlasLoadResult")] + void PreloadTextureAtlases (string [] atlasNames, SKTextureAtlasLoadCallback completionHandler); - [Export ("floatValue")] - float FloatValue { get; set; } /* float, not CGFloat */ + [Export ("preloadWithCompletionHandler:")] + [Async] + void Preload (Action completion); - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector2Value")] - Vector2 _FloatVector2Value { get; set; } + [MacCatalyst (13, 1)] + [Static, Export ("atlasWithDictionary:")] + SKTextureAtlas FromDictionary (NSDictionary properties); - [MacCatalyst (13, 1)] - [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] - [Internal] - Vector2 _VectorFloat2Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; } - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector3Value")] - Vector3 _FloatVector3Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] - [Internal] - Vector3 _VectorFloat3Value { + /// Holds shareable uniform data for SKShader objects. + /// + /// Apple documentation for SKUniform + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKUniform : NSCopying, NSSecureCoding { + [Export ("initWithName:")] + NativeHandle Constructor (string name); + + [Export ("initWithName:texture:")] + NativeHandle Constructor (string name, [NullAllowed] SKTexture texture); + + [Export ("initWithName:float:")] + NativeHandle Constructor (string name, float /* float, not CGFloat */ value); + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector2:")] + IntPtr InitWithNameFloatVector2 (string name, Vector2 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat2:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; + [MarshalNativeExceptions] + [Internal] + IntPtr InitWithNameVectorFloat2 (string name, Vector2 value); + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector3:")] + IntPtr InitWithNameFloatVector3 (string name, Vector3 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat3:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } - - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [MacCatalyst (13, 1)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("floatVector4Value")] - Vector4 _FloatVector4Value { get; set; } - - [MacCatalyst (13, 1)] - [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] - [Internal] - Vector4 _VectorFloat4Value { + [Internal] + IntPtr InitWithNameVectorFloat3 (string name, Vector3 value); + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("initWithName:floatVector4:")] + IntPtr InitWithNameFloatVector4 (string name, Vector4 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:vectorFloat4:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; + [Internal] + IntPtr InitWithNameVectorFloat4 (string name, Vector4 value); + + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat2x2:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + NativeHandle Constructor (string name, MatrixFloat2x2 value); -#if !NET - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Export ("floatMatrix2Value")] - Matrix2 _FloatMatrix2Value { get; set; } -#endif // !NET + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat3x3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + NativeHandle Constructor (string name, MatrixFloat3x3 value); - [MacCatalyst (13, 1)] - [Export ("matrixFloat2x2Value", ArgumentSemantic.Assign)] - MatrixFloat2x2 MatrixFloat2x2Value { + [MacCatalyst (13, 1)] + [Export ("initWithName:matrixFloat4x4:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; + NativeHandle Constructor (string name, MatrixFloat4x4 value); + + [Export ("name")] + string Name { get; } + + [Export ("uniformType")] + SKUniformType UniformType { get; } + + [Export ("textureValue")] + [NullAllowed] + SKTexture TextureValue { get; set; } + + [Export ("floatValue")] + float FloatValue { get; set; } /* float, not CGFloat */ + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector2Value")] + Vector2 _FloatVector2Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] + [Internal] + Vector2 _VectorFloat2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector3Value")] + Vector3 _FloatVector3Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] + [Internal] + Vector3 _VectorFloat3Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Internal] + [Deprecated (PlatformName.iOS, 10, 0)] + [Deprecated (PlatformName.TvOS, 10, 0)] + [Deprecated (PlatformName.MacOSX, 10, 12)] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1)] + [Export ("floatVector4Value")] + Vector4 _FloatVector4Value { get; set; } + + [MacCatalyst (13, 1)] + [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] + [Internal] + Vector4 _VectorFloat4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [MacCatalyst (13, 1)] + [Export ("matrixFloat2x2Value", ArgumentSemantic.Assign)] + MatrixFloat2x2 MatrixFloat2x2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [MacCatalyst (13, 1)] + [Export ("matrixFloat3x3Value", ArgumentSemantic.Assign)] + MatrixFloat3x3 MatrixFloat3x3Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [MacCatalyst (13, 1)] + [Export ("matrixFloat4x4Value", ArgumentSemantic.Assign)] + MatrixFloat4x4 MatrixFloat4x4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Static, Export ("uniformWithName:")] + SKUniform Create (string name); + + [Static, Export ("uniformWithName:texture:")] + SKUniform Create (string name, [NullAllowed] SKTexture texture); + + [Static, Export ("uniformWithName:float:")] + SKUniform Create (string name, float /* float, not CGFloat */ value); + + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat2:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [MarshalNativeExceptions] + SKUniform Create (string name, Vector2 value); -#if !NET - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Export ("floatMatrix3Value")] - Matrix3 _FloatMatrix3Value { get; set; } -#endif // !NET - - [MacCatalyst (13, 1)] - [Export ("matrixFloat3x3Value", ArgumentSemantic.Assign)] - MatrixFloat3x3 MatrixFloat3x3Value { + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat3:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; + SKUniform Create (string name, Vector3 value); + + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:vectorFloat4:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + SKUniform Create (string name, Vector4 value); -#if !NET - [Internal] - [Deprecated (PlatformName.iOS, 10, 0)] - [Deprecated (PlatformName.TvOS, 10, 0)] - [Deprecated (PlatformName.MacOSX, 10, 12)] - [Export ("floatMatrix4Value")] - Matrix4 _FloatMatrix4Value { get; set; } -#endif // !NET + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat2x2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKUniform Create (string name, MatrixFloat2x2 value); - [MacCatalyst (13, 1)] - [Export ("matrixFloat4x4Value", ArgumentSemantic.Assign)] - MatrixFloat4x4 MatrixFloat4x4Value { + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat3x3:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; + SKUniform Create (string name, MatrixFloat3x3 value); + + [MacCatalyst (13, 1)] + [Static] + [Export ("uniformWithName:matrixFloat4x4:")] [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; + SKUniform Create (string name, MatrixFloat4x4 value); } - [Static, Export ("uniformWithName:")] - SKUniform Create (string name); - - [Static, Export ("uniformWithName:texture:")] - SKUniform Create (string name, [NullAllowed] SKTexture texture); - - [Static, Export ("uniformWithName:float:")] - SKUniform Create (string name, float /* float, not CGFloat */ value); - - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - [MarshalNativeExceptions] - SKUniform Create (string name, Vector2 value); - - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Vector3 value); - - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:vectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Vector4 value); - -#if !NET - [Obsolete ("Use the '(string, MatrixFloat2x2)' overload instead.")] - [Static] - [Export ("uniformWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Matrix2 value); -#endif // !NET + /// The delegate for a custom action, used with . + delegate void SKActionDurationHandler (SKNode node, nfloat elapsedTime); + /// [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat2x2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat2x2 value); - -#if !NET - [Obsolete ("Use the '(string, MatrixFloat3x3)' overload instead.")] - [Static] - [Export ("uniformWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Matrix3 value); -#endif + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] // To create an action, call the class method for the action you are interested in. + partial interface SKAction : NSSecureCoding, NSCopying { - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat3x3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat3x3 value); - -#if !NET - [Obsolete ("Use 'the '(string, MatrixFloat4x4)' overload instead.")] - [Static] - [Export ("uniformWithName:matrixFloat4x4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, Matrix4 value); -#endif // !NET + [Export ("duration")] + double Duration { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("uniformWithName:matrixFloat4x4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKUniform Create (string name, MatrixFloat4x4 value); -} + [Export ("timingMode")] + SKActionTimingMode TimingMode { get; set; } -/// The delegate for a custom action, used with . -delegate void SKActionDurationHandler (SKNode node, nfloat elapsedTime); + [Export ("speed")] + nfloat Speed { get; set; } -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] // To create an action, call the class method for the action you are interested in. -partial interface SKAction : NSSecureCoding, NSCopying { + [Export ("reversedAction")] + SKAction ReversedAction { get; } - [Export ("duration")] - double Duration { get; set; } + // These are in a category + [Static, Export ("moveByX:y:duration:")] + SKAction MoveBy (nfloat deltaX, nfloat deltaY, double sec); - [Export ("timingMode")] - SKActionTimingMode TimingMode { get; set; } + [Static, Export ("moveBy:duration:")] + SKAction MoveBy (CGVector delta, double duration); - [Export ("speed")] - nfloat Speed { get; set; } + [Static, Export ("moveTo:duration:")] + SKAction MoveTo (CGPoint location, double sec); - [Export ("reversedAction")] - SKAction ReversedAction { get; } + [Static, Export ("moveToX:duration:")] + SKAction MoveToX (nfloat x, double sec); - // These are in a category - [Static, Export ("moveByX:y:duration:")] - SKAction MoveBy (nfloat deltaX, nfloat deltaY, double sec); + [Static, Export ("moveToY:duration:")] + SKAction MoveToY (nfloat y, double sec); - [Static, Export ("moveBy:duration:")] - SKAction MoveBy (CGVector delta, double duration); + [Static, Export ("rotateByAngle:duration:")] + SKAction RotateByAngle (nfloat radians, double sec); - [Static, Export ("moveTo:duration:")] - SKAction MoveTo (CGPoint location, double sec); + [Static, Export ("rotateToAngle:duration:")] + SKAction RotateToAngle (nfloat radians, double sec); - [Static, Export ("moveToX:duration:")] - SKAction MoveToX (nfloat x, double sec); + [Static, Export ("rotateToAngle:duration:shortestUnitArc:")] + SKAction RotateToAngle (nfloat radians, double sec, bool shortedUnitArc); - [Static, Export ("moveToY:duration:")] - SKAction MoveToY (nfloat y, double sec); + [Static, Export ("resizeByWidth:height:duration:")] + SKAction ResizeByWidth (nfloat width, nfloat height, double duration); - [Static, Export ("rotateByAngle:duration:")] - SKAction RotateByAngle (nfloat radians, double sec); + [Static, Export ("resizeToWidth:height:duration:")] + SKAction ResizeTo (nfloat width, nfloat height, double duration); - [Static, Export ("rotateToAngle:duration:")] - SKAction RotateToAngle (nfloat radians, double sec); + [Static, Export ("resizeToWidth:duration:")] + SKAction ResizeToWidth (nfloat width, double duration); - [Static, Export ("rotateToAngle:duration:shortestUnitArc:")] - SKAction RotateToAngle (nfloat radians, double sec, bool shortedUnitArc); + [Static, Export ("resizeToHeight:duration:")] + SKAction ResizeToHeight (nfloat height, double duration); - [Static, Export ("resizeByWidth:height:duration:")] - SKAction ResizeByWidth (nfloat width, nfloat height, double duration); + [Static, Export ("scaleBy:duration:")] + SKAction ScaleBy (nfloat scale, double sec); - [Static, Export ("resizeToWidth:height:duration:")] - SKAction ResizeTo (nfloat width, nfloat height, double duration); + [Static, Export ("scaleXBy:y:duration:")] + SKAction ScaleBy (nfloat xScale, nfloat yScale, double sec); - [Static, Export ("resizeToWidth:duration:")] - SKAction ResizeToWidth (nfloat width, double duration); + [Static, Export ("scaleTo:duration:")] + SKAction ScaleTo (nfloat scale, double sec); - [Static, Export ("resizeToHeight:duration:")] - SKAction ResizeToHeight (nfloat height, double duration); + [Static, Export ("scaleXTo:y:duration:")] + SKAction ScaleTo (nfloat xScale, nfloat yScale, double sec); - [Static, Export ("scaleBy:duration:")] - SKAction ScaleBy (nfloat scale, double sec); + [Static, Export ("scaleXTo:duration:")] + SKAction ScaleXTo (nfloat scale, double sec); - [Static, Export ("scaleXBy:y:duration:")] - SKAction ScaleBy (nfloat xScale, nfloat yScale, double sec); + [Static, Export ("scaleYTo:duration:")] + SKAction ScaleYTo (nfloat scale, double sec); - [Static, Export ("scaleTo:duration:")] - SKAction ScaleTo (nfloat scale, double sec); + [MacCatalyst (13, 1)] + [Static] + [Export ("scaleToSize:duration:")] + SKAction ScaleTo (CGSize size, double sec); - [Static, Export ("scaleXTo:y:duration:")] - SKAction ScaleTo (nfloat xScale, nfloat yScale, double sec); + [Static, Export ("sequence:")] + SKAction Sequence ([Params] SKAction [] actions); - [Static, Export ("scaleXTo:duration:")] - SKAction ScaleXTo (nfloat scale, double sec); + [Static, Export ("group:")] + SKAction Group ([Params] SKAction [] actions); - [Static, Export ("scaleYTo:duration:")] - SKAction ScaleYTo (nfloat scale, double sec); + [Static, Export ("repeatAction:count:")] + SKAction RepeatAction (SKAction action, nuint count); - [MacCatalyst (13, 1)] - [Static] - [Export ("scaleToSize:duration:")] - SKAction ScaleTo (CGSize size, double sec); + [Static, Export ("repeatActionForever:")] + SKAction RepeatActionForever (SKAction action); - [Static, Export ("sequence:")] - SKAction Sequence ([Params] SKAction [] actions); + [Static, Export ("fadeInWithDuration:")] + SKAction FadeInWithDuration (double sec); - [Static, Export ("group:")] - SKAction Group ([Params] SKAction [] actions); + [Static, Export ("fadeOutWithDuration:")] + SKAction FadeOutWithDuration (double sec); - [Static, Export ("repeatAction:count:")] - SKAction RepeatAction (SKAction action, nuint count); + [Static, Export ("fadeAlphaBy:duration:")] + SKAction FadeAlphaBy (nfloat factor, double sec); - [Static, Export ("repeatActionForever:")] - SKAction RepeatActionForever (SKAction action); + [Static, Export ("fadeAlphaTo:duration:")] + SKAction FadeAlphaTo (nfloat alpha, double sec); - [Static, Export ("fadeInWithDuration:")] - SKAction FadeInWithDuration (double sec); + [MacCatalyst (13, 1)] + [Static, Export ("setTexture:")] + SKAction SetTexture (SKTexture texture); - [Static, Export ("fadeOutWithDuration:")] - SKAction FadeOutWithDuration (double sec); + [MacCatalyst (13, 1)] + [Static, Export ("setTexture:resize:")] + SKAction SetTexture (SKTexture texture, bool resize); - [Static, Export ("fadeAlphaBy:duration:")] - SKAction FadeAlphaBy (nfloat factor, double sec); + [Static, Export ("animateWithTextures:timePerFrame:")] + SKAction AnimateWithTextures (SKTexture [] textures, double sec); - [Static, Export ("fadeAlphaTo:duration:")] - SKAction FadeAlphaTo (nfloat alpha, double sec); + [Static, Export ("animateWithTextures:timePerFrame:resize:restore:")] + SKAction AnimateWithTextures (SKTexture [] textures, double sec, bool resize, bool restore); - [MacCatalyst (13, 1)] - [Static, Export ("setTexture:")] - SKAction SetTexture (SKTexture texture); + [Static, Export ("playSoundFileNamed:waitForCompletion:")] + SKAction PlaySoundFileNamed (string soundFile, bool wait); - [MacCatalyst (13, 1)] - [Static, Export ("setTexture:resize:")] - SKAction SetTexture (SKTexture texture, bool resize); + [Static, Export ("colorizeWithColor:colorBlendFactor:duration:")] + SKAction ColorizeWithColor (UIColor color, nfloat colorBlendFactor, double sec); - [Static, Export ("animateWithTextures:timePerFrame:")] - SKAction AnimateWithTextures (SKTexture [] textures, double sec); + [Static, Export ("colorizeWithColorBlendFactor:duration:")] + SKAction ColorizeWithColorBlendFactor (nfloat colorBlendFactor, double sec); - [Static, Export ("animateWithTextures:timePerFrame:resize:restore:")] - SKAction AnimateWithTextures (SKTexture [] textures, double sec, bool resize, bool restore); + [Static, Export ("followPath:duration:")] + SKAction FollowPath (CGPath path, double sec); - [Static, Export ("playSoundFileNamed:waitForCompletion:")] - SKAction PlaySoundFileNamed (string soundFile, bool wait); - - [Static, Export ("colorizeWithColor:colorBlendFactor:duration:")] - SKAction ColorizeWithColor (UIColor color, nfloat colorBlendFactor, double sec); - - [Static, Export ("colorizeWithColorBlendFactor:duration:")] - SKAction ColorizeWithColorBlendFactor (nfloat colorBlendFactor, double sec); - - [Static, Export ("followPath:duration:")] - SKAction FollowPath (CGPath path, double sec); - - [Static, Export ("followPath:asOffset:orientToPath:duration:")] + [Static, Export ("followPath:asOffset:orientToPath:duration:")] #if XAMCORE_5_0 SKAction FollowPath (CGPath path, bool offset, bool orientToPath, double sec); #else - SKAction FollowPath (CGPath path, bool offset, bool orient, double sec); + SKAction FollowPath (CGPath path, bool offset, bool orient, double sec); #endif - [MacCatalyst (13, 1)] - [Static, Export ("followPath:speed:")] - SKAction FollowPath (CGPath path, nfloat speed); + [MacCatalyst (13, 1)] + [Static, Export ("followPath:speed:")] + SKAction FollowPath (CGPath path, nfloat speed); - [MacCatalyst (13, 1)] - [Static, Export ("followPath:asOffset:orientToPath:speed:")] + [MacCatalyst (13, 1)] + [Static, Export ("followPath:asOffset:orientToPath:speed:")] #if XAMCORE_5_0 SKAction FollowPath (CGPath path, bool offset, bool orientToPath, nfloat speed); #else - SKAction FollowPath (CGPath path, bool offset, bool orient, nfloat speed); + SKAction FollowPath (CGPath path, bool offset, bool orient, nfloat speed); #endif - [Static, Export ("speedBy:duration:")] - SKAction SpeedBy (nfloat speed, double sec); - - [Static, Export ("speedTo:duration:")] - SKAction SpeedTo (nfloat speed, double sec); - - [Static, Export ("waitForDuration:")] - SKAction WaitForDuration (double sec); + [Static, Export ("speedBy:duration:")] + SKAction SpeedBy (nfloat speed, double sec); - [Static, Export ("waitForDuration:withRange:")] - SKAction WaitForDuration (double sec, double durationRange); + [Static, Export ("speedTo:duration:")] + SKAction SpeedTo (nfloat speed, double sec); - [Static, Export ("removeFromParent")] - SKAction RemoveFromParent (); + [Static, Export ("waitForDuration:")] + SKAction WaitForDuration (double sec); - [Static, Export ("performSelector:onTarget:")] - SKAction PerformSelector (Selector selector, NSObject target); + [Static, Export ("waitForDuration:withRange:")] + SKAction WaitForDuration (double sec, double durationRange); + + [Static, Export ("removeFromParent")] + SKAction RemoveFromParent (); + + [Static, Export ("performSelector:onTarget:")] + SKAction PerformSelector (Selector selector, NSObject target); - [Static, Export ("runBlock:")] - SKAction Run (Action block); - - [Static, Export ("runBlock:queue:")] - SKAction Run (Action block, DispatchQueue queue); - - [Static, Export ("runAction:onChildWithName:")] - SKAction RunAction (SKAction action, string name); - - [Static, Export ("customActionWithDuration:actionBlock:")] - SKAction CustomActionWithDuration (double seconds, SKActionDurationHandler actionHandler); + [Static, Export ("runBlock:")] + SKAction Run (Action block); + + [Static, Export ("runBlock:queue:")] + SKAction Run (Action block, DispatchQueue queue); + + [Static, Export ("runAction:onChildWithName:")] + SKAction RunAction (SKAction action, string name); + + [Static, Export ("customActionWithDuration:actionBlock:")] + SKAction CustomActionWithDuration (double seconds, SKActionDurationHandler actionHandler); + + // + // iOS 8 cluster (a few more are above, as part of their family + // + [MacCatalyst (13, 1)] + [Static, Export ("hide")] + SKAction Hide (); + + [MacCatalyst (13, 1)] + [Static, Export ("unhide")] + SKAction Unhide (); + + [MacCatalyst (13, 1)] + [Static, Export ("reachTo:rootNode:duration:")] + SKAction ReachTo (CGPoint position, SKNode rootNode, double secs); + + [MacCatalyst (13, 1)] + [Static, Export ("reachTo:rootNode:velocity:")] + SKAction ReachTo (CGPoint position, SKNode rootNode, nfloat velocity); + + [MacCatalyst (13, 1)] + [Static, Export ("reachToNode:rootNode:duration:")] + SKAction ReachToNode (SKNode node, SKNode rootNode, double sec); + + [MacCatalyst (13, 1)] + [Static, Export ("reachToNode:rootNode:velocity:")] + SKAction ReachToNode (SKNode node, SKNode rootNode, nfloat velocity); + + [MacCatalyst (13, 1)] + [Static, Export ("strengthTo:duration:")] + SKAction StrengthTo (float /* float, not CGFloat */ strength, double sec); + + [MacCatalyst (13, 1)] + [Static, Export ("strengthBy:duration:")] + SKAction StrengthBy (float /* float, not CGFloat */ strength, double sec); + + [MacCatalyst (13, 1)] + [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] + SKActionTimingFunction2 TimingFunction2 { get; set; } + + [MacCatalyst (13, 1)] + [Static, Export ("falloffBy:duration:")] + SKAction FalloffBy (float /* float, not CGFloat */ to, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("falloffTo:duration:")] + SKAction FalloffTo (float falloff, double sec); + + // iOS 9 cluster + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:")] + [return: NullAllowed] + SKAction Create (string name); + + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:duration:")] + [return: NullAllowed] + SKAction Create (string name, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:fromURL:")] + [return: NullAllowed] + SKAction Create (string name, NSUrl url); + + [MacCatalyst (13, 1)] + [Static] + [Export ("actionNamed:fromURL:duration:")] + [return: NullAllowed] + SKAction Create (string name, NSUrl url, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("setNormalTexture:")] + SKAction SetNormalTexture (SKTexture texture); + + [MacCatalyst (13, 1)] + [Static] + [Export ("setNormalTexture:resize:")] + SKAction SetNormalTexture (SKTexture texture, bool resize); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithNormalTextures:timePerFrame:")] + SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithNormalTextures:timePerFrame:resize:restore:")] + SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame, bool resize, bool restore); + + [MacCatalyst (13, 1)] + [Static] + [Export ("play")] + SKAction CreatePlay (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("pause")] + SKAction CreatePause (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("stop")] + SKAction CreateStop (); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changePlaybackRateTo:duration:")] + SKAction CreateChangePlaybackRate (float playbackRate, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changePlaybackRateBy:duration:")] + SKAction CreateChangePlaybackRateBy (float playbackRate, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeVolumeTo:duration:")] + SKAction CreateChangeVolume (float newVolume, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeVolumeBy:duration:")] + SKAction CreateChangeVolumeBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeChargeTo:duration:")] + SKAction CreateChangeChargeTo (float newCharge, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeChargeBy:duration:")] + SKAction CreateChangeChargeBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeMassTo:duration:")] + SKAction CreateChangeMassTo (float newMass, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeMassBy:duration:")] + SKAction CreateChangeMassBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyForce:duration:")] + SKAction CreateApplyForce (CGVector force, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyForce:atPoint:duration:")] + SKAction CreateApplyForce (CGVector force, CGPoint point, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyTorque:duration:")] + SKAction CreateApplyTorque (nfloat torque, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyImpulse:duration:")] + SKAction CreateApplyImpulse (CGVector impulse, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyImpulse:atPoint:duration:")] + SKAction CreateApplyImpulse (CGVector impulse, CGPoint point, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("applyAngularImpulse:duration:")] + SKAction CreateApplyAngularImpulse (nfloat impulse, double duration); + + // SKAction_SKAudioNode inlined + + [MacCatalyst (13, 1)] + [Static] + [Export ("stereoPanTo:duration:")] + SKAction CreateStereoPanTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("stereoPanBy:duration:")] + SKAction CreateStereoPanBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeReverbTo:duration:")] + SKAction CreateChangeReverbTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeReverbBy:duration:")] + SKAction CreateChangeReverbBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeObstructionTo:duration:")] + SKAction CreateChangeObstructionTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeObstructionBy:duration:")] + SKAction CreateChangeObstructionBy (float by, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeOcclusionTo:duration:")] + SKAction CreateChangeOcclusionTo (float target, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("changeOcclusionBy:duration:")] + SKAction CreateChangeOcclusionBy (float by, double duration); + + // SKAction_SKWarpable + + [MacCatalyst (13, 1)] + [Static] + [Export ("warpTo:duration:")] + [return: NullAllowed] + SKAction WarpTo (SKWarpGeometry warp, double duration); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithWarps:times:")] + [return: NullAllowed] + SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times); + + [MacCatalyst (13, 1)] + [Static] + [Export ("animateWithWarps:times:restore:")] + [return: NullAllowed] + SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times, bool restore); + } - // - // iOS 8 cluster (a few more are above, as part of their family - // + /// [MacCatalyst (13, 1)] - [Static, Export ("hide")] - SKAction Hide (); + [DisableDefaultCtor] // see https://bugzilla.xamarin.com/show_bug.cgi?id=14502 + [BaseType (typeof (NSObject))] + partial interface SKPhysicsBody : NSSecureCoding, NSCopying { - [MacCatalyst (13, 1)] - [Static, Export ("unhide")] - SKAction Unhide (); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithBodies:")] + SKPhysicsBody FromBodies (SKPhysicsBody [] bodies); - [MacCatalyst (13, 1)] - [Static, Export ("reachTo:rootNode:duration:")] - SKAction ReachTo (CGPoint position, SKNode rootNode, double secs); + [Static, Export ("bodyWithCircleOfRadius:")] + SKPhysicsBody CreateCircularBody (nfloat radius); - [MacCatalyst (13, 1)] - [Static, Export ("reachTo:rootNode:velocity:")] - SKAction ReachTo (CGPoint position, SKNode rootNode, nfloat velocity); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithCircleOfRadius:center:")] + SKPhysicsBody CreateCircularBody (nfloat radius, CGPoint center); - [MacCatalyst (13, 1)] - [Static, Export ("reachToNode:rootNode:duration:")] - SKAction ReachToNode (SKNode node, SKNode rootNode, double sec); + [Static, Export ("bodyWithRectangleOfSize:")] + SKPhysicsBody CreateRectangularBody (CGSize size); - [MacCatalyst (13, 1)] - [Static, Export ("reachToNode:rootNode:velocity:")] - SKAction ReachToNode (SKNode node, SKNode rootNode, nfloat velocity); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithRectangleOfSize:center:")] + SKPhysicsBody CreateRectangularBody (CGSize size, CGPoint center); - [MacCatalyst (13, 1)] - [Static, Export ("strengthTo:duration:")] - SKAction StrengthTo (float /* float, not CGFloat */ strength, double sec); + [Static, Export ("bodyWithPolygonFromPath:")] + SKPhysicsBody CreateBodyFromPath (CGPath path); - [MacCatalyst (13, 1)] - [Static, Export ("strengthBy:duration:")] - SKAction StrengthBy (float /* float, not CGFloat */ strength, double sec); + [Static, Export ("bodyWithEdgeFromPoint:toPoint:")] + SKPhysicsBody CreateEdge (CGPoint fromPoint, CGPoint toPoint); - [MacCatalyst (13, 1)] - [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] - SKActionTimingFunction2 TimingFunction2 { get; set; } + [Static, Export ("bodyWithEdgeChainFromPath:")] + SKPhysicsBody CreateEdgeChain (CGPath path); - [MacCatalyst (13, 1)] - [Static, Export ("falloffBy:duration:")] - SKAction FalloffBy (float /* float, not CGFloat */ to, double duration); + [Static, Export ("bodyWithEdgeLoopFromPath:")] + SKPhysicsBody CreateEdgeLoop (CGPath path); - [MacCatalyst (13, 1)] - [Static] - [Export ("falloffTo:duration:")] - SKAction FalloffTo (float falloff, double sec); + [Static, Export ("bodyWithEdgeLoopFromRect:")] + SKPhysicsBody CreateEdgeLoop (CGRect rect); - // iOS 9 cluster - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:")] - [return: NullAllowed] - SKAction Create (string name); + [Export ("dynamic")] + bool Dynamic { [Bind ("isDynamic")] get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:duration:")] - [return: NullAllowed] - SKAction Create (string name, double duration); + [Export ("usesPreciseCollisionDetection")] + bool UsesPreciseCollisionDetection { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:fromURL:")] - [return: NullAllowed] - SKAction Create (string name, NSUrl url); + [Export ("allowsRotation")] + bool AllowsRotation { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("actionNamed:fromURL:duration:")] - [return: NullAllowed] - SKAction Create (string name, NSUrl url, double duration); + [Export ("resting")] + bool Resting { [Bind ("isResting")] get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("setNormalTexture:")] - SKAction SetNormalTexture (SKTexture texture); + [Export ("friction")] + nfloat Friction { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("setNormalTexture:resize:")] - SKAction SetNormalTexture (SKTexture texture, bool resize); + [Export ("restitution")] + nfloat Restitution { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithNormalTextures:timePerFrame:")] - SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame); + [Export ("linearDamping", ArgumentSemantic.Assign)] + nfloat LinearDamping { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithNormalTextures:timePerFrame:resize:restore:")] - SKAction AnimateWithNormalTextures (SKTexture [] textures, double secondsPerFrame, bool resize, bool restore); + [Export ("angularDamping", ArgumentSemantic.Assign)] + nfloat AngularDamping { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("play")] - SKAction CreatePlay (); + [Export ("density")] + nfloat Density { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("pause")] - SKAction CreatePause (); + [Export ("mass")] + nfloat Mass { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("stop")] - SKAction CreateStop (); + [Export ("area")] + nfloat Area { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changePlaybackRateTo:duration:")] - SKAction CreateChangePlaybackRate (float playbackRate, double duration); + [Export ("affectedByGravity", ArgumentSemantic.Assign)] + bool AffectedByGravity { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changePlaybackRateBy:duration:")] - SKAction CreateChangePlaybackRateBy (float playbackRate, double duration); + [Export ("categoryBitMask", ArgumentSemantic.Assign)] + uint CategoryBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeVolumeTo:duration:")] - SKAction CreateChangeVolume (float newVolume, double duration); + [Export ("collisionBitMask", ArgumentSemantic.Assign)] + uint CollisionBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeVolumeBy:duration:")] - SKAction CreateChangeVolumeBy (float by, double duration); + [Export ("contactTestBitMask", ArgumentSemantic.Assign)] + uint ContactTestBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeChargeTo:duration:")] - SKAction CreateChangeChargeTo (float newCharge, double duration); + [Export ("joints")] + SKPhysicsJoint [] Joints { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeChargeBy:duration:")] - SKAction CreateChangeChargeBy (float by, double duration); + [Export ("node", ArgumentSemantic.Weak)] + [NullAllowed] + SKNode Node { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeMassTo:duration:")] - SKAction CreateChangeMassTo (float newMass, double duration); + [Export ("velocity")] + CGVector Velocity { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeMassBy:duration:")] - SKAction CreateChangeMassBy (float by, double duration); + [Export ("angularVelocity")] + nfloat AngularVelocity { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("applyForce:duration:")] - SKAction CreateApplyForce (CGVector force, double duration); + [Export ("applyForce:")] + void ApplyForce (CGVector force); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyForce:atPoint:duration:")] - SKAction CreateApplyForce (CGVector force, CGPoint point, double duration); + [Export ("applyForce:atPoint:")] + void ApplyForce (CGVector force, CGPoint point); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyTorque:duration:")] - SKAction CreateApplyTorque (nfloat torque, double duration); + [Export ("applyTorque:")] + void ApplyTorque (nfloat torque); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyImpulse:duration:")] - SKAction CreateApplyImpulse (CGVector impulse, double duration); + [Export ("applyImpulse:")] + void ApplyImpulse (CGVector impulse); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyImpulse:atPoint:duration:")] - SKAction CreateApplyImpulse (CGVector impulse, CGPoint point, double duration); + [Export ("applyImpulse:atPoint:")] + void ApplyImpulse (CGVector impulse, CGPoint point); - [MacCatalyst (13, 1)] - [Static] - [Export ("applyAngularImpulse:duration:")] - SKAction CreateApplyAngularImpulse (nfloat impulse, double duration); + [Export ("applyAngularImpulse:")] + void ApplyAngularImpulse (nfloat impulse); - // SKAction_SKAudioNode inlined + [Export ("allContactedBodies")] + SKPhysicsBody [] AllContactedBodies { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("stereoPanTo:duration:")] - SKAction CreateStereoPanTo (float target, double duration); + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithTexture:size:")] + SKPhysicsBody Create (SKTexture texture, CGSize size); - [MacCatalyst (13, 1)] - [Static] - [Export ("stereoPanBy:duration:")] - SKAction CreateStereoPanBy (float by, double duration); + [MacCatalyst (13, 1)] + [Static, Export ("bodyWithTexture:alphaThreshold:size:")] + SKPhysicsBody Create (SKTexture texture, float /* float, not CGFloat */ alphaThreshold, CGSize size); - [MacCatalyst (13, 1)] - [Static] - [Export ("changeReverbTo:duration:")] - SKAction CreateChangeReverbTo (float target, double duration); + [MacCatalyst (13, 1)] + [Export ("charge")] + nfloat Charge { get; set; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeReverbBy:duration:")] - SKAction CreateChangeReverbBy (float by, double duration); + [MacCatalyst (13, 1)] + [Export ("fieldBitMask")] + uint FieldBitMask { get; set; } /* uint32_t */ - [MacCatalyst (13, 1)] - [Static] - [Export ("changeObstructionTo:duration:")] - SKAction CreateChangeObstructionTo (float target, double duration); + [MacCatalyst (13, 1)] + [Export ("pinned")] + bool Pinned { get; set; } + } + /// Encapsulates the data of a collision between two s. + /// + /// + /// Apple documentation for SKPhysicsContact [MacCatalyst (13, 1)] - [Static] - [Export ("changeObstructionBy:duration:")] - SKAction CreateChangeObstructionBy (float by, double duration); + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] // An SKPhysicsContact object is created automatically by Scene Kit + partial interface SKPhysicsContact { - [MacCatalyst (13, 1)] - [Static] - [Export ("changeOcclusionTo:duration:")] - SKAction CreateChangeOcclusionTo (float target, double duration); + [Export ("bodyA")] + SKPhysicsBody BodyA { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("changeOcclusionBy:duration:")] - SKAction CreateChangeOcclusionBy (float by, double duration); + [Export ("bodyB")] + SKPhysicsBody BodyB { get; } - // SKAction_SKWarpable + [Export ("contactPoint")] + CGPoint ContactPoint { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("warpTo:duration:")] - [return: NullAllowed] - SKAction WarpTo (SKWarpGeometry warp, double duration); + [Export ("collisionImpulse")] + nfloat CollisionImpulse { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithWarps:times:")] - [return: NullAllowed] - SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times); + [MacCatalyst (13, 1)] + [Export ("contactNormal")] + CGVector ContactNormal { get; } - [MacCatalyst (13, 1)] - [Static] - [Export ("animateWithWarps:times:restore:")] - [return: NullAllowed] - SKAction Animate (SKWarpGeometry [] warps, NSNumber [] times, bool restore); -} + } -/// -[MacCatalyst (13, 1)] -[DisableDefaultCtor] // see https://bugzilla.xamarin.com/show_bug.cgi?id=14502 -[BaseType (typeof (NSObject))] -partial interface SKPhysicsBody : NSSecureCoding, NSCopying { + /// Interface representing the required methods (if any) of the protocol . + /// + /// This interface contains the required methods (if any) from the protocol defined by . + /// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. + /// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. + /// + interface ISKPhysicsContactDelegate { } + /// [MacCatalyst (13, 1)] - [Static, Export ("bodyWithBodies:")] - SKPhysicsBody FromBodies (SKPhysicsBody [] bodies); + [BaseType (typeof (NSObject))] + [Model] + [Protocol] + partial interface SKPhysicsContactDelegate { - [Static, Export ("bodyWithCircleOfRadius:")] - SKPhysicsBody CreateCircularBody (nfloat radius); + [Export ("didBeginContact:")] + void DidBeginContact (SKPhysicsContact contact); - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithCircleOfRadius:center:")] - SKPhysicsBody CreateCircularBody (nfloat radius, CGPoint center); + [Export ("didEndContact:")] + void DidEndContact (SKPhysicsContact contact); + } - [Static, Export ("bodyWithRectangleOfSize:")] - SKPhysicsBody CreateRectangularBody (CGSize size); + /// + delegate void SKPhysicsWorldBodiesEnumeratorHandler (SKPhysicsBody body, out bool stop); + /// The delegate used for enumerating bodies that fall along a ray when used with M:SpriteKit.SKPhysicsWorld.EnumerateBodies(System.Drawing.PointF,System.Drawing.PointF,SpriteKit.SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler*. + delegate void SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler (SKPhysicsBody body, CGPoint point, CGVector normal, out bool stop); + /// [MacCatalyst (13, 1)] - [Static, Export ("bodyWithRectangleOfSize:center:")] - SKPhysicsBody CreateRectangularBody (CGSize size, CGPoint center); - - [Static, Export ("bodyWithPolygonFromPath:")] - SKPhysicsBody CreateBodyFromPath (CGPath path); - - [Static, Export ("bodyWithEdgeFromPoint:toPoint:")] - SKPhysicsBody CreateEdge (CGPoint fromPoint, CGPoint toPoint); + [BaseType (typeof (NSObject), + Delegates = new string [] { "WeakContactDelegate" }, + Events = new Type [] { typeof (SKPhysicsContactDelegate) })] + [DisableDefaultCtor] // You do not create SKPhysicsWorld objects directly; instead, read the physicsWorld property of an SKScene object. + partial interface SKPhysicsWorld : NSSecureCoding { - [Static, Export ("bodyWithEdgeChainFromPath:")] - SKPhysicsBody CreateEdgeChain (CGPath path); + [Export ("gravity")] + CGVector Gravity { get; set; } - [Static, Export ("bodyWithEdgeLoopFromPath:")] - SKPhysicsBody CreateEdgeLoop (CGPath path); + [Export ("speed")] + nfloat Speed { get; set; } - [Static, Export ("bodyWithEdgeLoopFromRect:")] - SKPhysicsBody CreateEdgeLoop (CGRect rect); + [Export ("contactDelegate", ArgumentSemantic.Assign), NullAllowed] + NSObject WeakContactDelegate { get; set; } - [Export ("dynamic")] - bool Dynamic { [Bind ("isDynamic")] get; set; } + [Wrap ("WeakContactDelegate")] + ISKPhysicsContactDelegate ContactDelegate { get; set; } - [Export ("usesPreciseCollisionDetection")] - bool UsesPreciseCollisionDetection { get; set; } + [Export ("addJoint:")] + void AddJoint (SKPhysicsJoint joint); - [Export ("allowsRotation")] - bool AllowsRotation { get; set; } + [Export ("removeJoint:")] + void RemoveJoint (SKPhysicsJoint joint); - [Export ("resting")] - bool Resting { [Bind ("isResting")] get; set; } + [Export ("removeAllJoints")] + void RemoveAllJoints (); - [Export ("friction")] - nfloat Friction { get; set; } + [Export ("bodyAtPoint:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGPoint point); - [Export ("restitution")] - nfloat Restitution { get; set; } + [Export ("bodyInRect:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGRect rect); - [Export ("linearDamping", ArgumentSemantic.Assign)] - nfloat LinearDamping { get; set; } + [Export ("bodyAlongRayStart:end:")] + [return: NullAllowed] + SKPhysicsBody GetBody (CGPoint rayStart, CGPoint rayEnd); - [Export ("angularDamping", ArgumentSemantic.Assign)] - nfloat AngularDamping { get; set; } + [Export ("enumerateBodiesAtPoint:usingBlock:")] + void EnumerateBodies (CGPoint point, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); - [Export ("density")] - nfloat Density { get; set; } + [Export ("enumerateBodiesInRect:usingBlock:")] + void EnumerateBodies (CGRect rect, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); - [Export ("mass")] - nfloat Mass { get; set; } + [Export ("enumerateBodiesAlongRayStart:end:usingBlock:")] + void EnumerateBodies (CGPoint start, CGPoint end, SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler enumeratorHandler); - [Export ("area")] - nfloat Area { get; } - - [Export ("affectedByGravity", ArgumentSemantic.Assign)] - bool AffectedByGravity { get; set; } + // + // iOS 8 + // + [MacCatalyst (13, 1)] + [Export ("sampleFieldsAt:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector3 SampleFields (/* vector_float3 */ Vector3 position); + } - [Export ("categoryBitMask", ArgumentSemantic.Assign)] - uint CategoryBitMask { get; set; } /* uint32_t */ + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [Abstract] // You never instantiate objects of this class directly + partial interface SKPhysicsJoint : NSSecureCoding { - [Export ("collisionBitMask", ArgumentSemantic.Assign)] - uint CollisionBitMask { get; set; } /* uint32_t */ + [Export ("bodyA", ArgumentSemantic.Retain)] + SKPhysicsBody BodyA { get; set; } - [Export ("contactTestBitMask", ArgumentSemantic.Assign)] - uint ContactTestBitMask { get; set; } /* uint32_t */ + [Export ("bodyB", ArgumentSemantic.Retain)] + SKPhysicsBody BodyB { get; set; } - [Export ("joints")] - SKPhysicsJoint [] Joints { get; } + [MacCatalyst (13, 1)] + [Export ("reactionForce")] + CGVector ReactionForce { get; } - [Export ("node", ArgumentSemantic.Weak)] - [NullAllowed] - SKNode Node { get; } + [MacCatalyst (13, 1)] + [Export ("reactionTorque")] + nfloat ReactionTorque { get; } + } - [Export ("velocity")] - CGVector Velocity { get; set; } + /// A that pins two bodies to a common point. + /// + /// Apple documentation for SKPhysicsJointPin + [MacCatalyst (13, 1)] + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchor` using the default ctor (see #14511) + partial interface SKPhysicsJointPin { - [Export ("angularVelocity")] - nfloat AngularVelocity { get; set; } + [Static, Export ("jointWithBodyA:bodyB:anchor:")] + SKPhysicsJointPin Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); - [Export ("applyForce:")] - void ApplyForce (CGVector force); + [Export ("shouldEnableLimits")] + bool ShouldEnableLimits { get; set; } - [Export ("applyForce:atPoint:")] - void ApplyForce (CGVector force, CGPoint point); + [Export ("lowerAngleLimit")] + nfloat LowerAngleLimit { get; set; } - [Export ("applyTorque:")] - void ApplyTorque (nfloat torque); + [Export ("upperAngleLimit")] + nfloat UpperAngleLimit { get; set; } - [Export ("applyImpulse:")] - void ApplyImpulse (CGVector impulse); + [Export ("frictionTorque")] + nfloat FrictionTorque { get; set; } - [Export ("applyImpulse:atPoint:")] - void ApplyImpulse (CGVector impulse, CGPoint point); + [MacCatalyst (13, 1)] + [Export ("rotationSpeed")] + nfloat RotationSpeed { get; set; } + } - [Export ("applyAngularImpulse:")] - void ApplyAngularImpulse (nfloat impulse); + /// A that connects two bodies as if by a spring. + /// + /// Apple documentation for SKPhysicsJointSpring + [MacCatalyst (13, 1)] + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) + partial interface SKPhysicsJointSpring { - [Export ("allContactedBodies")] - SKPhysicsBody [] AllContactedBodies { get; } + [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] + SKPhysicsJointSpring Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); - // - // iOS 8 - // - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithTexture:size:")] - SKPhysicsBody Create (SKTexture texture, CGSize size); + [Export ("damping")] + nfloat Damping { get; set; } - [MacCatalyst (13, 1)] - [Static, Export ("bodyWithTexture:alphaThreshold:size:")] - SKPhysicsBody Create (SKTexture texture, float /* float, not CGFloat */ alphaThreshold, CGSize size); + [Export ("frequency")] + nfloat Frequency { get; set; } + } + /// A that rigidly connects two bodies. + /// + /// At least one of the s must have its property set to or this will not behave properly. + /// + /// Apple documentation for SKPhysicsJointFixed [MacCatalyst (13, 1)] - [Export ("charge")] - nfloat Charge { get; set; } + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // https://bugzilla.xamarin.com/show_bug.cgi?id=14511 + partial interface SKPhysicsJointFixed { - [MacCatalyst (13, 1)] - [Export ("fieldBitMask")] - uint FieldBitMask { get; set; } /* uint32_t */ + [Static, Export ("jointWithBodyA:bodyB:anchor:")] + SKPhysicsJointFixed Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); + } + /// A that connects two bodies as if by a sliding rod. + /// + /// Apple documentation for SKPhysicsJointSliding [MacCatalyst (13, 1)] - [Export ("pinned")] - bool Pinned { get; set; } -} + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchor` and `axis` using the default ctor (see #14511) + partial interface SKPhysicsJointSliding { -/// Encapsulates the data of a collision between two s. -/// -/// -/// Apple documentation for SKPhysicsContact -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] // An SKPhysicsContact object is created automatically by Scene Kit -partial interface SKPhysicsContact { + [Static, Export ("jointWithBodyA:bodyB:anchor:axis:")] + SKPhysicsJointSliding Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor, CGVector axis); - [Export ("bodyA")] - SKPhysicsBody BodyA { get; } + [Export ("shouldEnableLimits")] + bool ShouldEnableLimits { get; set; } - [Export ("bodyB")] - SKPhysicsBody BodyB { get; } + [Export ("lowerDistanceLimit")] + nfloat LowerDistanceLimit { get; set; } - [Export ("contactPoint")] - CGPoint ContactPoint { get; } - - [Export ("collisionImpulse")] - nfloat CollisionImpulse { get; } + [Export ("upperDistanceLimit")] + nfloat UpperDistanceLimit { get; set; } + } + /// A that connects two bodies as if by a rope. + /// + /// Apple documentation for SKPhysicsJointLimit [MacCatalyst (13, 1)] - [Export ("contactNormal")] - CGVector ContactNormal { get; } + [BaseType (typeof (SKPhysicsJoint))] + [DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) + partial interface SKPhysicsJointLimit { -} + [Export ("maxLength")] + nfloat MaxLength { get; set; } -/// Interface representing the required methods (if any) of the protocol . -/// -/// This interface contains the required methods (if any) from the protocol defined by . -/// If developers create classes that implement this interface, the implementation methods will automatically be exported to Objective-C with the matching signature from the method defined in the protocol. -/// Optional methods (if any) are provided by the class as extension methods to the interface, allowing developers to invoke any optional methods on the protocol. -/// -interface ISKPhysicsContactDelegate { } - -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[Model] -[Protocol] -partial interface SKPhysicsContactDelegate { - - [Export ("didBeginContact:")] - void DidBeginContact (SKPhysicsContact contact); - - [Export ("didEndContact:")] - void DidEndContact (SKPhysicsContact contact); -} + [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] + SKPhysicsJointLimit Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); + } -/// -delegate void SKPhysicsWorldBodiesEnumeratorHandler (SKPhysicsBody body, out bool stop); -/// The delegate used for enumerating bodies that fall along a ray when used with M:SpriteKit.SKPhysicsWorld.EnumerateBodies(System.Drawing.PointF,System.Drawing.PointF,SpriteKit.SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler*. -delegate void SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler (SKPhysicsBody body, CGPoint point, CGVector normal, out bool stop); + /// Defines a range for acceptable float values. + /// + /// Apple documentation for SKRange + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKRange : NSSecureCoding, NSCopying { + [DesignatedInitializer] + [Export ("initWithLowerLimit:upperLimit:")] + NativeHandle Constructor (nfloat lowerLimit, nfloat upperLimier); -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject), - Delegates = new string [] { "WeakContactDelegate" }, - Events = new Type [] { typeof (SKPhysicsContactDelegate) })] -[DisableDefaultCtor] // You do not create SKPhysicsWorld objects directly; instead, read the physicsWorld property of an SKScene object. -partial interface SKPhysicsWorld : NSSecureCoding { + [Export ("lowerLimit")] + nfloat LowerLimit { get; set; } - [Export ("gravity")] - CGVector Gravity { get; set; } + [Export ("upperLimit")] + nfloat UpperLimit { get; set; } - [Export ("speed")] - nfloat Speed { get; set; } + [Static, Export ("rangeWithLowerLimit:upperLimit:")] + SKRange Create (nfloat lower, nfloat upper); - [Export ("contactDelegate", ArgumentSemantic.Assign), NullAllowed] - NSObject WeakContactDelegate { get; set; } + [Static, Export ("rangeWithLowerLimit:")] + SKRange CreateWithLowerLimit (nfloat lower); - [Wrap ("WeakContactDelegate")] - ISKPhysicsContactDelegate ContactDelegate { get; set; } + [Static, Export ("rangeWithUpperLimit:")] + SKRange CreateWithUpperLimit (nfloat upper); - [Export ("addJoint:")] - void AddJoint (SKPhysicsJoint joint); + [Static, Export ("rangeWithConstantValue:")] + SKRange CreateConstant (nfloat value); - [Export ("removeJoint:")] - void RemoveJoint (SKPhysicsJoint joint); + [Static, Export ("rangeWithValue:variance:")] + SKRange CreateWithVariance (nfloat value, nfloat variance); - [Export ("removeAllJoints")] - void RemoveAllJoints (); + [Static, Export ("rangeWithNoLimits")] + SKRange CreateUnlimited (); + } - [Export ("bodyAtPoint:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGPoint point); + /// A that holds audio information. + /// + /// Apple documentation for SKAudioNode + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + [DisableDefaultCtor] + interface SKAudioNode : NSSecureCoding { + [Export ("initWithAVAudioNode:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] AVAudioNode node); - [Export ("bodyInRect:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGRect rect); + [Export ("initWithFileNamed:")] + NativeHandle Constructor (string fileName); - [Export ("bodyAlongRayStart:end:")] - [return: NullAllowed] - SKPhysicsBody GetBody (CGPoint rayStart, CGPoint rayEnd); + [Export ("initWithURL:")] + NativeHandle Constructor (NSUrl url); - [Export ("enumerateBodiesAtPoint:usingBlock:")] - void EnumerateBodies (CGPoint point, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + [NullAllowed, Export ("avAudioNode", ArgumentSemantic.Retain)] + AVAudioNode AvAudioNode { get; set; } - [Export ("enumerateBodiesInRect:usingBlock:")] - void EnumerateBodies (CGRect rect, SKPhysicsWorldBodiesEnumeratorHandler enumeratorHandler); + [Export ("autoplayLooped")] + bool AutoplayLooped { get; set; } - [Export ("enumerateBodiesAlongRayStart:end:usingBlock:")] - void EnumerateBodies (CGPoint start, CGPoint end, SKPhysicsWorldBodiesAlongRayStartEnumeratorHandler enumeratorHandler); + [Export ("positional")] + bool Positional { [Bind ("isPositional")] get; set; } + } - // - // iOS 8 - // + /// A node that specifies the position inside a from which it can be rendered. + /// + /// Apple documentation for SKCameraNode [MacCatalyst (13, 1)] - [Export ("sampleFieldsAt:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector3 SampleFields (/* vector_float3 */ Vector3 position); -} - -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[Abstract] // You never instantiate objects of this class directly -partial interface SKPhysicsJoint : NSSecureCoding { - - [Export ("bodyA", ArgumentSemantic.Retain)] - SKPhysicsBody BodyA { get; set; } - - [Export ("bodyB", ArgumentSemantic.Retain)] - SKPhysicsBody BodyB { get; set; } + [BaseType (typeof (SKNode))] + interface SKCameraNode { + [Export ("containsNode:")] + bool Contains (SKNode node); - [MacCatalyst (13, 1)] - [Export ("reactionForce")] - CGVector ReactionForce { get; } + [Export ("containedNodeSet")] + NSSet ContainedNodeSet { get; } + } + /// A that holds an archived collection of child nodes that can be used in multiple places throughout the game. + /// + /// Apple documentation for SKReferenceNode [MacCatalyst (13, 1)] - [Export ("reactionTorque")] - nfloat ReactionTorque { get; } -} - -/// A that pins two bodies to a common point. -/// -/// Apple documentation for SKPhysicsJointPin -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchor` using the default ctor (see #14511) -partial interface SKPhysicsJointPin { + [BaseType (typeof (SKNode))] + [DisableDefaultCtor] + interface SKReferenceNode { + [Export ("initWithURL:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] NSUrl url); - [Static, Export ("jointWithBodyA:bodyB:anchor:")] - SKPhysicsJointPin Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); + [Export ("initWithFileNamed:")] + [DesignatedInitializer] + NativeHandle Constructor ([NullAllowed] string fileName); - [Export ("shouldEnableLimits")] - bool ShouldEnableLimits { get; set; } + [Static] + [Export ("referenceNodeWithFileNamed:")] + SKReferenceNode FromFile (string fileName); - [Export ("lowerAngleLimit")] - nfloat LowerAngleLimit { get; set; } + [Static] + [Export ("referenceNodeWithURL:")] + SKReferenceNode FromUrl (NSUrl referenceUrl); - [Export ("upperAngleLimit")] - nfloat UpperAngleLimit { get; set; } + [Export ("didLoadReferenceNode:")] + void DidLoadReferenceNode ([NullAllowed] SKNode node); - [Export ("frictionTorque")] - nfloat FrictionTorque { get; set; } + [Export ("resolveReferenceNode")] + void Resolve (); + } + /// Holds per-node data to be used with a custom shader. + /// + /// Apple documentation for SKAttribute [MacCatalyst (13, 1)] - [Export ("rotationSpeed")] - nfloat RotationSpeed { get; set; } -} - -/// A that connects two bodies as if by a spring. -/// -/// Apple documentation for SKPhysicsJointSpring -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) -partial interface SKPhysicsJointSpring { + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + interface SKAttribute : NSSecureCoding { + [Static] + [Export ("attributeWithName:type:")] + SKAttribute Create (string name, SKAttributeType type); - [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] - SKPhysicsJointSpring Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); - - [Export ("damping")] - nfloat Damping { get; set; } - - [Export ("frequency")] - nfloat Frequency { get; set; } -} - -/// A that rigidly connects two bodies. -/// -/// At least one of the s must have its property set to or this will not behave properly. -/// -/// Apple documentation for SKPhysicsJointFixed -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // https://bugzilla.xamarin.com/show_bug.cgi?id=14511 -partial interface SKPhysicsJointFixed { - - [Static, Export ("jointWithBodyA:bodyB:anchor:")] - SKPhysicsJointFixed Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor); -} - -/// A that connects two bodies as if by a sliding rod. -/// -/// Apple documentation for SKPhysicsJointSliding -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchor` and `axis` using the default ctor (see #14511) -partial interface SKPhysicsJointSliding { - - [Static, Export ("jointWithBodyA:bodyB:anchor:axis:")] - SKPhysicsJointSliding Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchor, CGVector axis); + [Export ("initWithName:type:")] + [DesignatedInitializer] + NativeHandle Constructor (string name, SKAttributeType type); - [Export ("shouldEnableLimits")] - bool ShouldEnableLimits { get; set; } + [Export ("name")] + string Name { get; } - [Export ("lowerDistanceLimit")] - nfloat LowerDistanceLimit { get; set; } + [Export ("type")] + SKAttributeType Type { get; } + } - [Export ("upperDistanceLimit")] - nfloat UpperDistanceLimit { get; set; } -} + /// Holds the value, of the appropriate , for an . + /// + /// Apple documentation for SKAttributeValue + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] // DesignatedInitializer below + interface SKAttributeValue : NSSecureCoding { + [DesignatedInitializer] + [Export ("init")] + NativeHandle Constructor (); -/// A that connects two bodies as if by a rope. -/// -/// Apple documentation for SKPhysicsJointLimit -[MacCatalyst (13, 1)] -[BaseType (typeof (SKPhysicsJoint))] -[DisableDefaultCtor] // impossible to set the `anchorA` and `anchorB` using the default ctor (see #14511) -partial interface SKPhysicsJointLimit { + [Static] + [Export ("valueWithFloat:")] + SKAttributeValue Create (float value); - [Export ("maxLength")] - nfloat MaxLength { get; set; } + [Static] + [Export ("valueWithVectorFloat2:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKAttributeValue Create (Vector2 value); - [Static, Export ("jointWithBodyA:bodyB:anchorA:anchorB:")] - SKPhysicsJointLimit Create (SKPhysicsBody bodyA, SKPhysicsBody bodyB, CGPoint anchorA, CGPoint anchorB); -} + [Static] + [Export ("valueWithVectorFloat3:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKAttributeValue Create (Vector3 value); -/// Defines a range for acceptable float values. -/// -/// Apple documentation for SKRange -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKRange : NSSecureCoding, NSCopying { - [DesignatedInitializer] - [Export ("initWithLowerLimit:upperLimit:")] - NativeHandle Constructor (nfloat lowerLimit, nfloat upperLimier); + [Static] + [Export ("valueWithVectorFloat4:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + SKAttributeValue Create (Vector4 value); + + [Export ("floatValue")] + float FloatValue { get; set; } + + [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] + Vector2 VectorFloat2Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] + Vector3 VectorFloat3Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] + Vector4 VectorFloat4Value { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + } - [Export ("lowerLimit")] - nfloat LowerLimit { get; set; } + /// A single kind of tile in a tile map. + /// + /// Apple documentation for SKTileDefinition + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + interface SKTileDefinition : NSCopying, NSSecureCoding { + [Static] + [Export ("tileDefinitionWithTexture:")] + SKTileDefinition Create (SKTexture texture); - [Export ("upperLimit")] - nfloat UpperLimit { get; set; } + [Static] + [Export ("tileDefinitionWithTexture:size:")] + SKTileDefinition Create (SKTexture texture, CGSize size); - [Static, Export ("rangeWithLowerLimit:upperLimit:")] - SKRange Create (nfloat lower, nfloat upper); + [Static] + [Export ("tileDefinitionWithTexture:normalTexture:size:")] + SKTileDefinition Create (SKTexture texture, SKTexture normalTexture, CGSize size); - [Static, Export ("rangeWithLowerLimit:")] - SKRange CreateWithLowerLimit (nfloat lower); + [Static] + [Export ("tileDefinitionWithTextures:size:timePerFrame:")] + SKTileDefinition Create (SKTexture [] textures, CGSize size, nfloat timePerFrame); - [Static, Export ("rangeWithUpperLimit:")] - SKRange CreateWithUpperLimit (nfloat upper); + [Static] + [Export ("tileDefinitionWithTextures:normalTextures:size:timePerFrame:")] + SKTileDefinition Create (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); - [Static, Export ("rangeWithConstantValue:")] - SKRange CreateConstant (nfloat value); + [Export ("initWithTexture:")] + NativeHandle Constructor (SKTexture texture); - [Static, Export ("rangeWithValue:variance:")] - SKRange CreateWithVariance (nfloat value, nfloat variance); + [Export ("initWithTexture:size:")] + NativeHandle Constructor (SKTexture texture, CGSize size); - [Static, Export ("rangeWithNoLimits")] - SKRange CreateUnlimited (); -} + [Export ("initWithTexture:normalTexture:size:")] + NativeHandle Constructor (SKTexture texture, SKTexture normalTexture, CGSize size); -/// A that holds audio information. -/// -/// Apple documentation for SKAudioNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -[DisableDefaultCtor] -interface SKAudioNode : NSSecureCoding { - [Export ("initWithAVAudioNode:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] AVAudioNode node); + [Export ("initWithTextures:size:timePerFrame:")] + NativeHandle Constructor (SKTexture [] textures, CGSize size, nfloat timePerFrame); - [Export ("initWithFileNamed:")] - NativeHandle Constructor (string fileName); + [Export ("initWithTextures:normalTextures:size:timePerFrame:")] + NativeHandle Constructor (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); - [Export ("initWithURL:")] - NativeHandle Constructor (NSUrl url); + [Export ("textures", ArgumentSemantic.Copy)] + SKTexture [] Textures { get; set; } - [NullAllowed, Export ("avAudioNode", ArgumentSemantic.Retain)] - AVAudioNode AvAudioNode { get; set; } + [Export ("normalTextures", ArgumentSemantic.Copy)] + SKTexture [] NormalTextures { get; set; } - [Export ("autoplayLooped")] - bool AutoplayLooped { get; set; } + [NullAllowed, Export ("userData", ArgumentSemantic.Retain)] + NSMutableDictionary UserData { get; set; } - [Export ("positional")] - bool Positional { [Bind ("isPositional")] get; set; } -} + [NullAllowed, Export ("name")] + string Name { get; set; } -/// A node that specifies the position inside a from which it can be rendered. -/// -/// Apple documentation for SKCameraNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKCameraNode { - [Export ("containsNode:")] - bool Contains (SKNode node); - - [Export ("containedNodeSet")] - NSSet ContainedNodeSet { get; } -} + [Export ("size", ArgumentSemantic.Assign)] + CGSize Size { get; set; } -/// A that holds an archived collection of child nodes that can be used in multiple places throughout the game. -/// -/// Apple documentation for SKReferenceNode -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -[DisableDefaultCtor] -interface SKReferenceNode { - [Export ("initWithURL:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] NSUrl url); - - [Export ("initWithFileNamed:")] - [DesignatedInitializer] - NativeHandle Constructor ([NullAllowed] string fileName); - - [Static] - [Export ("referenceNodeWithFileNamed:")] - SKReferenceNode FromFile (string fileName); - - [Static] - [Export ("referenceNodeWithURL:")] - SKReferenceNode FromUrl (NSUrl referenceUrl); - - [Export ("didLoadReferenceNode:")] - void DidLoadReferenceNode ([NullAllowed] SKNode node); - - [Export ("resolveReferenceNode")] - void Resolve (); -} + [Export ("timePerFrame")] + nfloat TimePerFrame { get; set; } -/// Holds per-node data to be used with a custom shader. -/// -/// Apple documentation for SKAttribute -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -interface SKAttribute : NSSecureCoding { - [Static] - [Export ("attributeWithName:type:")] - SKAttribute Create (string name, SKAttributeType type); - - [Export ("initWithName:type:")] - [DesignatedInitializer] - NativeHandle Constructor (string name, SKAttributeType type); - - [Export ("name")] - string Name { get; } - - [Export ("type")] - SKAttributeType Type { get; } -} + [Export ("placementWeight")] + nuint PlacementWeight { get; set; } -/// Holds the value, of the appropriate , for an . -/// -/// Apple documentation for SKAttributeValue -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] // DesignatedInitializer below -interface SKAttributeValue : NSSecureCoding { - [DesignatedInitializer] - [Export ("init")] - NativeHandle Constructor (); - - [Static] - [Export ("valueWithFloat:")] - SKAttributeValue Create (float value); - - [Static] - [Export ("valueWithVectorFloat2:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector2 value); - - [Static] - [Export ("valueWithVectorFloat3:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector3 value); - - [Static] - [Export ("valueWithVectorFloat4:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - SKAttributeValue Create (Vector4 value); - - [Export ("floatValue")] - float FloatValue { get; set; } - - [Export ("vectorFloat2Value", ArgumentSemantic.Assign)] - Vector2 VectorFloat2Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [Export ("rotation", ArgumentSemantic.Assign)] + SKTileDefinitionRotation Rotation { get; set; } - [Export ("vectorFloat3Value", ArgumentSemantic.Assign)] - Vector3 VectorFloat3Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [Export ("flipVertically")] + bool FlipVertically { get; set; } - [Export ("vectorFloat4Value", ArgumentSemantic.Assign)] - Vector4 VectorFloat4Value { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; + [Export ("flipHorizontally")] + bool FlipHorizontally { get; set; } } -} - -/// A single kind of tile in a tile map. -/// -/// Apple documentation for SKTileDefinition -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -interface SKTileDefinition : NSCopying, NSSecureCoding { - [Static] - [Export ("tileDefinitionWithTexture:")] - SKTileDefinition Create (SKTexture texture); - - [Static] - [Export ("tileDefinitionWithTexture:size:")] - SKTileDefinition Create (SKTexture texture, CGSize size); - - [Static] - [Export ("tileDefinitionWithTexture:normalTexture:size:")] - SKTileDefinition Create (SKTexture texture, SKTexture normalTexture, CGSize size); - - [Static] - [Export ("tileDefinitionWithTextures:size:timePerFrame:")] - SKTileDefinition Create (SKTexture [] textures, CGSize size, nfloat timePerFrame); - [Static] - [Export ("tileDefinitionWithTextures:normalTextures:size:timePerFrame:")] - SKTileDefinition Create (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); - - [Export ("initWithTexture:")] - NativeHandle Constructor (SKTexture texture); + /// + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + interface SKTileMapNode : NSCopying, NSSecureCoding { + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); - [Export ("initWithTexture:size:")] - NativeHandle Constructor (SKTexture texture, CGSize size); + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); - [Export ("initWithTexture:normalTexture:size:")] - NativeHandle Constructor (SKTexture texture, SKTexture normalTexture, CGSize size); + [Static] + [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:tileGroupLayout:")] + SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); - [Export ("initWithTextures:size:timePerFrame:")] - NativeHandle Constructor (SKTexture [] textures, CGSize size, nfloat timePerFrame); + [Export ("initWithTileSet:columns:rows:tileSize:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); - [Export ("initWithTextures:normalTextures:size:timePerFrame:")] - NativeHandle Constructor (SKTexture [] textures, SKTexture [] normalTextures, CGSize size, nfloat timePerFrame); + [Export ("initWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); - [Export ("textures", ArgumentSemantic.Copy)] - SKTexture [] Textures { get; set; } + [Export ("initWithTileSet:columns:rows:tileSize:tileGroupLayout:")] + NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); - [Export ("normalTextures", ArgumentSemantic.Copy)] - SKTexture [] NormalTextures { get; set; } + [Export ("numberOfColumns")] + nuint NumberOfColumns { get; set; } - [NullAllowed, Export ("userData", ArgumentSemantic.Retain)] - NSMutableDictionary UserData { get; set; } + [Export ("numberOfRows")] + nuint NumberOfRows { get; set; } - [NullAllowed, Export ("name")] - string Name { get; set; } + [Export ("tileSize", ArgumentSemantic.Assign)] + CGSize TileSize { get; set; } - [Export ("size", ArgumentSemantic.Assign)] - CGSize Size { get; set; } + [Export ("mapSize")] + CGSize MapSize { get; } - [Export ("timePerFrame")] - nfloat TimePerFrame { get; set; } + [Export ("tileSet", ArgumentSemantic.Assign)] + SKTileSet TileSet { get; set; } - [Export ("placementWeight")] - nuint PlacementWeight { get; set; } + [Export ("colorBlendFactor")] + nfloat ColorBlendFactor { get; set; } - [Export ("rotation", ArgumentSemantic.Assign)] - SKTileDefinitionRotation Rotation { get; set; } + [Export ("color", ArgumentSemantic.Retain)] + UIColor Color { get; set; } - [Export ("flipVertically")] - bool FlipVertically { get; set; } + [Export ("blendMode", ArgumentSemantic.Assign)] + SKBlendMode BlendMode { get; set; } - [Export ("flipHorizontally")] - bool FlipHorizontally { get; set; } -} + [Export ("anchorPoint", ArgumentSemantic.Assign)] + CGPoint AnchorPoint { get; set; } -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKTileMapNode : NSCopying, NSSecureCoding { - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); + [NullAllowed, Export ("shader", ArgumentSemantic.Retain)] + SKShader Shader { get; set; } - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); + [Export ("lightingBitMask")] + uint LightingBitMask { get; set; } - [Static] - [Export ("tileMapNodeWithTileSet:columns:rows:tileSize:tileGroupLayout:")] - SKTileMapNode Create (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); + [Export ("enableAutomapping")] + bool EnableAutomapping { get; set; } - [Export ("initWithTileSet:columns:rows:tileSize:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize); + [Export ("fillWithTileGroup:")] + void Fill ([NullAllowed] SKTileGroup tileGroup); - [Export ("initWithTileSet:columns:rows:tileSize:fillWithTileGroup:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup tileGroup); + [Export ("tileDefinitionAtColumn:row:")] + [return: NullAllowed] + SKTileDefinition GetTileDefinition (nuint column, nuint row); - [Export ("initWithTileSet:columns:rows:tileSize:tileGroupLayout:")] - NativeHandle Constructor (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, SKTileGroup [] tileGroupLayout); + [Export ("tileGroupAtColumn:row:")] + [return: NullAllowed] + SKTileGroup GetTileGroup (nuint column, nuint row); - [Export ("numberOfColumns")] - nuint NumberOfColumns { get; set; } + [Export ("setTileGroup:forColumn:row:")] + void SetTileGroup ([NullAllowed] SKTileGroup tileGroup, nuint column, nuint row); - [Export ("numberOfRows")] - nuint NumberOfRows { get; set; } + [Export ("setTileGroup:andTileDefinition:forColumn:row:")] + void SetTileGroup (SKTileGroup tileGroup, SKTileDefinition tileDefinition, nuint column, nuint row); - [Export ("tileSize", ArgumentSemantic.Assign)] - CGSize TileSize { get; set; } + [Export ("tileColumnIndexFromPosition:")] + nuint GetTileColumnIndex (CGPoint position); - [Export ("mapSize")] - CGSize MapSize { get; } + [Export ("tileRowIndexFromPosition:")] + nuint GetTileRowIndex (CGPoint position); - [Export ("tileSet", ArgumentSemantic.Assign)] - SKTileSet TileSet { get; set; } + [Export ("centerOfTileAtColumn:row:")] + CGPoint GetCenterOfTile (nuint column, nuint row); - [Export ("colorBlendFactor")] - nfloat ColorBlendFactor { get; set; } + // Static Category from GameplayKit + [MacCatalyst (13, 1)] + [Static] + [Export ("tileMapNodesWithTileSet:columns:rows:tileSize:fromNoiseMap:tileTypeNoiseMapThresholds:")] + SKTileMapNode [] FromTileSet (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, GKNoiseMap noiseMap, NSNumber [] thresholds); - [Export ("color", ArgumentSemantic.Retain)] - UIColor Color { get; set; } + [Export ("attributeValues", ArgumentSemantic.Copy)] + NSDictionary AttributeValues { get; set; } - [Export ("blendMode", ArgumentSemantic.Assign)] - SKBlendMode BlendMode { get; set; } + [Export ("valueForAttributeNamed:")] + [return: NullAllowed] + SKAttributeValue GetValue (string key); - [Export ("anchorPoint", ArgumentSemantic.Assign)] - CGPoint AnchorPoint { get; set; } + [Export ("setValue:forAttributeNamed:")] + void SetValue (SKAttributeValue value, string key); + } - [NullAllowed, Export ("shader", ArgumentSemantic.Retain)] - SKShader Shader { get; set; } + /// Represents the possible elements of a in the form of objects. + /// + /// An collects a set of related objects that may be placed on a . Additionally, it may define a default tile group and tile size. + /// + /// Apple documentation for SKTileSet + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKTileSet : NSCopying, NSSecureCoding { + [Static] + [Export ("tileSetWithTileGroups:")] + SKTileSet Create (SKTileGroup [] tileGroups); - [Export ("lightingBitMask")] - uint LightingBitMask { get; set; } + [Static] + [Export ("tileSetWithTileGroups:tileSetType:")] + SKTileSet Create (SKTileGroup [] tileGroups, SKTileSetType tileSetType); - [Export ("enableAutomapping")] - bool EnableAutomapping { get; set; } + [Export ("initWithTileGroups:")] + NativeHandle Constructor (SKTileGroup [] tileGroups); - [Export ("fillWithTileGroup:")] - void Fill ([NullAllowed] SKTileGroup tileGroup); + [Export ("initWithTileGroups:tileSetType:")] + NativeHandle Constructor (SKTileGroup [] tileGroups, SKTileSetType tileSetType); - [Export ("tileDefinitionAtColumn:row:")] - [return: NullAllowed] - SKTileDefinition GetTileDefinition (nuint column, nuint row); + [Static] + [Export ("tileSetNamed:")] + [return: NullAllowed] + SKTileSet FromName (string name); - [Export ("tileGroupAtColumn:row:")] - [return: NullAllowed] - SKTileGroup GetTileGroup (nuint column, nuint row); + [Static] + [Export ("tileSetFromURL:")] + [return: NullAllowed] + SKTileSet FromUrl (NSUrl url); - [Export ("setTileGroup:forColumn:row:")] - void SetTileGroup ([NullAllowed] SKTileGroup tileGroup, nuint column, nuint row); + [Export ("tileGroups", ArgumentSemantic.Copy)] + SKTileGroup [] TileGroups { get; set; } - [Export ("setTileGroup:andTileDefinition:forColumn:row:")] - void SetTileGroup (SKTileGroup tileGroup, SKTileDefinition tileDefinition, nuint column, nuint row); + [NullAllowed, Export ("name")] + string Name { get; set; } - [Export ("tileColumnIndexFromPosition:")] - nuint GetTileColumnIndex (CGPoint position); + [Export ("type", ArgumentSemantic.Assign)] + SKTileSetType Type { get; set; } - [Export ("tileRowIndexFromPosition:")] - nuint GetTileRowIndex (CGPoint position); + [NullAllowed, Export ("defaultTileGroup", ArgumentSemantic.Assign)] + SKTileGroup DefaultTileGroup { get; set; } - [Export ("centerOfTileAtColumn:row:")] - CGPoint GetCenterOfTile (nuint column, nuint row); + [Export ("defaultTileSize", ArgumentSemantic.Assign)] + CGSize DefaultTileSize { get; set; } + } - // Static Category from GameplayKit + /// [MacCatalyst (13, 1)] - [Static] - [Export ("tileMapNodesWithTileSet:columns:rows:tileSize:fromNoiseMap:tileTypeNoiseMapThresholds:")] - SKTileMapNode [] FromTileSet (SKTileSet tileSet, nuint columns, nuint rows, CGSize tileSize, GKNoiseMap noiseMap, NSNumber [] thresholds); - - [Export ("attributeValues", ArgumentSemantic.Copy)] - NSDictionary AttributeValues { get; set; } - - [Export ("valueForAttributeNamed:")] - [return: NullAllowed] - SKAttributeValue GetValue (string key); - - [Export ("setValue:forAttributeNamed:")] - void SetValue (SKAttributeValue value, string key); -} - -/// Represents the possible elements of a in the form of objects. -/// -/// An collects a set of related objects that may be placed on a . Additionally, it may define a default tile group and tile size. -/// -/// Apple documentation for SKTileSet -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKTileSet : NSCopying, NSSecureCoding { - [Static] - [Export ("tileSetWithTileGroups:")] - SKTileSet Create (SKTileGroup [] tileGroups); - - [Static] - [Export ("tileSetWithTileGroups:tileSetType:")] - SKTileSet Create (SKTileGroup [] tileGroups, SKTileSetType tileSetType); - - [Export ("initWithTileGroups:")] - NativeHandle Constructor (SKTileGroup [] tileGroups); - - [Export ("initWithTileGroups:tileSetType:")] - NativeHandle Constructor (SKTileGroup [] tileGroups, SKTileSetType tileSetType); + [BaseType (typeof (NSObject))] + interface SKTileGroup : NSCopying, NSSecureCoding { + [Static] + [Export ("tileGroupWithTileDefinition:")] + SKTileGroup Create (SKTileDefinition tileDefinition); - [Static] - [Export ("tileSetNamed:")] - [return: NullAllowed] - SKTileSet FromName (string name); + [Static] + [Export ("tileGroupWithRules:")] + SKTileGroup Create (SKTileGroupRule [] rules); - [Static] - [Export ("tileSetFromURL:")] - [return: NullAllowed] - SKTileSet FromUrl (NSUrl url); + [Static] + [Export ("emptyTileGroup")] + SKTileGroup CreateEmpty (); - [Export ("tileGroups", ArgumentSemantic.Copy)] - SKTileGroup [] TileGroups { get; set; } + [Export ("initWithTileDefinition:")] + NativeHandle Constructor (SKTileDefinition tileDefinition); - [NullAllowed, Export ("name")] - string Name { get; set; } + [Export ("initWithRules:")] + NativeHandle Constructor (SKTileGroupRule [] rules); - [Export ("type", ArgumentSemantic.Assign)] - SKTileSetType Type { get; set; } + [Export ("rules", ArgumentSemantic.Copy)] + SKTileGroupRule [] Rules { get; set; } - [NullAllowed, Export ("defaultTileGroup", ArgumentSemantic.Assign)] - SKTileGroup DefaultTileGroup { get; set; } + [NullAllowed, Export ("name")] + string Name { get; set; } + } - [Export ("defaultTileSize", ArgumentSemantic.Assign)] - CGSize DefaultTileSize { get; set; } -} + /// Defines adjacency rules for tiles in an . + /// + /// Apple documentation for SKTileGroupRule + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKTileGroupRule : NSCopying, NSSecureCoding { + [Static] + [Export ("tileGroupRuleWithAdjacency:tileDefinitions:")] + SKTileGroupRule Create (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); -/// -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKTileGroup : NSCopying, NSSecureCoding { - [Static] - [Export ("tileGroupWithTileDefinition:")] - SKTileGroup Create (SKTileDefinition tileDefinition); + [Export ("initWithAdjacency:tileDefinitions:")] + NativeHandle Constructor (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); - [Static] - [Export ("tileGroupWithRules:")] - SKTileGroup Create (SKTileGroupRule [] rules); + [Export ("adjacency", ArgumentSemantic.Assign)] + SKTileAdjacencyMask Adjacency { get; set; } - [Static] - [Export ("emptyTileGroup")] - SKTileGroup CreateEmpty (); + [Export ("tileDefinitions", ArgumentSemantic.Copy)] + SKTileDefinition [] TileDefinitions { get; set; } - [Export ("initWithTileDefinition:")] - NativeHandle Constructor (SKTileDefinition tileDefinition); + [NullAllowed, Export ("name")] + string Name { get; set; } + } - [Export ("initWithRules:")] - NativeHandle Constructor (SKTileGroupRule [] rules); + /// Defines geometry deformation on objects. + /// + /// Apple documentation for SKWarpGeometry + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + interface SKWarpGeometry : NSCopying, NSSecureCoding { } - [Export ("rules", ArgumentSemantic.Copy)] - SKTileGroupRule [] Rules { get; set; } + /// Associates a and subdivision levels with an implementation. + [MacCatalyst (13, 1)] + [Protocol] + interface SKWarpable { + [Abstract] + [NullAllowed, Export ("warpGeometry", ArgumentSemantic.Assign)] + SKWarpGeometry WarpGeometry { get; set; } - [NullAllowed, Export ("name")] - string Name { get; set; } -} + [Abstract] + [Export ("subdivisionLevels")] + nint SubdivisionLevels { get; set; } + } -/// Defines adjacency rules for tiles in an . -/// -/// Apple documentation for SKTileGroupRule -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKTileGroupRule : NSCopying, NSSecureCoding { - [Static] - [Export ("tileGroupRuleWithAdjacency:tileDefinitions:")] - SKTileGroupRule Create (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); + /// A subclass that defines a warpable grid. + /// + /// Apple documentation for SKWarpGeometryGrid + [MacCatalyst (13, 1)] + [BaseType (typeof (SKWarpGeometry))] + [DisableDefaultCtor] + interface SKWarpGeometryGrid : NSSecureCoding { + [Static] + [Export ("grid")] + SKWarpGeometryGrid GetGrid (); - [Export ("initWithAdjacency:tileDefinitions:")] - NativeHandle Constructor (SKTileAdjacencyMask adjacency, SKTileDefinition [] tileDefinitions); + [Static] + [Export ("gridWithColumns:rows:")] + SKWarpGeometryGrid Create (nint cols, nint rows); - [Export ("adjacency", ArgumentSemantic.Assign)] - SKTileAdjacencyMask Adjacency { get; set; } + [Internal] + [Static] + [Export ("gridWithColumns:rows:sourcePositions:destPositions:")] + SKWarpGeometryGrid GridWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - [Export ("tileDefinitions", ArgumentSemantic.Copy)] - SKTileDefinition [] TileDefinitions { get; set; } + [Internal] + [DesignatedInitializer] + [Export ("initWithColumns:rows:sourcePositions:destPositions:")] + IntPtr InitWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - [NullAllowed, Export ("name")] - string Name { get; set; } -} + [Export ("numberOfColumns")] + nint NumberOfColumns { get; } -/// Defines geometry deformation on objects. -/// -/// Apple documentation for SKWarpGeometry -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -interface SKWarpGeometry : NSCopying, NSSecureCoding { } - -/// Associates a and subdivision levels with an implementation. -[MacCatalyst (13, 1)] -[Protocol] -interface SKWarpable { - [Abstract] - [NullAllowed, Export ("warpGeometry", ArgumentSemantic.Assign)] - SKWarpGeometry WarpGeometry { get; set; } - - [Abstract] - [Export ("subdivisionLevels")] - nint SubdivisionLevels { get; set; } -} + [Export ("numberOfRows")] + nint NumberOfRows { get; } -/// A subclass that defines a warpable grid. -/// -/// Apple documentation for SKWarpGeometryGrid -[MacCatalyst (13, 1)] -[BaseType (typeof (SKWarpGeometry))] -[DisableDefaultCtor] -interface SKWarpGeometryGrid : NSSecureCoding { - [Static] - [Export ("grid")] - SKWarpGeometryGrid GetGrid (); - - [Static] - [Export ("gridWithColumns:rows:")] - SKWarpGeometryGrid Create (nint cols, nint rows); - - [Internal] - [Static] - [Export ("gridWithColumns:rows:sourcePositions:destPositions:")] - SKWarpGeometryGrid GridWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - - [Internal] - [DesignatedInitializer] - [Export ("initWithColumns:rows:sourcePositions:destPositions:")] - IntPtr InitWithColumns (nint cols, nint rows, [NullAllowed] IntPtr sourcePositions, [NullAllowed] IntPtr destPositions); - - [Export ("numberOfColumns")] - nint NumberOfColumns { get; } - - [Export ("numberOfRows")] - nint NumberOfRows { get; } - - [Export ("vertexCount")] - nint VertexCount { get; } - - [Export ("sourcePositionAtIndex:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector2 GetSourcePosition (nint index); - - [Export ("destPositionAtIndex:")] - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - Vector2 GetDestPosition (nint index); - - [Internal] - [Export ("gridByReplacingSourcePositions:")] - SKWarpGeometryGrid _GridByReplacingSourcePositions (IntPtr sourcePositions); - - [Internal] - [Export ("gridByReplacingDestPositions:")] - SKWarpGeometryGrid _GridByReplacingDestPositions (IntPtr destPositions); -} + [Export ("vertexCount")] + nint VertexCount { get; } -// SKRenderer is not available for WatchKit apps and the iOS simulator -/// The class used to render SpriteKit. -[MacCatalyst (13, 1)] -[BaseType (typeof (NSObject))] -[DisableDefaultCtor] -interface SKRenderer { - [Static] - [Export ("rendererWithDevice:")] - SKRenderer FromDevice (IMTLDevice device); + [Export ("sourcePositionAtIndex:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector2 GetSourcePosition (nint index); - [Export ("renderWithViewport:commandBuffer:renderPassDescriptor:")] - void Render (CGRect viewport, IMTLCommandBuffer commandBuffer, MTLRenderPassDescriptor renderPassDescriptor); + [Export ("destPositionAtIndex:")] + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + Vector2 GetDestPosition (nint index); - [Export ("renderWithViewport:renderCommandEncoder:renderPassDescriptor:commandQueue:")] - void Render (CGRect viewport, IMTLRenderCommandEncoder renderCommandEncoder, MTLRenderPassDescriptor renderPassDescriptor, IMTLCommandQueue commandQueue); + [Internal] + [Export ("gridByReplacingSourcePositions:")] + SKWarpGeometryGrid _GridByReplacingSourcePositions (IntPtr sourcePositions); - [Export ("updateAtTime:")] - void Update (double currentTime); + [Internal] + [Export ("gridByReplacingDestPositions:")] + SKWarpGeometryGrid _GridByReplacingDestPositions (IntPtr destPositions); + } - [NullAllowed, Export ("scene", ArgumentSemantic.Assign)] - SKScene Scene { get; set; } + // SKRenderer is not available for WatchKit apps and the iOS simulator + /// The class used to render SpriteKit. + [MacCatalyst (13, 1)] + [BaseType (typeof (NSObject))] + [DisableDefaultCtor] + interface SKRenderer { + [Static] + [Export ("rendererWithDevice:")] + SKRenderer FromDevice (IMTLDevice device); - [Export ("ignoresSiblingOrder")] - bool IgnoresSiblingOrder { get; set; } + [Export ("renderWithViewport:commandBuffer:renderPassDescriptor:")] + void Render (CGRect viewport, IMTLCommandBuffer commandBuffer, MTLRenderPassDescriptor renderPassDescriptor); - [Export ("shouldCullNonVisibleNodes")] - bool ShouldCullNonVisibleNodes { get; set; } + [Export ("renderWithViewport:renderCommandEncoder:renderPassDescriptor:commandQueue:")] + void Render (CGRect viewport, IMTLRenderCommandEncoder renderCommandEncoder, MTLRenderPassDescriptor renderPassDescriptor, IMTLCommandQueue commandQueue); - [Export ("showsDrawCount")] - bool ShowsDrawCount { get; set; } + [Export ("updateAtTime:")] + void Update (double currentTime); - [Export ("showsNodeCount")] - bool ShowsNodeCount { get; set; } + [NullAllowed, Export ("scene", ArgumentSemantic.Assign)] + SKScene Scene { get; set; } - [Export ("showsQuadCount")] - bool ShowsQuadCount { get; set; } + [Export ("ignoresSiblingOrder")] + bool IgnoresSiblingOrder { get; set; } - [Export ("showsPhysics")] - bool ShowsPhysics { get; set; } + [Export ("shouldCullNonVisibleNodes")] + bool ShouldCullNonVisibleNodes { get; set; } - [Export ("showsFields")] - bool ShowsFields { get; set; } -} + [Export ("showsDrawCount")] + bool ShowsDrawCount { get; set; } -/// A that holds a geometric transform. -[MacCatalyst (13, 1)] -[BaseType (typeof (SKNode))] -interface SKTransformNode { - [Export ("xRotation")] - nfloat XRotation { get; set; } + [Export ("showsNodeCount")] + bool ShowsNodeCount { get; set; } - [Export ("yRotation")] - nfloat YRotation { get; set; } + [Export ("showsQuadCount")] + bool ShowsQuadCount { get; set; } - [Export ("eulerAngles")] - VectorFloat3 EulerAngles { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; - } + [Export ("showsPhysics")] + bool ShowsPhysics { get; set; } - [Export ("rotationMatrix")] - MatrixFloat3x3 RotationMatrix { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; + [Export ("showsFields")] + bool ShowsFields { get; set; } } - [Export ("quaternion")] - Quaternion Quaternion { - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - get; - [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] - set; + /// A that holds a geometric transform. + [MacCatalyst (13, 1)] + [BaseType (typeof (SKNode))] + interface SKTransformNode { + [Export ("xRotation")] + nfloat XRotation { get; set; } + + [Export ("yRotation")] + nfloat YRotation { get; set; } + + [Export ("eulerAngles")] + VectorFloat3 EulerAngles { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("rotationMatrix")] + MatrixFloat3x3 RotationMatrix { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } + + [Export ("quaternion")] + Quaternion Quaternion { + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + get; + [MarshalDirective (NativePrefix = "xamarin_simd__", Library = "__Internal")] + set; + } } } -} diff --git a/src/storekit.cs b/src/storekit.cs index 1f273c0191f4..1b3269170981 100644 --- a/src/storekit.cs +++ b/src/storekit.cs @@ -79,17 +79,13 @@ partial interface SKDownload { [Export ("state")] SKDownloadState State { get; } #if MONOMAC - [NoiOS] - [NoTV] - [NoMacCatalyst] + [NoiOS][NoTV][NoMacCatalyst] [Obsolete ("Use 'State' instead.")] [Wrap ("State", IsVirtual = true)] - SKDownloadState DownloadState { get; } + SKDownloadState DownloadState { get; } - [NoiOS] - [NoTV] - [NoMacCatalyst] - [Deprecated (PlatformName.MacOSX, 10, 15, message: "Use 'ExpectedContentLength' instead.")] + [NoiOS][NoTV][NoMacCatalyst] + [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'ExpectedContentLength' instead.")] [Export ("contentLength", ArgumentSemantic.Copy)] NSNumber ContentLength { get; } #else @@ -378,10 +374,8 @@ interface SKProduct { string ProductIdentifier { get; } #if MONOMAC - [NoiOS] - [NoTV] - [NoMacCatalyst] - [Deprecated (PlatformName.MacOSX, 10, 15, message: "Use 'IsDownloadable' instead.")] +[NoiOS][NoTV][NoMacCatalyst] + [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'IsDownloadable' instead.")] [Export ("downloadable")] bool Downloadable { get; } #elif !NET diff --git a/src/tvmlkit.cs b/src/tvmlkit.cs index ac782b340890..b63ba6ae19e7 100644 --- a/src/tvmlkit.cs +++ b/src/tvmlkit.cs @@ -716,8 +716,7 @@ interface ITVBrowserViewControllerDataSource { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -735,8 +734,7 @@ interface ITVBrowserViewControllerDelegate { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -801,8 +799,7 @@ interface ITVDocumentViewControllerDelegate { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol] - [Model] + [Protocol][Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/uikit.cs b/src/uikit.cs index e88ec7e7c10a..dc2a77d216f0 100644 --- a/src/uikit.cs +++ b/src/uikit.cs @@ -15777,7 +15777,7 @@ interface UITableViewRowAction : NSCopying { // , Events=new Type [] {typeof(UITextFieldDelegate)})] custom logic needed, see https://bugzilla.xamarin.com/show_bug.cgi?id=53174 interface UITextField : UITextInput, UIContentSizeCategoryAdjusting, UILetterformAwareAdjusting #if IOS - , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting + , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting #endif // IOS { [Export ("initWithFrame:")] @@ -15993,7 +15993,7 @@ interface UITextFieldDelegate { [BaseType (typeof (UIScrollView), Delegates = new string [] { "WeakDelegate" }, Events = new Type [] { typeof (UITextViewDelegate) })] interface UITextView : UITextInput, NSCoding, UIContentSizeCategoryAdjusting, UILetterformAwareAdjusting #if IOS - , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting + , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting #endif // IOS { [Export ("initWithFrame:")] diff --git a/src/webkit.cs b/src/webkit.cs index 3eb3bd941851..08a7e3be2435 100644 --- a/src/webkit.cs +++ b/src/webkit.cs @@ -32,7 +32,7 @@ #if MONOMAC using AppKit; -using UIColor = AppKit.NSColor; +using UIColor=AppKit.NSColor; using UIScrollView = AppKit.NSScrollView; using UIImage = AppKit.NSImage; using IUIContextMenuInteractionCommitAnimating = Foundation.NSObject; @@ -2539,7 +2539,7 @@ partial interface WebUIDelegate { [Export ("webView:shouldPerformAction:fromSender:"), DelegateName ("WebViewPerformAction"), DefaultValue (null)] bool UIShouldPerformActionfromSender (WebView webView, Selector action, NSObject sender); #else - [Export ("webView:shouldPerformAction:fromSender:"), DelegateName ("WebViewPerformAction"), DefaultValue (null)] + [Export ("webView:shouldPerformAction:fromSender:"), DelegateName("WebViewPerformAction"), DefaultValue (null)] bool UIShouldPerformAction (WebView webView, Selector action, NSObject sender); #endif @@ -5760,7 +5760,7 @@ interface WKWindowFeatures { } #if MONOMAC - interface UIPreviewActionItem { } + interface UIPreviewActionItem {} #endif interface IWKPreviewActionItem { } diff --git a/src/xkit.cs b/src/xkit.cs index fb04b16ca6c7..6aa374e5d656 100644 --- a/src/xkit.cs +++ b/src/xkit.cs @@ -44,21 +44,21 @@ using NSView = System.Object; using NSWindow = System.Object; #else -using UICollectionLayoutListConfiguration = System.Object; -using UIContentInsetsReference = System.Object; -using UIEdgeInsets = System.Object; -using UITraitCollection = System.Object; +using UICollectionLayoutListConfiguration=System.Object; +using UIContentInsetsReference=System.Object; +using UIEdgeInsets=System.Object; +using UITraitCollection=System.Object; #endif // !MONOMAC #if MONOMAC -using BezierPath = AppKit.NSBezierPath; -using Image = AppKit.NSImage; -using TextAlignment = AppKit.NSTextAlignment; -using LineBreakMode = AppKit.NSLineBreakMode; -using CollectionLayoutSectionOrthogonalScrollingBehavior = AppKit.NSCollectionLayoutSectionOrthogonalScrollingBehavior; -using CollectionElementCategory = AppKit.NSCollectionElementCategory; -using StringAttributes = AppKit.NSStringAttributes; -using View = AppKit.NSView; +using BezierPath=AppKit.NSBezierPath; +using Image=AppKit.NSImage; +using TextAlignment=AppKit.NSTextAlignment; +using LineBreakMode=AppKit.NSLineBreakMode; +using CollectionLayoutSectionOrthogonalScrollingBehavior=AppKit.NSCollectionLayoutSectionOrthogonalScrollingBehavior; +using CollectionElementCategory=AppKit.NSCollectionElementCategory; +using StringAttributes=AppKit.NSStringAttributes; +using View=AppKit.NSView; using UICollectionLayoutSectionOrthogonalScrollingProperties = System.Object; #else using BezierPath = UIKit.UIBezierPath; @@ -72,26 +72,26 @@ #endif #if MONOMAC -using IXWritingToolsCoordinatorDelegate = AppKit.INSWritingToolsCoordinatorDelegate; -using XWritingToolsBehavior = AppKit.NSWritingToolsBehavior; -using XWritingToolsCoordinator = AppKit.NSWritingToolsCoordinator; -using XWritingToolsCoordinatorAnimationParameters = AppKit.NSWritingToolsCoordinatorAnimationParameters; -using XWritingToolsCoordinatorContext = AppKit.NSWritingToolsCoordinatorContext; -using XWritingToolsCoordinatorContextScope = AppKit.NSWritingToolsCoordinatorContextScope; -using XWritingToolsCoordinatorDelegate = AppKit.NSWritingToolsCoordinatorDelegate; -using XWritingToolsCoordinatorDelegateReplaceRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateReplaceRangeCallback; -using XWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback; -using XWritingToolsCoordinatorDelegateRequestsContextsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsContextsCallback; -using XWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback; -using XWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback; -using XWritingToolsCoordinatorDelegateRequestsRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsRangeCallback; -using XWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback; -using XWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback; -using XWritingToolsCoordinatorState = AppKit.NSWritingToolsCoordinatorState; -using XWritingToolsCoordinatorTextAnimation = AppKit.NSWritingToolsCoordinatorTextAnimation; -using XWritingToolsCoordinatorTextReplacementReason = AppKit.NSWritingToolsCoordinatorTextReplacementReason; -using XWritingToolsCoordinatorTextUpdateReason = AppKit.NSWritingToolsCoordinatorTextUpdateReason; -using XWritingToolsResultOptions = AppKit.NSWritingToolsResultOptions; + using IXWritingToolsCoordinatorDelegate = AppKit.INSWritingToolsCoordinatorDelegate; + using XWritingToolsBehavior = AppKit.NSWritingToolsBehavior; + using XWritingToolsCoordinator = AppKit.NSWritingToolsCoordinator; + using XWritingToolsCoordinatorAnimationParameters = AppKit.NSWritingToolsCoordinatorAnimationParameters; + using XWritingToolsCoordinatorContext = AppKit.NSWritingToolsCoordinatorContext; + using XWritingToolsCoordinatorContextScope = AppKit.NSWritingToolsCoordinatorContextScope; + using XWritingToolsCoordinatorDelegate = AppKit.NSWritingToolsCoordinatorDelegate; + using XWritingToolsCoordinatorDelegateReplaceRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateReplaceRangeCallback; + using XWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback; + using XWritingToolsCoordinatorDelegateRequestsContextsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsContextsCallback; + using XWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback; + using XWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback; + using XWritingToolsCoordinatorDelegateRequestsRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsRangeCallback; + using XWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback; + using XWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback; + using XWritingToolsCoordinatorState = AppKit.NSWritingToolsCoordinatorState; + using XWritingToolsCoordinatorTextAnimation = AppKit.NSWritingToolsCoordinatorTextAnimation; + using XWritingToolsCoordinatorTextReplacementReason = AppKit.NSWritingToolsCoordinatorTextReplacementReason; + using XWritingToolsCoordinatorTextUpdateReason = AppKit.NSWritingToolsCoordinatorTextUpdateReason; + using XWritingToolsResultOptions = AppKit.NSWritingToolsResultOptions; #else using IXWritingToolsCoordinatorDelegate = UIKit.IUIWritingToolsCoordinatorDelegate; using XWritingToolsBehavior = UIKit.UIWritingToolsBehavior; @@ -4183,7 +4183,7 @@ interface NSTextList : NSCoding, NSCopying, NSSecureCoding { NativeHandle Constructor (NSTextListMarkerFormats format); #if NET - [BindAs (typeof (NSTextListMarkerFormats))] + [BindAs (typeof (NSTextListMarkerFormats))] #endif [Export ("markerFormat")] #if NET @@ -4733,20 +4733,20 @@ interface UIWritingToolsCoordinator : UIInteraction } #if MONOMAC - interface INSWritingToolsCoordinatorDelegate { } + interface INSWritingToolsCoordinatorDelegate {} #else interface IUIWritingToolsCoordinatorDelegate { } #endif #if MONOMAC - delegate void NSWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext [] contexts); + delegate void NSWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext[] contexts); delegate void NSWritingToolsCoordinatorDelegateReplaceRangeCallback ([NullAllowed] NSAttributedString replacementText); delegate void NSWritingToolsCoordinatorDelegateRequestsRangeCallback (NSRange range, NSUuid contextId); - delegate void NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback (BezierPath [] paths); - delegate void NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback (BezierPath [] paths); + delegate void NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback (BezierPath[] paths); + delegate void NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback (BezierPath[] paths); delegate void NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback ([NullAllowed] NSTextPreview [] view); // different signature vs other platforms delegate void NSWritingToolsCoordinatorDelegateRequestsPreviewCallback ([NullAllowed] NSTextPreview textPreview); // doesn't exist on other platforms - delegate void NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback (/* [BindAs (typeof (NSRange[]))] */ NSValue [] ranges); // BindAs doesn't work here + delegate void NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback (/* [BindAs (typeof (NSRange[]))] */ NSValue[] ranges); // BindAs doesn't work here delegate void NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback (View view); #else delegate void UIWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext [] contexts); diff --git a/tests/BundledResources/ResourcesTest.cs b/tests/BundledResources/ResourcesTest.cs index d616b7828018..f5ca6d1710b8 100644 --- a/tests/BundledResources/ResourcesTest.cs +++ b/tests/BundledResources/ResourcesTest.cs @@ -9,6 +9,7 @@ using System; using System.IO; +using System.Linq; using NUnit.Framework; using Foundation; @@ -41,10 +42,14 @@ public void Bundled () if (!hasResources) { Assert.That (resources.Length, Is.EqualTo (0), "No resources"); } else { - Assert.That (resources.Length, Is.GreaterThanOrEqualTo (2), "Resources"); - Assert.That (resources, Contains.Item ("__monotouch_content_basn3p08.png"), "res-basn3p08.png"); - Assert.That (resources, Contains.Item ("__monotouch_content_basn3p08__with__loc.png"), "res-basn3p08_with_loc.png"); - Assert.That (resources, Contains.Item ("__monotouch_content_xamvideotest.mp4"), "res-xamvideotest.mp4"); + var expectedResources = new string [] { + "basn3p08.png", + "basn3p08__with__loc.png", + "xamvideotest.mp4", + }; + var oldPrefixed = expectedResources.Select (v => $"__monotouch_content_{v}").ToArray (); + var newPrefixed = expectedResources.Select (v => $"__monotouch_item_BundleResource_{v}").ToArray (); + Assert.That (resources, Is.EquivalentTo (oldPrefixed).Or.EquivalentTo (newPrefixed), "Resources"); } } } diff --git a/tests/cecil-tests/Documentation.KnownFailures.txt b/tests/cecil-tests/Documentation.KnownFailures.txt index 224642bbeb8e..218d01ad7ee1 100644 --- a/tests/cecil-tests/Documentation.KnownFailures.txt +++ b/tests/cecil-tests/Documentation.KnownFailures.txt @@ -41493,7 +41493,6 @@ M:NotificationCenter.NSExtensionContext_NCWidgetAdditions.SetWidgetLargestAvaila M:NotificationCenter.NSWidgetSearchForTermEventArgs.#ctor(System.String,System.UIntPtr) M:NotificationCenter.NSWidgetSearchResultSelectedEventArgs.#ctor(Foundation.NSObject) M:ObjCBindings.BindingTypeAttribute.#ctor -M:ObjCBindings.BindingTypeAttribute`1.#ctor M:ObjCBindings.ExportAttribute`1.#ctor M:ObjCRuntime.AdoptsAttribute.#ctor(System.String) M:ObjCRuntime.AssemblyRegistrationEventArgs.#ctor diff --git a/tests/common/Configuration.cs b/tests/common/Configuration.cs index ced1564c820f..f4d1f8058edc 100644 --- a/tests/common/Configuration.cs +++ b/tests/common/Configuration.cs @@ -1,12 +1,12 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; - using Xamarin.Utils; #nullable disable // until we get around to fixing this file @@ -44,6 +44,7 @@ static partial class Configuration { public static string DOTNET_DIR; static Version xcode_version; + public static Version XcodeVersion { get { if (xcode_version is null) @@ -53,6 +54,7 @@ public static Version XcodeVersion { } static bool? use_system; // if the system-installed XI/XM should be used instead of the local one. + public static bool UseSystem { get { if (!use_system.HasValue) @@ -65,6 +67,7 @@ public static bool UseSystem { } static bool? is_vsts; // if the system-installed XI/XM should be used instead of the local one. + public static bool IsVsts { get { if (!is_vsts.HasValue) @@ -147,14 +150,18 @@ static void ParseConfigFiles () tests_dir = file; break; } + dir = Path.GetDirectoryName (dir); } + if (tests_dir is null) - throw new Exception ($"Could not find the directory 'tests'. Please run 'make' in the tests/ directory."); + throw new Exception ( + $"Could not find the directory 'tests'. Please run 'make' in the tests/ directory."); // Run make ExecutionHelper.Execute ("make", new string [] { "-C", tests_dir, "test.config" }); test_config = FindConfigFiles ("test.config"); } + if (test_config.Any ()) ParseConfigFiles (test_config); ParseConfigFiles (FindConfigFiles ("configure.inc")); @@ -207,10 +214,14 @@ public static string EvaluateVariable (string variable) return result; var output = new StringBuilder (); - var rv = ExecutionHelper.Execute ("/usr/bin/make", new string [] { "-C", Path.Combine (SourceRoot, "tools", "devops"), "print-abspath-variable", $"VARIABLE={variable}" }, environmentVariables: null, stdout: output, stderr: output, timeout: TimeSpan.FromSeconds (5)); + var rv = ExecutionHelper.Execute ("/usr/bin/make", + new string [] { + "-C", Path.Combine (SourceRoot, "tools", "devops"), "print-abspath-variable", $"VARIABLE={variable}" + }, environmentVariables: null, stdout: output, stderr: output, timeout: TimeSpan.FromSeconds (5)); if (rv != 0) throw new Exception ($"Failed to evaluate variable '{variable}'. Exit code: {rv}. Output:\n{output}"); - result = output.ToString ().Split (new char [] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Where (v => v.StartsWith (variable + "=", StringComparison.Ordinal)).SingleOrDefault (); + result = output.ToString ().Split (new char [] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) + .Where (v => v.StartsWith (variable + "=", StringComparison.Ordinal)).SingleOrDefault (); if (result is null) throw new Exception ($"Could not find the variable '{variable}' to evaluate."); return result.Substring (variable.Length + 1); @@ -233,7 +244,8 @@ public static string GetPListStringValue (string plist, string key) using (var fs = new StringReader (ReadPListAsXml (plist))) { using (var reader = System.Xml.XmlReader.Create (fs, settings)) { doc.Load (reader); - return doc.DocumentElement.SelectSingleNode ($"//dict/key[text()='{key}']/following-sibling::string[1]/text()").Value; + return doc.DocumentElement + .SelectSingleNode ($"//dict/key[text()='{key}']/following-sibling::string[1]/text()").Value; } } } @@ -278,7 +290,8 @@ static Configuration () DotNetExecutable = GetVariable ("DOTNET", null); DotNetTfm = GetVariable ("DOTNET_TFM", null); EnableXamarin = !string.IsNullOrEmpty (GetVariable ("ENABLE_XAMARIN", "")); - XcodeIsStable = string.Equals (GetVariable ("XCODE_IS_STABLE", ""), "true", StringComparison.OrdinalIgnoreCase); + XcodeIsStable = string.Equals (GetVariable ("XCODE_IS_STABLE", ""), "true", + StringComparison.OrdinalIgnoreCase); DOTNET_DIR = GetVariable ("DOTNET_DIR", ""); XcodeVersionString = GetVariable ("XCODE_VERSION", GetXcodeVersion (xcode_root)); @@ -316,19 +329,23 @@ public static string RootPath { throw new FormatException (".git worktree file is not valid"); } } + if (Directory.Exists (path)) found = true; if (!found) { dir = Path.GetDirectoryName (dir); if (dir is null) - throw new Exception ($"Could not find the xamarin-macios repo given the test assembly directory {TestAssemblyDirectory}"); + throw new Exception ( + $"Could not find the xamarin-macios repo given the test assembly directory {TestAssemblyDirectory}"); path = Path.Combine (dir, ".git"); } } + path = Path.GetDirectoryName (path); if (!Directory.Exists (path)) - throw new Exception ($"Could not find the xamarin-macios repo given the test assembly directory {TestAssemblyDirectory}"); + throw new Exception ( + $"Could not find the xamarin-macios repo given the test assembly directory {TestAssemblyDirectory}"); return path; } } @@ -419,9 +436,11 @@ public static string GetNuGetVersionNoMetadata (TargetFramework framework) public static string GetNuGetVersionNoMetadata (ApplePlatform platform) { - var workloadVersion = Environment.GetEnvironmentVariable ($"{platform.AsString ().ToUpper ()}_WORKLOAD_VERSION"); - return string.IsNullOrEmpty (workloadVersion) ? - GetVariable ($"{platform.AsString ().ToUpper ()}_NUGET_VERSION_NO_METADATA", string.Empty) : workloadVersion; + var workloadVersion = + Environment.GetEnvironmentVariable ($"{platform.AsString ().ToUpper ()}_WORKLOAD_VERSION"); + return string.IsNullOrEmpty (workloadVersion) + ? GetVariable ($"{platform.AsString ().ToUpper ()}_NUGET_VERSION_NO_METADATA", string.Empty) + : workloadVersion; } // This is only applicable for .NET @@ -580,11 +599,14 @@ public static string CloneTestDirectory (string directory) var testsTemporaryDirectory = Cache.CreateTemporaryDirectory ($"{Path.GetFileName (directory)}"); // Only copy files in git, we want a clean copy - var rv = ExecutionHelper.Execute ("git", new string [] { "ls-files" }, out var ls_files_output, working_directory: directory, timeout: TimeSpan.FromSeconds (15)); + var rv = ExecutionHelper.Execute ("git", new string [] { "ls-files" }, out var ls_files_output, + working_directory: directory, timeout: TimeSpan.FromSeconds (15)); if (rv != 0) - throw new Exception ($"Failed to list test files. 'git ls-files' in {directory} failed with exit code {rv}."); + throw new Exception ( + $"Failed to list test files. 'git ls-files' in {directory} failed with exit code {rv}."); - var files = ls_files_output.ToString ().Split (new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToArray (); + var files = ls_files_output.ToString ().Split (new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries) + .ToArray (); foreach (var file in files) { var src = Path.Combine (directory, file); var tgt = Path.Combine (testsTemporaryDirectory, file); @@ -593,7 +615,8 @@ public static string CloneTestDirectory (string directory) File.Copy (src, tgt); if (tgt.EndsWith (".csproj", StringComparison.OrdinalIgnoreCase)) { var initialContents = File.ReadAllText (tgt); - var fixedContents = initialContents.Replace ($"$(MSBuildThisFileDirectory)", Path.GetDirectoryName (src) + Path.DirectorySeparatorChar); + var fixedContents = initialContents.Replace ($"$(MSBuildThisFileDirectory)", + Path.GetDirectoryName (src) + Path.DirectorySeparatorChar); if (initialContents != fixedContents) File.WriteAllText (tgt, fixedContents); } @@ -689,16 +712,19 @@ public static void Touch (string file) } static bool? is_apfs; + static bool IsAPFS { get { if (!is_apfs.HasValue) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { is_apfs = false; } else { - var exit_code = ExecutionHelper.Execute ("/bin/df", new string [] { "-t", "apfs", "/" }, out var output, TimeSpan.FromSeconds (10)); + var exit_code = ExecutionHelper.Execute ("/bin/df", new string [] { "-t", "apfs", "/" }, + out var output, TimeSpan.FromSeconds (10)); is_apfs = exit_code == 0 && output.Trim ().Split ('\n').Length >= 2; } } + return is_apfs.Value; } } @@ -714,6 +740,7 @@ static void EnsureFilestampChange () // Return true if the current machine can run ARM64 binaries. static bool? canRunArm64; + public static bool CanRunArm64 { get { if (!canRunArm64.HasValue) { @@ -725,6 +752,7 @@ public static bool CanRunArm64 { canRunArm64 = false; } } + return canRunArm64.Value; } } @@ -739,6 +767,7 @@ public static IEnumerable CallNM (string file, string nmArguments, strin arguments.Add ("-arch"); arguments.Add (arch); } + var symbols = ExecutionHelper.Execute ("nm", arguments, hide_output: true).Split ('\n'); return symbols.Where ((v) => { return !v.EndsWith (": no symbols", StringComparison.Ordinal); @@ -759,6 +788,39 @@ public static IEnumerable GetUndefinedNativeSymbols (string file, string { return CallNM (file, "-gujA", arch); } + + public static bool TryGetApiDefinitionRsp (TargetFramework framework, + [NotNullWhen (true)] out string rspPath) + { + rspPath = null; + var platform = framework.Platform switch { + ApplePlatform.iOS => "ios", + ApplePlatform.TVOS => "tvos", + ApplePlatform.MacOSX => "macos", + ApplePlatform.MacCatalyst => "maccatalyst", + _ => null, + }; + if (platform is null) + return false; + rspPath = Path.Combine (SourceRoot, "src", "build", "dotnet", platform, $"apidefinition-{platform}.rsp"); + return true; + } + + public static bool TryGetPlatformPreprocessorSymbolsRsp (TargetFramework framework, + [NotNullWhen (true)] out string rspPath) + { + rspPath = null; + var platform = framework.Platform switch { + ApplePlatform.iOS => "ios", + ApplePlatform.TVOS => "tvos", + ApplePlatform.MacOSX => "macos", + ApplePlatform.MacCatalyst => "maccatalyst", + _ => null, + }; + if (platform is null) + return false; + rspPath = Path.Combine (SourceRoot, "src", "rsp", "dotnet", $"{platform}-defines-dotnet.rsp"); + return true; + } } } - diff --git a/tests/common/MonoTouch.Dialog/Reflect.cs b/tests/common/MonoTouch.Dialog/Reflect.cs deleted file mode 100644 index cd1c335a2a3d..000000000000 --- a/tests/common/MonoTouch.Dialog/Reflect.cs +++ /dev/null @@ -1,471 +0,0 @@ -// -// Reflect.cs: Creates Element classes from an instance -// -// Author: -// Miguel de Icaza (miguel@gnome.org) -// -// Copyright 2010, Novell, Inc. -// -// Code licensed under the MIT X11 license -// - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using System.Drawing; - -using UIKit; -using Foundation; - -using NSAction = global::System.Action; - -namespace MonoTouch.Dialog { - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class EntryAttribute : Attribute { - public EntryAttribute () : this (null) { } - - public EntryAttribute (string placeholder) - { - Placeholder = placeholder; - } - - public string Placeholder; - public UIKeyboardType KeyboardType; - public UITextAutocorrectionType AutocorrectionType; - public UITextAutocapitalizationType AutocapitalizationType; - public UITextFieldViewMode ClearButtonMode; - } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class DateAttribute : Attribute { } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class TimeAttribute : Attribute { } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class CheckboxAttribute : Attribute { } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class MultilineAttribute : Attribute { } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class HtmlAttribute : Attribute { } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class SkipAttribute : Attribute { } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class PasswordAttribute : EntryAttribute { - public PasswordAttribute (string placeholder) : base (placeholder) { } - } - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class AlignmentAttribute : Attribute { - public AlignmentAttribute (UITextAlignment alignment) - { - Alignment = alignment; - } - public UITextAlignment Alignment; - } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class RadioSelectionAttribute : Attribute { - public string Target; - public RadioSelectionAttribute (string target) - { - Target = target; - } - } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class OnTapAttribute : Attribute { - public OnTapAttribute (string method) - { - Method = method; - } - public string Method; - } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class CaptionAttribute : Attribute { - public CaptionAttribute (string caption) - { - Caption = caption; - } - public string Caption; - } - - [AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class SectionAttribute : Attribute { - public SectionAttribute () { } - - public SectionAttribute (string caption) - { - Caption = caption; - } - - public SectionAttribute (string caption, string footer) - { - Caption = caption; - Footer = footer; - } - public string Caption, Footer; - } - - public class RangeAttribute : Attribute { - public RangeAttribute (float low, float high) - { - Low = low; - High = high; - } - public float Low, High; - public bool ShowCaption; - } - - public class BindingContext : IDisposable { - public RootElement Root; - Dictionary mappings; - Dictionary handlerMappings; - - class MemberAndInstance { - public MemberAndInstance (MemberInfo mi, object o) - { - Member = mi; - Obj = o; - } - public MemberInfo Member; - public object Obj; - } - - static object GetValue (MemberInfo mi, object o) - { - var fi = mi as FieldInfo; - if (fi is not null) - return fi.GetValue (o); - var pi = mi as PropertyInfo; - - var getMethod = pi.GetGetMethod (); - return getMethod.Invoke (o, new object [0]); - } - - static void SetValue (MemberInfo mi, object o, object val) - { - var fi = mi as FieldInfo; - if (fi is not null) { - fi.SetValue (o, val); - return; - } - var pi = mi as PropertyInfo; - var setMethod = pi.GetSetMethod (); - setMethod.Invoke (o, new object [] { val }); - } - - static string MakeCaption (string name) - { - var sb = new StringBuilder (name.Length); - bool nextUp = true; - - foreach (char c in name) { - if (nextUp) { - sb.Append (Char.ToUpper (c)); - nextUp = false; - } else { - if (c == '_') { - sb.Append (' '); - continue; - } - if (Char.IsUpper (c)) - sb.Append (' '); - sb.Append (c); - } - } - return sb.ToString (); - } - - // Returns the type for fields and properties and null for everything else - static Type GetTypeForMember (MemberInfo mi) - { - if (mi is FieldInfo) - return ((FieldInfo) mi).FieldType; - else if (mi is PropertyInfo) - return ((PropertyInfo) mi).PropertyType; - return null; - } - - public BindingContext (object callbacks, object o, string title) - { - if (o is null) - throw new ArgumentNullException ("o"); - - mappings = new Dictionary (); - handlerMappings = new Dictionary (); - - Root = new RootElement (title); - Populate (callbacks, o, Root); - } - - void Populate (object callbacks, object o, RootElement root) - { - MemberInfo last_radio_index = null; - var members = o.GetType ().GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public | - BindingFlags.NonPublic | BindingFlags.Instance); - - Section section = null; - - foreach (var mi in members) { - Type mType = GetTypeForMember (mi); - - if (mType is null) - continue; - - string caption = null; - object [] attrs = mi.GetCustomAttributes (false); - bool skip = false; - foreach (var attr in attrs) { - if (attr is SkipAttribute || attr is System.Runtime.CompilerServices.CompilerGeneratedAttribute) - skip = true; - else if (attr is CaptionAttribute) - caption = ((CaptionAttribute) attr).Caption; - else if (attr is SectionAttribute) { - if (section is not null) - root.Add (section); - var sa = attr as SectionAttribute; - section = new Section (sa.Caption, sa.Footer); - } - } - if (skip) - continue; - - if (caption is null) - caption = MakeCaption (mi.Name); - - if (section is null) - section = new Section (); - - Element element = null; - if (mType == typeof (string)) { - PasswordAttribute pa = null; - AlignmentAttribute align = null; - EntryAttribute ea = null; - object html = null; - NSAction invoke = null; - bool multi = false; - - foreach (object attr in attrs) { - if (attr is PasswordAttribute) - pa = attr as PasswordAttribute; - else if (attr is EntryAttribute) - ea = attr as EntryAttribute; - else if (attr is MultilineAttribute) - multi = true; - else if (attr is HtmlAttribute) - html = attr; - else if (attr is AlignmentAttribute) - align = attr as AlignmentAttribute; - - if (attr is OnTapAttribute) { - string mname = ((OnTapAttribute) attr).Method; - - if (callbacks is null) { - throw new Exception ("Your class contains [OnTap] attributes, but you passed a null object for `context' in the constructor"); - } - - var method = callbacks.GetType ().GetMethod (mname); - if (method is null) - throw new Exception ("Did not find method " + mname); - invoke = delegate - { - method.Invoke (method.IsStatic ? null : callbacks, new object [0]); - }; - } - } - - string value = (string) GetValue (mi, o); - if (pa is not null) - element = new EntryElement (caption, pa.Placeholder, value, true); - else if (ea is not null) - element = new EntryElement (caption, ea.Placeholder, value) { KeyboardType = ea.KeyboardType, AutocapitalizationType = ea.AutocapitalizationType, AutocorrectionType = ea.AutocorrectionType, ClearButtonMode = ea.ClearButtonMode }; - else if (multi) - element = new MultilineElement (caption, value); - else if (html is not null) - element = new HtmlElement (caption, value); - else { - var selement = new StringElement (caption, value); - element = selement; - - if (align is not null) - selement.Alignment = align.Alignment; - } - - if (invoke is not null) { - var strElement = (StringElement) element; - strElement.Tapped += invoke; - handlerMappings.Add (strElement, invoke); - } - } else if (mType == typeof (float)) { - var floatElement = new FloatElement (null, null, (float) GetValue (mi, o)); - floatElement.Caption = caption; - element = floatElement; - - foreach (object attr in attrs) { - if (attr is RangeAttribute) { - var ra = attr as RangeAttribute; - floatElement.MinValue = ra.Low; - floatElement.MaxValue = ra.High; - floatElement.ShowCaption = ra.ShowCaption; - } - } - } else if (mType == typeof (bool)) { - bool checkbox = false; - foreach (object attr in attrs) { - if (attr is CheckboxAttribute) - checkbox = true; - } - - if (checkbox) - element = new CheckboxElement (caption, (bool) GetValue (mi, o)); - else - element = new BooleanElement (caption, (bool) GetValue (mi, o)); - } else if (mType == typeof (DateTime)) { - var dateTime = (DateTime) GetValue (mi, o); - bool asDate = false, asTime = false; - - foreach (object attr in attrs) { - if (attr is DateAttribute) - asDate = true; - else if (attr is TimeAttribute) - asTime = true; - } - - if (asDate) - element = new DateElement (caption, dateTime); - else if (asTime) - element = new TimeElement (caption, dateTime); - else - element = new DateTimeElement (caption, dateTime); - } else if (mType.IsEnum) { - var csection = new Section (); - ulong evalue = Convert.ToUInt64 (GetValue (mi, o), null); - int idx = 0; - int selected = 0; - - foreach (var fi in mType.GetFields (BindingFlags.Public | BindingFlags.Static)) { - ulong v = Convert.ToUInt64 (GetValue (fi, null)); - - if (v == evalue) - selected = idx; - - CaptionAttribute ca = Attribute.GetCustomAttribute (fi, typeof (CaptionAttribute)) as CaptionAttribute; - csection.Add (new RadioElement (ca is not null ? ca.Caption : MakeCaption (fi.Name))); - idx++; - } - - element = new RootElement (caption, new RadioGroup (null, selected)) { csection }; - } else if (mType == typeof (UIImage)) { - element = new ImageElement ((UIImage) GetValue (mi, o)); - } else if (typeof (System.Collections.IEnumerable).IsAssignableFrom (mType)) { - var csection = new Section (); - int count = 0; - - if (last_radio_index is null) - throw new Exception ("IEnumerable found, but no previous int found"); - foreach (var e in (IEnumerable) GetValue (mi, o)) { - csection.Add (new RadioElement (e.ToString ())); - count++; - } - int selected = (int) GetValue (last_radio_index, o); - if (selected >= count || selected < 0) - selected = 0; - element = new RootElement (caption, new MemberRadioGroup (null, selected, last_radio_index)) { csection }; - last_radio_index = null; - } else if (typeof (int) == mType) { - foreach (object attr in attrs) { - if (attr is RadioSelectionAttribute) { - last_radio_index = mi; - break; - } - } - } else { - var nested = GetValue (mi, o); - if (nested is not null) { - var newRoot = new RootElement (caption); - Populate (callbacks, nested, newRoot); - element = newRoot; - } - } - - if (element is null) - continue; - section.Add (element); - mappings [element] = new MemberAndInstance (mi, o); - } - root.Add (section); - } - - class MemberRadioGroup : RadioGroup { - public MemberInfo mi; - - public MemberRadioGroup (string key, int selected, MemberInfo mi) : base (key, selected) - { - this.mi = mi; - } - } - - public void Dispose () - { - Dispose (true); - } - - protected virtual void Dispose (bool disposing) - { - if (disposing) { - // Dispose any [OnTap] handler associated to its element - foreach (var strElement in handlerMappings) - strElement.Key.Tapped -= strElement.Value; - handlerMappings = null; - - foreach (var element in mappings.Keys) { - element.Dispose (); - } - mappings = null; - } - } - - public void Fetch () - { - foreach (var dk in mappings) { - Element element = dk.Key; - MemberInfo mi = dk.Value.Member; - object obj = dk.Value.Obj; - - if (element is DateTimeElement) - SetValue (mi, obj, ((DateTimeElement) element).DateValue); - else if (element is FloatElement) - SetValue (mi, obj, ((FloatElement) element).Value); - else if (element is BooleanElement) - SetValue (mi, obj, ((BooleanElement) element).Value); - else if (element is CheckboxElement) - SetValue (mi, obj, ((CheckboxElement) element).Value); - else if (element is EntryElement) { - var entry = (EntryElement) element; - entry.FetchValue (); - SetValue (mi, obj, entry.Value); - } else if (element is ImageElement) - SetValue (mi, obj, ((ImageElement) element).Value); - else if (element is RootElement) { - var re = element as RootElement; - if (re.group as MemberRadioGroup is not null) { - var group = re.group as MemberRadioGroup; - SetValue (group.mi, obj, re.RadioSelected); - } else if (re.group as RadioGroup is not null) { - var mType = GetTypeForMember (mi); - var fi = mType.GetFields (BindingFlags.Public | BindingFlags.Static) [re.RadioSelected]; - - SetValue (mi, obj, fi.GetValue (null)); - } - } - } - } - } -} diff --git a/tests/dotnet/UnitTests/ProjectTest.cs b/tests/dotnet/UnitTests/ProjectTest.cs index ddc33649d0f4..d1696f8d48dd 100644 --- a/tests/dotnet/UnitTests/ProjectTest.cs +++ b/tests/dotnet/UnitTests/ProjectTest.cs @@ -232,11 +232,19 @@ public void BuildBindingsTest2 (ApplePlatform platform) Assert.That (resourceBundle, Does.Exist, "Bundle existence"); } - [TestCase ("iOS", "monotouch")] - [TestCase ("tvOS", "monotouch")] - [TestCase ("macOS", "xammac")] - [TestCase ("MacCatalyst", "monotouch")] - public void BuildBundledResources (string platform, string prefix) + [TestCase ("iOS", "monotouch", true)] + [TestCase ("tvOS", "monotouch", true)] + [TestCase ("macOS", "xammac", true)] + [TestCase ("MacCatalyst", "monotouch", true)] + [TestCase ("iOS", "monotouch", false)] + [TestCase ("tvOS", "monotouch", false)] + [TestCase ("macOS", "xammac", false)] + [TestCase ("MacCatalyst", "monotouch", false)] + [TestCase ("iOS", "monotouch", null)] + [TestCase ("tvOS", "monotouch", null)] + [TestCase ("macOS", "xammac", null)] + [TestCase ("MacCatalyst", "monotouch", null)] + public void BuildBundledResources (string platform, string prefix, bool? bundleOriginalResources) { Configuration.IgnoreIfIgnoredPlatform (platform); var assemblyName = "BundledResources"; @@ -870,9 +878,6 @@ public void LibraryWithResources (ApplePlatform platform, bool? bundleOriginalRe var platformPrefix = (platform == ApplePlatform.MacOSX) ? "xammac" : "monotouch"; if (actualBundleOriginalResources) { expectedResources = new string [] { - $"__{platformPrefix}_content_A.ttc", - $"__{platformPrefix}_content_B.otf", - $"__{platformPrefix}_content_C.ttf", $"__{platformPrefix}_item_AtlasTexture_Archer__Attack.atlas_sarcher__attack__0001.png", $"__{platformPrefix}_item_AtlasTexture_Archer__Attack.atlas_sarcher__attack__0002.png", $"__{platformPrefix}_item_AtlasTexture_Archer__Attack.atlas_sarcher__attack__0003.png", diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj index 354782fa214d..313be15b4244 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj @@ -39,6 +39,10 @@ + + + + diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/ExportDataTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/ExportDataTests.cs index 04470f323983..e0384f20ed5f 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/ExportDataTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/ExportDataTests.cs @@ -54,22 +54,31 @@ public IEnumerator GetEnumerator () yield return [ Method.Default, new ExportData ("symbol", ArgumentSemantic.None, Method.Default), - "{ Type: 'ObjCBindings.Method', Selector: 'symbol', ArgumentSemantic: 'None', Flags: 'Default' }" + "{ Type: 'ObjCBindings.Method', Selector: 'symbol', ArgumentSemantic: 'None', Flags: 'Default', NativePrefix: 'null', NativeSuffix: 'null', Library: 'null' }" ]; yield return [ Method.Default, new ExportData ("symbol"), - "{ Type: 'ObjCBindings.Method', Selector: 'symbol', ArgumentSemantic: 'None', Flags: 'Default' }" + "{ Type: 'ObjCBindings.Method', Selector: 'symbol', ArgumentSemantic: 'None', Flags: 'Default', NativePrefix: 'null', NativeSuffix: 'null', Library: 'null' }" ]; yield return [ Property.Default, new ExportData ("symbol", ArgumentSemantic.Retain, Property.Default), - "{ Type: 'ObjCBindings.Property', Selector: 'symbol', ArgumentSemantic: 'Retain', Flags: 'Default' }" + "{ Type: 'ObjCBindings.Property', Selector: 'symbol', ArgumentSemantic: 'Retain', Flags: 'Default', NativePrefix: 'null', NativeSuffix: 'null', Library: 'null' }" ]; yield return [ Property.Default, new ExportData ("symbol"), - "{ Type: 'ObjCBindings.Property', Selector: 'symbol', ArgumentSemantic: 'None', Flags: 'Default' }" + "{ Type: 'ObjCBindings.Property', Selector: 'symbol', ArgumentSemantic: 'None', Flags: 'Default', NativePrefix: 'null', NativeSuffix: 'null', Library: 'null' }" + ]; + yield return [ + Method.Default, + new ExportData ("symbol", ArgumentSemantic.None, + Method.Default | Method.CustomMarshalDirective) { + NativePrefix = "xamarin_", + Library = "__Internal" + }, + "{ Type: 'ObjCBindings.Method', Selector: 'symbol', ArgumentSemantic: 'None', Flags: 'CustomMarshalDirective', NativePrefix: 'xamarin_', NativeSuffix: 'null', Library: '__Internal' }" ]; } @@ -81,6 +90,7 @@ IEnumerator IEnumerable.GetEnumerator () [ClassData (typeof (TestDataToString))] void TestFieldDataToString (T @enum, ExportData x, string expected) where T : Enum { + var str = x.ToString (); Assert.NotNull (@enum); Assert.Equal (expected, x.ToString ()); } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/FieldDataTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/FieldDataTests.cs index 15fb125cb083..bc5900a2de98 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/FieldDataTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Attributes/FieldDataTests.cs @@ -63,11 +63,11 @@ public IEnumerator GetEnumerator () { yield return [ new FieldData ("symbol", null, EnumValue.Default), - "{ SymbolName: 'symbol' LibraryName: 'null', Flags: 'Default' }" + "{ SymbolName: 'symbol', LibraryName: 'null', Flags: 'Default' }" ]; yield return [ new FieldData ("symbol", "lib", EnumValue.Default), - "{ SymbolName: 'symbol' LibraryName: 'lib', Flags: 'Default' }" + "{ SymbolName: 'symbol', LibraryName: 'lib', Flags: 'Default' }" ]; } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Availability/AvailabilityTriviaTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Availability/AvailabilityTriviaTests.cs new file mode 100644 index 000000000000..fe70fbfc74c4 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Availability/AvailabilityTriviaTests.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Xunit; + +namespace Microsoft.Macios.Generator.Tests.Availability; + +public class AvailabilityTriviaTests { + + [Fact] + public void AllSupportedPlatforms () + { + SymbolAvailability.Builder builder = SymbolAvailability.CreateBuilder (); + builder.Add (new SupportedOSPlatformData ("ios12.0")); + builder.Add (new SupportedOSPlatformData ("tvos12.0")); + builder.Add (new SupportedOSPlatformData ("macos10.14")); + builder.Add (new SupportedOSPlatformData ("macCatalyst13.0")); + var availability = builder.ToImmutable (); + var trivia = new AvailabilityTrivia (availability); + Assert.Null (trivia.Start); + Assert.Null (trivia.End); + Assert.Null (availability.Trivia); + } + + [Fact] + public void SomeUnsupportedVersions () + { + SymbolAvailability.Builder builder = SymbolAvailability.CreateBuilder (); + builder.Add (new SupportedOSPlatformData ("ios12.0")); + builder.Add (new UnsupportedOSPlatformData ("ios9.0")); + builder.Add (new SupportedOSPlatformData ("tvos12.0")); + builder.Add (new SupportedOSPlatformData ("macos10.14")); + builder.Add (new SupportedOSPlatformData ("maccatalyst13.0")); + var availability = builder.ToImmutable (); + var trivia = new AvailabilityTrivia (availability); + Assert.Null (trivia.Start); + Assert.Null (trivia.End); + Assert.Null (availability.Trivia); + } + + [Fact] + public void SingleFullyUnsupportedPlatform () + { + SymbolAvailability.Builder builder = SymbolAvailability.CreateBuilder (); + builder.Add (new UnsupportedOSPlatformData ("ios")); + builder.Add (new SupportedOSPlatformData ("tvos12.0")); + builder.Add (new SupportedOSPlatformData ("macos10.14")); + builder.Add (new SupportedOSPlatformData ("maccatalyst13.0")); + var availability = builder.ToImmutable (); + var trivia = new AvailabilityTrivia (availability); + Assert.Equal ("#if !IOS", trivia.Start); + Assert.Equal ("#endif", trivia.End); + Assert.NotNull (availability.Trivia); + } + + [Fact] + public void DoubleUnsupportedPlatform () + { + SymbolAvailability.Builder builder = SymbolAvailability.CreateBuilder (); + builder.Add (new SupportedOSPlatformData ("ios")); + builder.Add (new SupportedOSPlatformData ("tvos12.0")); + builder.Add (new UnsupportedOSPlatformData ("macos")); + builder.Add (new UnsupportedOSPlatformData ("maccatalyst")); + var availability = builder.ToImmutable (); + var trivia = new AvailabilityTrivia (availability); + Assert.Equal ("#if IOS || TVOS", trivia.Start); + Assert.Equal ("#endif", trivia.End); + Assert.NotNull (availability.Trivia); + } + + [Fact] + public void SingleSupportedPlatform () + { + SymbolAvailability.Builder builder = SymbolAvailability.CreateBuilder (); + builder.Add (new SupportedOSPlatformData ("ios")); + builder.Add (new UnsupportedOSPlatformData ("tvos")); + builder.Add (new UnsupportedOSPlatformData ("macos")); + builder.Add (new UnsupportedOSPlatformData ("maccatalyst")); + var availability = builder.ToImmutable (); + var trivia = new AvailabilityTrivia (availability); + Assert.Equal ("#if IOS", trivia.Start); + Assert.Equal ("#endif", trivia.End); + Assert.NotNull (availability.Trivia); + } + +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs index 7d4eaec29e4d..f849fd0a9937 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs @@ -23,11 +23,11 @@ public class BaseGeneratorTestClass { // list of the defines for each platform, this is passed to the parser to ensure that // we are testing the platforms as if they were being compiled. - readonly Dictionary platformDefines = new () { - { ApplePlatform.iOS, new [] { "__IOS__" } }, - { ApplePlatform.TVOS, new [] { "__TVOS__" } }, - { ApplePlatform.MacOSX, new [] { "__MACOS__" } }, - { ApplePlatform.MacCatalyst, new [] { "__MACCATALYST__" } }, + readonly Dictionary platformDefines = new () { + { TargetFramework.DotNet_iOS, new [] { "__IOS__" } }, + { TargetFramework.DotNet_tvOS, new [] { "__TVOS__" } }, + { TargetFramework.DotNet_macOS, new [] { "__MACOS__" } }, + { TargetFramework.DotNet_MacCatalyst, new [] { "__MACCATALYST__" } }, }; public BaseGeneratorTestClass () @@ -45,6 +45,22 @@ protected Compilation RunGeneratorsAndUpdateCompilation (Compilation compilation protected GeneratorDriverRunResult RunGenerators (Compilation compilation) => Driver.RunGenerators (compilation).GetRunResult (); + protected IEnumerable GetPlatformDefines (TargetFramework targetFramework) + { + if (Configuration.TryGetPlatformPreprocessorSymbolsRsp (targetFramework, out var rspFile)) { + var args = new [] { $"@{rspFile}" }; + var workingDirectory = Path.Combine (Configuration.SourceRoot, "src"); + var parseResult = CSharpCommandLineParser.Default.Parse ( + args, null, null); + var frameworkDefines = parseResult.ParseOptions.PreprocessorSymbolNames.ToList (); + // add the platform ones that are not in this rsp + frameworkDefines.AddRange (platformDefines [targetFramework]); + return frameworkDefines; + } + + return []; + } + protected CompilationResult CreateCompilation (ApplePlatform platform, [CallerMemberName] string name = "", params string [] sources) { // get the dotnet bcl and fully load it for the test. @@ -52,6 +68,8 @@ protected CompilationResult CreateCompilation (ApplePlatform platform, [CallerMe .Select (assembly => MetadataReference.CreateFromFile (assembly)).ToList (); // get the dll for the current platform var targetFramework = TargetFramework.GetTargetFramework (platform, isDotNet: true); + // get the platform definitions + var preprocessorSymbols = GetPlatformDefines (targetFramework); var platformDll = Configuration.GetBaseLibrary (targetFramework); if (!string.IsNullOrEmpty (platformDll)) { references.Add (MetadataReference.CreateFromFile (platformDll)); @@ -59,7 +77,7 @@ protected CompilationResult CreateCompilation (ApplePlatform platform, [CallerMe throw new InvalidOperationException ($"Could not find platform dll for {platform}"); } - var parseOptions = new CSharpParseOptions (LanguageVersion.Latest, DocumentationMode.None, preprocessorSymbols: platformDefines [platform]); + var parseOptions = new CSharpParseOptions (LanguageVersion.Latest, DocumentationMode.None, preprocessorSymbols: preprocessorSymbols); var trees = sources.Select (s => CSharpSyntaxTree.ParseText (s, parseOptions)).ToImmutableArray (); var options = new CSharpCompilationOptions (OutputKind.NetModule) diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/ClassGenerationTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/ClassGenerationTests.cs index e88c49c9ae88..eb37750437b2 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/ClassGenerationTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/ClassGenerationTests.cs @@ -21,6 +21,9 @@ public class TestDataGenerator : BaseTestDataGenerator, IEnumerable { (ApplePlatform.MacOSX, "AVAudioPcmBuffer", "AVAudioPcmBufferDefaultCtr.cs", "ExpectedAVAudioPcmBufferDefaultCtr.cs", null), (ApplePlatform.iOS, "AVAudioPcmBuffer", "AVAudioPcmBufferNoNativeName.cs", "ExpectedAVAudioPcmBufferNoNativeName.cs", null), (ApplePlatform.MacOSX, "AVAudioPcmBuffer", "AVAudioPcmBufferNoNativeName.cs", "ExpectedAVAudioPcmBufferNoNativeName.cs", null), + (ApplePlatform.iOS, "CIImage", "CIImage.cs", "ExpectedCIImage.cs", null), + (ApplePlatform.TVOS, "CIImage", "CIImage.cs", "ExpectedCIImage.cs", null), + (ApplePlatform.MacCatalyst, "CIImage", "CIImage.cs", "ExpectedCIImage.cs", null), }; diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/CIImage.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/CIImage.cs new file mode 100644 index 000000000000..8441ffd7d72c --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/CIImage.cs @@ -0,0 +1,39 @@ +using System; +using System.Runtime.Versioning; +using Foundation; +using ObjCBindings; + +namespace TestNamespace; + +[SupportedOSPlatform ("macos")] +[SupportedOSPlatform ("ios11.0")] +[SupportedOSPlatform ("tvos11.0")] + +[BindingType ()] +public partial class CIImage { + + [SupportedOSPlatform ("maccatalyst13.1")] + [Field ("FormatRGBA16Int")] + public static partial int FormatRGBA16Int { get; } + + [SupportedOSPlatform ("maccatalyst13.1")] + [Field ("kCIFormatABGR8")] + public static partial int FormatABGR8 { get; } + + [SupportedOSPlatform ("maccatalyst13.1")] + [Field ("kCIFormatLA8")] + public static partial int FormatLA8 { + get; + + [SupportedOSPlatform ("ios17.0")] + [SupportedOSPlatform ("tvos17.0")] + [SupportedOSPlatform ("macos14.0")] + [SupportedOSPlatform ("maccatalyst17.0")] + set; + } + + [SupportedOSPlatform ("maccatalyst13.1")] + [Field ("kCIFormatLA8", Flags = Property.Notification)] + public static partial NSString DidProcessEditingNotification { get; } + +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/ExpectedCIImage.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/ExpectedCIImage.cs new file mode 100644 index 000000000000..296f006bbd28 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Classes/Data/ExpectedCIImage.cs @@ -0,0 +1,131 @@ +// + +#nullable enable + +using Foundation; +using ObjCBindings; +using ObjCRuntime; +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Threading.Tasks; + +namespace TestNamespace; + +[Register ("CIImage", true)] +public partial class CIImage +{ + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + static readonly NativeHandle class_ptr = Class.GetHandle ("CIImage"); + + public override NativeHandle ClassHandle => class_ptr; + + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + [DesignatedInitializer] + [Export ("init")] + public CIImage () : base (NSObjectFlag.Empty) + { + if (IsDirectBinding) + InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSend (this.Handle, global::ObjCRuntime.Selector.GetHandle ("init")), "init"); + else + InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.Selector.GetHandle ("init")), "init"); + } + + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + [EditorBrowsable (EditorBrowsableState.Advanced)] + protected CIImage (NSObjectFlag t) : base (t) {} + + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + [EditorBrowsable (EditorBrowsableState.Advanced)] + protected internal CIImage (NativeHandle handle) : base (handle) {} + + static Foundation.NSString? _DidProcessEditingNotification; + + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + [Advice ("Use 'CIImage.Notifications.DidProcessEditingNotification' helper method instead.")] + public static partial Foundation.NSString DidProcessEditingNotification + { + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + get + { + if (_DidProcessEditingNotification is null) + _DidProcessEditingNotification = Dlfcn.GetStringConstant (Libraries.TestNamespace.Handle, "kCIFormatLA8")!; + return _DidProcessEditingNotification; + } + } + + + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + public static partial int FormatABGR8 + { + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + get + { + return Dlfcn.GetInt32 (Libraries.TestNamespace.Handle, "kCIFormatABGR8"); + } + } + + + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + public static partial int FormatLA8 + { + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + get + { + return Dlfcn.GetInt32 (Libraries.TestNamespace.Handle, "kCIFormatLA8"); + } + + [SupportedOSPlatform ("macos14.0")] + [SupportedOSPlatform ("ios17.0")] + [SupportedOSPlatform ("tvos17.0")] + [SupportedOSPlatform ("maccatalyst17.0")] + set + { + Dlfcn.SetInt32 (Libraries.TestNamespace.Handle, "kCIFormatLA8", value); + } + } + + + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + [BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)] + public static partial int FormatRGBA16Int + { + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios11.0")] + [SupportedOSPlatform ("tvos11.0")] + [SupportedOSPlatform ("maccatalyst13.1")] + get + { + return Dlfcn.GetInt32 (Libraries.TestNamespace.Handle, "FormatRGBA16Int"); + } + } + // TODO: add binding code here +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Context/RootBindingContextTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Context/RootContextTests.cs similarity index 89% rename from tests/rgen/Microsoft.Macios.Generator.Tests/Context/RootBindingContextTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/Context/RootContextTests.cs index c745391fc579..d5eedd369d52 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Context/RootBindingContextTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Context/RootContextTests.cs @@ -7,7 +7,7 @@ namespace Microsoft.Macios.Generator.Tests.Context; -public class RootBindingContextTests : BaseGeneratorTestClass { +public class RootContextTests : BaseGeneratorTestClass { [Theory] [PlatformInlineData (ApplePlatform.iOS, "+CoreImage", "CoreImage", "CoreImage")] [PlatformInlineData (ApplePlatform.iOS, "+CoreServices", "CoreServices", "MobileCoreServices")] @@ -29,7 +29,7 @@ public class MyClass { "; var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); Assert.Single (compilation.SyntaxTrees); - var rootContext = new RootBindingContext (compilation.GetSemanticModel (syntaxTrees [0])); + var rootContext = new RootContext (compilation.GetSemanticModel (syntaxTrees [0])); Assert.True (rootContext.TryComputeLibraryName (attributeLibName, ns, out var libName, out var libPath)); Assert.Equal (expectedLibraryName, libName); } @@ -51,7 +51,7 @@ public class MyClass { "; var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); Assert.Single (compilation.SyntaxTrees); - var rootContext = new RootBindingContext (compilation.GetSemanticModel (syntaxTrees [0])); + var rootContext = new RootContext (compilation.GetSemanticModel (syntaxTrees [0])); Assert.Equal (rootContext.IsSystemLibrary (lib), expectedResult); } } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/AccessorTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/AccessorTests.cs index 844997aa508c..e1f9a406b4b2 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/AccessorTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/AccessorTests.cs @@ -1,10 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#pragma warning disable APL0003 using Microsoft.CodeAnalysis.CSharp; using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; using Microsoft.Macios.Generator.DataModel; +using ObjCRuntime; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; @@ -308,4 +311,205 @@ public void CompareSameKindSameAttrSameAvailability () Assert.True (x == y); Assert.False (x != y); } + + [Fact] + public void GetSelectorForFieldProperty () + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportFieldData = new (new ("Constant"), "lib"), + }; + + var accessor = new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [ + new ("First"), + new ("Second"), + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PrivateKeyword) + ]); + + Assert.Null (accessor.GetSelector (property)); + } + + [Fact] + public void GetGetterSelectorNoExportData () + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("label") + }; + + var accessor = new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [ + new ("First"), + new ("Second"), + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PrivateKeyword) + ]); + + var selector = accessor.GetSelector (property); + Assert.NotNull (selector); + Assert.Equal (property.ExportPropertyData.Value.Selector, selector); + } + + [Fact] + public void GetGetterSelectorExportData () + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("label") + }; + + var customSelector = "custom"; + var accessor = new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: new (customSelector), + attributes: [ + new ("First"), + new ("Second"), + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PrivateKeyword) + ]); + + var selector = accessor.GetSelector (property); + Assert.NotNull (selector); + Assert.Equal (customSelector, selector); + } + + [Fact] + public void GetSetterSelectorNoExportData () + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("label") + }; + + var accessor = new Accessor ( + accessorKind: AccessorKind.Setter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [ + new ("First"), + new ("Second"), + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PrivateKeyword) + ]); + + var selector = accessor.GetSelector (property); + Assert.NotNull (selector); + Assert.Equal ("setLabel:", selector); + } + + [Fact] + public void GetSetterSelectorExportData () + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("label") + }; + + var customSelector = "setCustom:"; + var accessor = new Accessor ( + accessorKind: AccessorKind.Setter, + symbolAvailability: new (), + exportPropertyData: new (customSelector), + attributes: [ + new ("First"), + new ("Second"), + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PrivateKeyword) + ]); + + var selector = accessor.GetSelector (property); + Assert.NotNull (selector); + Assert.Equal (customSelector, selector); + } + + [Theory] + [InlineData (false, false, false)] + [InlineData (false, true, true)] + [InlineData (true, false, true)] + [InlineData (true, true, true)] + public void ShouldMarshalNativeExceptionsBothFalse (bool propertyHasFlag, bool accessorHasFalg, bool expectedResult) + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ( + selector: "selector", + argumentSemantic: ArgumentSemantic.None, + flags: propertyHasFlag ? ObjCBindings.Property.MarshalNativeExceptions : ObjCBindings.Property.Default), + }; + + var accessor = new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: new ( + selector: "selector", + argumentSemantic: ArgumentSemantic.None, + flags: accessorHasFalg ? ObjCBindings.Property.MarshalNativeExceptions : ObjCBindings.Property.Default), + attributes: [ + new ("First"), + new ("Second"), + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PrivateKeyword) + ]); + Assert.Equal (expectedResult, accessor.ShouldMarshalNativeExceptions (property)); + } + + } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingComparerTests.cs similarity index 95% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesComparerTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingComparerTests.cs index 2a49d96cb44a..9a87bfd4693b 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingComparerTests.cs @@ -5,22 +5,23 @@ using Microsoft.Macios.Generator.Availability; using Microsoft.Macios.Generator.DataModel; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; -public class CodeChangesComparerTests : BaseGeneratorTestClass { - readonly CodeChangesEqualityComparer comparer = new (); +public class BindingComparerTests : BaseGeneratorTestClass { + readonly BindingEqualityComparer comparer = new (); [Fact] public void CompareDifferentFullyQualifiedSymbol () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name1", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS"], @@ -32,7 +33,7 @@ public void CompareDifferentFullyQualifiedSymbol () [Fact] public void CompareDifferentBase () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS"], @@ -40,7 +41,7 @@ public void CompareDifferentBase () symbolAvailability: new ()) { Base = "Base1" }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS"], @@ -54,7 +55,7 @@ public void CompareDifferentBase () [Fact] public void CompareDifferentInterface () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS"], @@ -62,7 +63,7 @@ public void CompareDifferentInterface () symbolAvailability: new ()) { Interfaces = ["IBase1"] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS"], @@ -76,13 +77,13 @@ public void CompareDifferentInterface () [Fact] public void CompareDifferentNameSymbol () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name1", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name2", @namespace: ["NS"], @@ -94,13 +95,13 @@ public void CompareDifferentNameSymbol () [Fact] public void CompareDifferentNamespaceSymbol () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS1"], fullyQualifiedSymbol: "NS.name1", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name1", @namespace: ["NS2"], @@ -112,13 +113,13 @@ public void CompareDifferentNamespaceSymbol () [Fact] public void CompareDifferentBindingType () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -130,13 +131,13 @@ public void CompareDifferentBindingType () [Fact] public void CompareDifferentAttributesLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -152,7 +153,7 @@ public void CompareDifferentAttributesLength () [Fact] public void CompareDifferentAttributes () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -162,7 +163,7 @@ public void CompareDifferentAttributes () new AttributeCodeChange (name: "name", arguments: ["arg1", "arg2"]) ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -178,13 +179,13 @@ public void CompareDifferentAttributes () [Fact] public void CompareDifferentMembersLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -206,7 +207,7 @@ public void CompareDifferentMembersLength () [Fact] public void CompareDifferentMembers () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -222,7 +223,7 @@ public void CompareDifferentMembers () attributes: []) ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -244,7 +245,7 @@ public void CompareDifferentMembers () [Fact] public void CompareDifferentPropertyLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -253,7 +254,7 @@ public void CompareDifferentPropertyLength () EnumMembers = [], Properties = [] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -300,7 +301,7 @@ public void CompareDifferentPropertyLength () [Fact] public void CompareSamePropertiesDiffOrder () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name", symbolAvailability: new ()) { @@ -366,7 +367,7 @@ public void CompareSamePropertiesDiffOrder () ]), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -440,7 +441,7 @@ public void CompareSamePropertiesDiffOrder () [Fact] public void CompareDifferentProperties () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -508,7 +509,7 @@ public void CompareDifferentProperties () ]), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -581,7 +582,7 @@ public void CompareDifferentProperties () [Fact] public void CompareDifferentEventsLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -665,7 +666,7 @@ public void CompareDifferentEventsLength () ]), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -739,7 +740,7 @@ public void CompareDifferentEventsLength () [Fact] public void CompareSameEventsDiffOrder () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -845,7 +846,7 @@ public void CompareSameEventsDiffOrder () ]), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -959,7 +960,7 @@ public void CompareSameEventsDiffOrder () [Fact] public void CompareDifferentEvents () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1043,7 +1044,7 @@ public void CompareDifferentEvents () ]), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1136,7 +1137,7 @@ public void CompareDifferentEvents () [Fact] public void CompareDifferentMethodsLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1261,8 +1262,7 @@ public void CompareDifferentMethodsLength () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -1278,12 +1278,12 @@ public void CompareDifferentMethodsLength () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false) + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input") ] ) ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1407,9 +1407,7 @@ public void CompareDifferentMethodsLength () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, - ReferenceKind = ReferenceKind.Out, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { }, ] ), @@ -1422,7 +1420,7 @@ public void CompareDifferentMethodsLength () [Fact] public void CompareSameMethodsDiffOrder () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1547,8 +1545,7 @@ public void CompareSameMethodsDiffOrder () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -1564,12 +1561,12 @@ public void CompareSameMethodsDiffOrder () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false) + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input") ] ) ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1687,7 +1684,7 @@ public void CompareSameMethodsDiffOrder () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false) + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input") ] ), new ( @@ -1708,8 +1705,7 @@ public void CompareSameMethodsDiffOrder () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -1723,7 +1719,7 @@ public void CompareSameMethodsDiffOrder () [Fact] public void CompareDifferentMethods () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1841,12 +1837,12 @@ public void CompareDifferentMethods () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false), + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input"), ] ), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -1971,8 +1967,7 @@ public void CompareDifferentMethods () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -1989,7 +1984,7 @@ public void CompareSameMethodsDiffAvailability () var builder = SymbolAvailability.CreateBuilder (); builder.Add (new SupportedOSPlatformData ("ios")); builder.Add (new SupportedOSPlatformData ("tvos")); - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -2114,8 +2109,7 @@ public void CompareSameMethodsDiffAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -2131,12 +2125,12 @@ public void CompareSameMethodsDiffAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false) + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input") ] ) ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -2246,7 +2240,7 @@ public void CompareSameMethodsDiffAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false) + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input") ] ), new ( @@ -2267,8 +2261,7 @@ public void CompareSameMethodsDiffAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -2285,7 +2278,7 @@ public void CompareSameMethodsSameAvailability () var builder = SymbolAvailability.CreateBuilder (); builder.Add (new SupportedOSPlatformData ("ios")); builder.Add (new SupportedOSPlatformData ("tvos")); - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -2410,8 +2403,7 @@ public void CompareSameMethodsSameAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -2427,12 +2419,12 @@ public void CompareSameMethodsSameAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false) + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input") ] ) ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], @@ -2549,7 +2541,7 @@ public void CompareSameMethodsSameAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false) + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input") ] ), new ( @@ -2570,8 +2562,7 @@ public void CompareSameMethodsSameAvailability () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesEqualityComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingEqualityComparerTests.cs similarity index 95% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesEqualityComparerTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingEqualityComparerTests.cs index f3a603c06133..27d768a901dc 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesEqualityComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingEqualityComparerTests.cs @@ -3,22 +3,23 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.Macios.Generator.DataModel; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; -public class CodeChangesEqualityComparerTests : BaseGeneratorTestClass { - readonly CodeChangesEqualityComparer equalityComparer = new (); +public class BindingEqualityComparerTests : BaseGeneratorTestClass { + readonly BindingEqualityComparer equalityComparer = new (); [Fact] public void CompareDifferentFullyQualifiedSymbol () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name1", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name1", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name2", @namespace: ["NS"], @@ -30,13 +31,13 @@ public void CompareDifferentFullyQualifiedSymbol () [Fact] public void CompareDifferentBindingType () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.SmartEnum, new ()), name: "name", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -48,13 +49,13 @@ public void CompareDifferentBindingType () [Fact] public void CompareDifferentAttributesLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -70,7 +71,7 @@ public void CompareDifferentAttributesLength () [Fact] public void CompareDifferentAttributes () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -80,7 +81,7 @@ public void CompareDifferentAttributes () new AttributeCodeChange (name: "name", arguments: ["arg1", "arg2"]) ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -96,13 +97,13 @@ public void CompareDifferentAttributes () [Fact] public void CompareDifferentMembersLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], fullyQualifiedSymbol: "NS.name", symbolAvailability: new ()); - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -124,7 +125,7 @@ public void CompareDifferentMembersLength () [Fact] public void CompareDifferentMembers () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -140,7 +141,7 @@ public void CompareDifferentMembers () attributes: []) ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -162,7 +163,7 @@ public void CompareDifferentMembers () [Fact] public void CompareDifferentPropertyLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -171,7 +172,7 @@ public void CompareDifferentPropertyLength () EnumMembers = [], Properties = [] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -218,7 +219,7 @@ public void CompareDifferentPropertyLength () [Fact] public void CompareSamePropertiesDiffOrder () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -286,7 +287,7 @@ public void CompareSamePropertiesDiffOrder () ]), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -360,7 +361,7 @@ public void CompareSamePropertiesDiffOrder () [Fact] public void CompareDifferentProperties () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -428,7 +429,7 @@ public void CompareDifferentProperties () ]), ] }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -502,7 +503,7 @@ public void CompareDifferentProperties () [Fact] public void CompareDifferentConstructorLength () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -571,7 +572,7 @@ public void CompareDifferentConstructorLength () ], Constructors = [], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -648,7 +649,7 @@ public void CompareDifferentConstructorLength () [Fact] public void CompareDifferentConstructors () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -719,7 +720,7 @@ public void CompareDifferentConstructors () new (type: "MyClass", symbolAvailability: new (), attributes: [], modifiers: [], parameters: []) ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -792,7 +793,7 @@ public void CompareDifferentConstructors () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]) ], }; @@ -802,7 +803,7 @@ public void CompareDifferentConstructors () [Fact] public void CompareSameConstructors () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -876,11 +877,11 @@ public void CompareSameConstructors () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]) ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -954,7 +955,7 @@ public void CompareSameConstructors () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]) ], }; @@ -964,7 +965,7 @@ public void CompareSameConstructors () [Fact] public void CompareSameConstructorsDiffOrder () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -1037,12 +1038,12 @@ public void CompareSameConstructorsDiffOrder () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]), new (type: "MyClass", symbolAvailability: new (), attributes: [], modifiers: [], parameters: []), ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -1115,7 +1116,7 @@ public void CompareSameConstructorsDiffOrder () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]), ], }; @@ -1125,7 +1126,7 @@ public void CompareSameConstructorsDiffOrder () [Fact] public void CompareSameDiffModifiers () { - var changes1 = new CodeChanges ( + var changes1 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -1202,12 +1203,12 @@ public void CompareSameDiffModifiers () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]), new (type: "MyClass", symbolAvailability: new (), attributes: [], modifiers: [], parameters: []), ], }; - var changes2 = new CodeChanges ( + var changes2 = new Binding ( bindingInfo: new (BindingType.Protocol, new ()), name: "name", @namespace: ["NS"], @@ -1286,7 +1287,7 @@ public void CompareSameDiffModifiers () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]), ], }; diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingTests.cs similarity index 95% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingTests.cs index 2542637ee4ae..74cd09880ac5 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CodeChangesTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/BindingTests.cs @@ -11,7 +11,7 @@ namespace Microsoft.Macios.Generator.Tests.DataModel; -public class CodeChangesTests : BaseGeneratorTestClass { +public class BindingTests : BaseGeneratorTestClass { class TestDataSkipEnumValueDeclaration : IEnumerable { public IEnumerator GetEnumerator () { @@ -74,7 +74,7 @@ public void SkipEnumValueDeclaration (ApplePlatform platform, string inputText, .FirstOrDefault (); Assert.NotNull (node); var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); - Assert.Equal (expected, CodeChanges.Skip (node, semanticModel)); + Assert.Equal (expected, Binding.Skip (node, semanticModel)); } @@ -183,7 +183,7 @@ public void SkipPropertyDeclaration (ApplePlatform platform, string inputText, b .FirstOrDefault (); Assert.NotNull (node); var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); - Assert.Equal (expected, CodeChanges.Skip (node, semanticModel)); + Assert.Equal (expected, Binding.Skip (node, semanticModel)); } class TestDataSkipMethodDeclaration : IEnumerable { @@ -249,6 +249,6 @@ public void SkipMethodDeclaration (ApplePlatform platform, string inputText, boo .FirstOrDefault (); Assert.NotNull (node); var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); - Assert.Equal (expected, CodeChanges.Skip (node, semanticModel)); + Assert.Equal (expected, Binding.Skip (node, semanticModel)); } } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ClassCodeChangesTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ClassBindingTests.cs similarity index 87% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ClassCodeChangesTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ClassBindingTests.cs index 1d1e5c3a3b0d..07eaacfd8174 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ClassCodeChangesTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ClassBindingTests.cs @@ -20,8 +20,52 @@ namespace Microsoft.Macios.Generator.Tests.DataModel; -public class ClassCodeChangesTests : BaseGeneratorTestClass { - readonly CodeChangesEqualityComparer comparer = new (); +public class ClassBindingTests : BaseGeneratorTestClass { + readonly BindingEqualityComparer comparer = new (); + + [Fact] + public void IsThreadSafe () + { + var binding = new Binding ( + bindingInfo: new (new BindingTypeData (Class.IsThreadSafe)), + name: "MyClass", + @namespace: ["NS"], + fullyQualifiedSymbol: "NS.MyClass", + symbolAvailability: new () + ) { + Base = "object", + Interfaces = ImmutableArray.Empty, + Attributes = [ + new ("ObjCBindings.BindingTypeAttribute") + ], + UsingDirectives = new HashSet { "Foundation", "ObjCRuntime", "ObjCBindings" }, + Modifiers = [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword) + ] + }; + Assert.True (binding.IsThreadSafe); + + binding = new Binding ( + bindingInfo: new (new BindingTypeData ()), + name: "MyClass", + @namespace: ["NS"], + fullyQualifiedSymbol: "NS.MyClass", + symbolAvailability: new () + ) { + Base = "object", + Interfaces = ImmutableArray.Empty, + Attributes = [ + new ("ObjCBindings.BindingTypeAttribute") + ], + UsingDirectives = new HashSet { "Foundation", "ObjCRuntime", "ObjCBindings" }, + Modifiers = [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword) + ] + }; + Assert.False (binding.IsThreadSafe); + } class TestDataCodeChangesFromClassDeclaration : IEnumerable { public IEnumerator GetEnumerator () @@ -45,7 +89,7 @@ public partial class MyClass { yield return [ emptyClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -79,7 +123,7 @@ public partial class MyClass : NSObject { yield return [ emptyClassWithBase, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -115,7 +159,7 @@ public partial class MyClass : NSObject, IMyInterface { yield return [ emptyClassWithBaseWithInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -149,7 +193,7 @@ internal partial class MyClass { yield return [ internalClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -187,7 +231,7 @@ public partial class MyClass { yield return [ emptyClassAvailability, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -225,7 +269,7 @@ public MyClass () {} yield return [ singleConstructorClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -275,7 +319,7 @@ public MyClass(string name) { yield return [ multiConstructorClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -312,9 +356,8 @@ public MyClass(string name) { parameters: [ new ( position: 0, - type: "string", - name: "name", - isBlittable: false + type: ReturnTypeForString (), + name: "name" ) ] ), @@ -336,7 +379,7 @@ public partial class MyClass { yield return [ singlePropertyClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -407,7 +450,7 @@ public partial class MyClass { yield return [ singlePropertySmartEnumClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -477,7 +520,7 @@ public partial class MyClass { yield return [ singlePropertyEnumClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -543,7 +586,7 @@ public partial class MyClass { yield return [ notificationPropertyClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -612,7 +655,7 @@ public partial class MyClass { yield return [ fieldPropertyClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -684,7 +727,7 @@ public partial class MyClass { yield return [ multiPropertyClassMissingExport, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -736,6 +779,78 @@ public partial class MyClass { } ]; + const string customMarshallingProperty = @" +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + [Export (""name"", Flags = Property.CustomMarshalDirective, NativePrefix = ""xamarin_"", Library = ""__Internal"")] + public partial string Name { get; set; } = string.Empty; +} +"; + + yield return [ + customMarshallingProperty, + new Binding ( + bindingInfo: new (new BindingTypeData ()), + name: "MyClass", + @namespace: ["NS"], + fullyQualifiedSymbol: "NS.MyClass", + symbolAvailability: new () + ) { + Base = "object", + Interfaces = ImmutableArray.Empty, + Attributes = [ + new ("ObjCBindings.BindingTypeAttribute") + ], + UsingDirectives = new HashSet { "ObjCBindings" }, + Modifiers = [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword) + ], + Properties = [ + new ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [ + new ("ObjCBindings.ExportAttribute", ["name", "ObjCBindings.Property.CustomMarshalDirective", "xamarin_", "__Internal"]) + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ] + ) { + ExportPropertyData = new ( + selector: "name", + argumentSemantic: ArgumentSemantic.None, + flags: Property.Default | Property.CustomMarshalDirective) { + NativePrefix = "xamarin_", + Library = "__Internal" + } + } + ] + } + ]; + const string multiPropertyClass = @" using ObjCBindings; @@ -753,7 +868,7 @@ public partial class MyClass { yield return [ multiPropertyClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -849,7 +964,7 @@ public partial class MyClass { yield return [ singleMethodClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -881,7 +996,7 @@ public partial class MyClass { SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false) + new (position: 0, type: ReturnTypeForString (), name: "name") ] ), ] @@ -904,7 +1019,7 @@ public void SetSurname (string inSurname) {} yield return [ multiMethodClassMissingExport, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -936,7 +1051,7 @@ public void SetSurname (string inSurname) {} SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false) + new (position: 0, type: ReturnTypeForString (), name: "name") ] ), ] @@ -960,7 +1075,7 @@ public partial class MyClass { "; yield return [ multiMethodClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -992,7 +1107,7 @@ public partial class MyClass { SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false) + new (position: 0, type: ReturnTypeForString (), name: "name") ] ), new ( @@ -1009,7 +1124,7 @@ public partial class MyClass { SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inSurname", isBlittable: false) + new (position: 0, type: ReturnTypeForString (), name: "inSurname") ] ), ] @@ -1031,7 +1146,7 @@ public partial class MyClass { yield return [ singleEventClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -1094,7 +1209,7 @@ public partial class MyClass { yield return [ multiEventClass, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "MyClass", @namespace: ["NS"], @@ -1172,7 +1287,7 @@ public partial class MyClass { [Theory] [AllSupportedPlatformsClassData] - void CodeChangesFromClassDeclaration (ApplePlatform platform, string inputText, CodeChanges expected) + void CodeChangesFromClassDeclaration (ApplePlatform platform, string inputText, Binding expected) { var (compilation, sourceTrees) = CreateCompilation (platform, sources: inputText); Assert.Single (sourceTrees); @@ -1183,7 +1298,7 @@ void CodeChangesFromClassDeclaration (ApplePlatform platform, string inputText, .FirstOrDefault (); Assert.NotNull (node); var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); - var changes = CodeChanges.FromDeclaration (node, semanticModel); + var changes = Binding.FromDeclaration (node, semanticModel); Assert.NotNull (changes); Assert.Equal (expected, changes.Value, comparer); } @@ -1191,7 +1306,7 @@ void CodeChangesFromClassDeclaration (ApplePlatform platform, string inputText, [Fact] public void IsStaticPropertyTest () { - var changes = new CodeChanges ( + var changes = new Binding ( bindingInfo: new (new BindingTypeData ()), name: "name1", @namespace: ["NS"], @@ -1200,7 +1315,7 @@ public void IsStaticPropertyTest () Assert.False (changes.IsStatic); - changes = new CodeChanges ( + changes = new Binding ( bindingInfo: new (new BindingTypeData ()), name: "name1", @namespace: ["NS"], @@ -1218,7 +1333,7 @@ public void IsStaticPropertyTest () [Fact] public void IsPartialPropertyTest () { - var changes = new CodeChanges ( + var changes = new Binding ( bindingInfo: new (new BindingTypeData ()), name: "name1", @namespace: ["NS"], @@ -1227,7 +1342,7 @@ public void IsPartialPropertyTest () Assert.False (changes.IsPartial); - changes = new CodeChanges ( + changes = new Binding ( bindingInfo: new (new BindingTypeData ()), name: "name1", @namespace: ["NS"], @@ -1245,7 +1360,7 @@ public void IsPartialPropertyTest () [Fact] public void IsAbstractPropertyTest () { - var changes = new CodeChanges ( + var changes = new Binding ( bindingInfo: new (new BindingTypeData ()), name: "name1", @namespace: ["NS"], @@ -1254,7 +1369,7 @@ public void IsAbstractPropertyTest () Assert.False (changes.IsAbstract); - changes = new CodeChanges ( + changes = new Binding ( bindingInfo: new (new BindingTypeData ()), name: "name1", @namespace: ["NS"], diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorComparerTests.cs index eb8a18369b9d..c57d129b2a60 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorComparerTests.cs @@ -4,6 +4,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.Macios.Generator.DataModel; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; @@ -128,7 +129,7 @@ public void CompareParameterDiffLength () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]); var y = new Constructor ("MyClass", symbolAvailability: new (), @@ -140,8 +141,8 @@ public void CompareParameterDiffLength () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ]); Assert.Equal (x.Parameters.Length.CompareTo (y.Parameters.Length), comparer.Compare (x, y)); } @@ -159,7 +160,7 @@ public void CompareDiffParameters () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]); var y = new Constructor ("MyClass", symbolAvailability: new (), @@ -171,7 +172,7 @@ public void CompareDiffParameters () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ]); var parameterCompare = new ParameterComparer (); Assert.Equal (parameterCompare.Compare (x.Parameters [0], y.Parameters [0]), comparer.Compare (x, y)); @@ -190,9 +191,7 @@ public void CompareDiffParametersSmartEnum () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "MyEnum", name: "name", isBlittable: false) { - IsSmartEnum = true - }, + new (position: 0, type: ReturnTypeForEnum ("MyEnum", isSmartEnum: true), name: "name"), ]); var y = new Constructor ("MyClass", symbolAvailability: new (), @@ -204,9 +203,7 @@ public void CompareDiffParametersSmartEnum () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "MyEnum", name: "name", isBlittable: false) { - IsSmartEnum = false - }, + new (position: 0, type: ReturnTypeForEnum ("MyEnum"), name: "name"), ]); var parameterCompare = new ParameterComparer (); Assert.Equal (parameterCompare.Compare (x.Parameters [0], y.Parameters [0]), comparer.Compare (x, y)); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorTests.cs index 1866feddd746..ed83a6a3cf96 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorTests.cs @@ -11,6 +11,7 @@ using Xamarin.Tests; using Xamarin.Utils; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; @@ -66,7 +67,7 @@ public TestClass (string inName) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "inName"), ] ) ]; @@ -96,8 +97,8 @@ public TestClass (string inName, int inAge) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false), - new (position: 1, type: "int", name: "inAge", isBlittable: true), + new (position: 0, type: ReturnTypeForString (), name: "inName"), + new (position: 1, type: ReturnTypeForInt (), name: "inAge"), ] ) ]; @@ -127,10 +128,8 @@ public TestClass (string? inName, int inAge) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, - }, - new (position: 1, type: "int", name: "inAge", isBlittable: true), + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName"), + new (position: 1, type: ReturnTypeForInt (), name: "inAge"), ] ) ]; @@ -163,13 +162,10 @@ public TestClass (string? inName, int inAge, params string[] inSurnames) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, - }, - new (position: 1, type: "int", name: "inAge", isBlittable: true), - new (position: 2, type: "string", name: "inSurnames", isBlittable: false) { + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName"), + new (position: 1, type: ReturnTypeForInt (), name: "inAge"), + new (position: 2, type: ReturnTypeForArray ("string"), name: "inSurnames") { IsParams = true, - IsArray = true, }, ] ) @@ -203,13 +199,10 @@ public TestClass (string? inName, int inAge, string[] inSurnames) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, - }, - new (position: 1, type: "int", name: "inAge", isBlittable: true), - new (position: 2, type: "string", name: "inSurnames", isBlittable: false) { + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName"), + new (position: 1, type: ReturnTypeForInt (), name: "inAge"), + new (position: 2, type: ReturnTypeForArray ("string"), name: "inSurnames") { IsParams = false, - IsArray = true }, ] ) @@ -243,14 +236,9 @@ public TestClass (string? inName, int inAge, string[]? inSurnames) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, - }, - new (position: 1, type: "int", name: "inAge", isBlittable: true), - new (position: 2, type: "string", name: "inSurnames", isBlittable: false) { - IsNullable = true, - IsArray = true - }, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName"), + new (position: 1, type: ReturnTypeForInt (), name: "inAge"), + new (position: 2, type: ReturnTypeForArray ("string", isNullable: true), name: "inSurnames"), ] ) ]; @@ -283,14 +271,9 @@ public TestClass (string? inName, int inAge, string?[] inSurnames) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, - }, - new (position: 1, type: "int", name: "inAge", isBlittable: true), - new (position: 2, type: "string?", name: "inSurnames", isBlittable: false) { - IsNullable = false, - IsArray = true - }, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName"), + new (position: 1, type: ReturnTypeForInt (), name: "inAge"), + new (position: 2, type: ReturnTypeForArray ("string?"), name: "inSurnames"), ] ) ]; @@ -323,14 +306,9 @@ public TestClass (string? inName, int inAge, string?[]? inSurnames) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (0, "string", "inName", false) { - IsNullable = true, - }, - new (1, "int", "inAge", true), - new (2, "string?", "inSurnames", false) { - IsNullable = true, - IsArray = true - }, + new (0, ReturnTypeForString (isNullable: true), "inName"), + new (1, ReturnTypeForInt (), "inAge"), + new (2, ReturnTypeForArray ("string?", isNullable: true), "inSurnames"), ] ) ]; @@ -363,13 +341,10 @@ public TestClass (string? inName, int inAge, string[][] inSurnames) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, - }, - new (position: 1, type: "int", name: "inAge", isBlittable: true), - new (position: 2, type: "string[]", name: "inSurnames", isBlittable: false) { + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName"), + new (position: 1, type: ReturnTypeForInt (), name: "inAge"), + new (position: 2, type: ReturnTypeForArray ("string[]"), name: "inSurnames") { IsParams = false, - IsArray = true }, ] ) @@ -398,8 +373,7 @@ public TestClass (string? inName = null) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName") { IsOptional = true, }, ] @@ -429,9 +403,8 @@ public TestClass (T? inName = null) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "T", name: "inName", isBlittable: false) { + new (position: 0, type: ReturnTypeForGeneric ("T", isNullable: true), name: "inName") { IsOptional = true, - IsNullable = true, }, ] ) @@ -466,14 +439,12 @@ public TestClass (string? inName = null) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inName", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "inName") { IsOptional = true, }, ] ) ]; - } IEnumerator IEnumerable.GetEnumerator () diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorsEqualityComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorsEqualityComparerTests.cs index f21926c38cec..5ddfafb092a7 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorsEqualityComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ConstructorsEqualityComparerTests.cs @@ -4,6 +4,7 @@ using Microsoft.Macios.Generator.Availability; using Microsoft.Macios.Generator.DataModel; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; @@ -22,15 +23,15 @@ public void CompareSingleElementDiffParameterCount () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 0, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 0, type: ReturnTypeForString (), name: "surname"), ]); var y = new Constructor ("MyClass", symbolAvailability: new (), attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]); Assert.False (compare.Equals ([x], [y])); } @@ -43,14 +44,14 @@ public void CompareSingleElementSameParameterCountDifferentParams () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "surname"), ]); var y = new Constructor ("MyClass", symbolAvailability: new (), attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]); Assert.False (compare.Equals ([x], [y])); } @@ -63,14 +64,14 @@ public void CompareDifferentConstructorCount () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "surname"), ]); var y = new Constructor ("MyClass", symbolAvailability: new (), attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]); Assert.False (compare.Equals ([x, y], [y])); } @@ -83,14 +84,14 @@ public void CompareSameConstructorsDifferentOrder () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "surname"), ]); var y = new Constructor ("MyClass", symbolAvailability: new (), attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]); Assert.True (compare.Equals ([x, y], [y, x])); } @@ -108,7 +109,7 @@ public void CompareSameConstructorsDifferentAvailability () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "surname"), ]); var yBuilder = SymbolAvailability.CreateBuilder (); @@ -120,7 +121,7 @@ public void CompareSameConstructorsDifferentAvailability () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ]); Assert.False (compare.Equals ([x], [y])); } @@ -138,7 +139,7 @@ public void CompareSameConstructorsSameAvailability () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "surname"), ]); var y = new Constructor ("MyClass", @@ -146,7 +147,7 @@ public void CompareSameConstructorsSameAvailability () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "surname"), ]); Assert.True (compare.Equals ([x], [y])); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CoreImageFilterTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CoreImageFilterTests.cs new file mode 100644 index 000000000000..e1d64424ad94 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/CoreImageFilterTests.cs @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Macios.Generator.Tests.DataModel; + +public class CoreImageFilterTests { + +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/DelegateInfoTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/DelegateInfoTests.cs index 90eed31b510e..46a9559f4833 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/DelegateInfoTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/DelegateInfoTests.cs @@ -18,7 +18,6 @@ public class DelegateInfoTests : BaseGeneratorTestClass { class TestDataFromMethodDeclaration : IEnumerable { public IEnumerator GetEnumerator () { - const string actionNoParam = @" using System; @@ -44,9 +43,8 @@ public void MyMethod (Action cb) {} parameters: [ new ( position: 0, - type: "System.Action", - name: "cb", - isBlittable: false + type: ReturnTypeForAction (), + name: "cb" ) { Delegate = new ( type: "System.Action", @@ -84,9 +82,8 @@ public void MyMethod (Action cb) {} parameters: [ new ( position: 0, - type: "System.Action", - name: "cb", - isBlittable: false + type: ReturnTypeForAction ("string"), + name: "cb" ) { Delegate = new ( type: "System.Action", @@ -130,9 +127,8 @@ public void MyMethod (Action cb) {} parameters: [ new ( position: 0, - type: "System.Action", - name: "cb", - isBlittable: false + type: ReturnTypeForAction ("string?"), + name: "cb" ) { Delegate = new ( type: "System.Action", @@ -178,9 +174,8 @@ public void MyMethod (Action cb) {} parameters: [ new ( position: 0, - type: "System.Action", - name: "cb", - isBlittable: false + type: ReturnTypeForAction ("string", "string"), + name: "cb" ) { Delegate = new ( type: "System.Action", @@ -230,9 +225,8 @@ public void MyMethod (Func cb) {} parameters: [ new ( position: 0, - type: "System.Func", - name: "cb", - isBlittable: false + type: ReturnTypeForFunc ("string", "string"), + name: "cb" ) { Delegate = new ( type: "System.Func", @@ -276,9 +270,8 @@ public void MyMethod (Func cb) {} parameters: [ new ( position: 0, - type: "System.Func", - name: "cb", - isBlittable: false + type: ReturnTypeForFunc ("string", "string", "string"), + name: "cb" ) { Delegate = new ( type: "System.Func", @@ -330,9 +323,8 @@ public void MyMethod (Callback cb) {} parameters: [ new ( position: 0, - type: "NS.MyClass.Callback", - name: "cb", - isBlittable: false + type: ReturnTypeForDelegate ("NS.MyClass.Callback"), + name: "cb" ) { Delegate = new ( type: "NS.MyClass.Callback", diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumDeclarationCodeChangesTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumDeclarationCodeChangesTests.cs index 17dee7248e2c..937a090a4e1a 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumDeclarationCodeChangesTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumDeclarationCodeChangesTests.cs @@ -10,7 +10,7 @@ namespace Microsoft.Macios.Generator.Tests.DataModel; public class EnumDeclarationCodeChangesTests : BaseGeneratorTestClass { - CodeChanges CreateCodeChanges (ApplePlatform platform, string name, string inputText) + Binding CreateCodeChanges (ApplePlatform platform, string name, string inputText) { var (compilation, sourceTrees) = CreateCompilation (platform, sources: inputText); Assert.Single (sourceTrees); @@ -20,7 +20,7 @@ CodeChanges CreateCodeChanges (ApplePlatform platform, string name, string input .FirstOrDefault (); Assert.NotNull (enumDeclaration); var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); - var codeChange = CodeChanges.FromDeclaration (enumDeclaration, semanticModel); + var codeChange = Binding.FromDeclaration (enumDeclaration, semanticModel); Assert.NotNull (codeChange); return codeChange.Value; } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumMemberCodeChangesTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumMemberCodeChangesTests.cs index 880bf2be4e3f..b7c5b6f8a195 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumMemberCodeChangesTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EnumMemberCodeChangesTests.cs @@ -281,7 +281,7 @@ public IEnumerator GetEnumerator () attributes: []); yield return [ fieldDataEnum, - "{ Name: 'EnumValue' SymbolAvailability: [] FieldInfo: FieldData = { SymbolName: 'x' LibraryName: 'libName', Flags: 'Default' }, LibraryName = Test, LibraryPath = /path/to/library Attributes: [] }" + "{ Name: 'EnumValue' SymbolAvailability: [] FieldInfo: FieldData = { SymbolName: 'x', LibraryName: 'libName', Flags: 'Default' }, LibraryName = Test, LibraryPath = /path/to/library Attributes: [] }" ]; var builder = SymbolAvailability.CreateBuilder (); @@ -296,7 +296,7 @@ public IEnumerator GetEnumerator () attributes: []); yield return [ availabilityEnum, - "{ Name: 'EnumValue' SymbolAvailability: [{ Platform: 'iOS', Supported: '0.0', Unsupported: [], Obsoleted: [] }] FieldInfo: FieldData = { SymbolName: 'x' LibraryName: 'libName', Flags: 'Default' }, LibraryName = Test, LibraryPath = /path/to/library Attributes: [] }" + "{ Name: 'EnumValue' SymbolAvailability: [{ Platform: 'iOS', Supported: '0.0', Unsupported: [], Obsoleted: [] }] FieldInfo: FieldData = { SymbolName: 'x', LibraryName: 'libName', Flags: 'Default' }, LibraryName = Test, LibraryPath = /path/to/library Attributes: [] }" ]; var attrsEnum = new EnumMember ( @@ -311,7 +311,7 @@ public IEnumerator GetEnumerator () ]); yield return [ attrsEnum, - "{ Name: 'EnumValue' SymbolAvailability: [{ Platform: 'iOS', Supported: '0.0', Unsupported: [], Obsoleted: [] }] FieldInfo: FieldData = { SymbolName: 'x' LibraryName: 'libName', Flags: 'Default' }, LibraryName = Test, LibraryPath = /path/to/library Attributes: [{ Name: Attribute1, Arguments: [] }, { Name: Attribute2, Arguments: [] }] }" + "{ Name: 'EnumValue' SymbolAvailability: [{ Platform: 'iOS', Supported: '0.0', Unsupported: [], Obsoleted: [] }] FieldInfo: FieldData = { SymbolName: 'x', LibraryName: 'libName', Flags: 'Default' }, LibraryName = Test, LibraryPath = /path/to/library Attributes: [{ Name: Attribute1, Arguments: [] }, { Name: Attribute2, Arguments: [] }] }" ]; } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EventTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EventTests.cs index f95a4c1035e7..ca5677179e2f 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EventTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/EventTests.cs @@ -210,8 +210,8 @@ public class TestClass { ], accessors: [ new ( - accessorKind: AccessorKind.Add - , symbolAvailability: new (), + accessorKind: AccessorKind.Add, + symbolAvailability: eventAvailabilityBuilder.ToImmutable (), exportPropertyData: null, attributes: [], modifiers: [] diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/InterfaceCodeChangesTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/InterfaceCodeChangesTests.cs index d952ab77f3ff..f9b7cd53d309 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/InterfaceCodeChangesTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/InterfaceCodeChangesTests.cs @@ -3,12 +3,14 @@ #pragma warning disable APL0003 using System.Collections; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.DataModel; using ObjCBindings; +using ObjCRuntime; using Xamarin.Tests; using Xamarin.Utils; using Xunit; @@ -18,7 +20,51 @@ namespace Microsoft.Macios.Generator.Tests.DataModel; public class InterfaceCodeChangesTests : BaseGeneratorTestClass { - readonly CodeChangesEqualityComparer comparer = new (); + readonly BindingEqualityComparer comparer = new (); + + [Fact] + public void IsThreadSafe () + { + var binding = new Binding ( + bindingInfo: new (new BindingTypeData (Protocol.IsThreadSafe)), + name: "MyClass", + @namespace: ["NS"], + fullyQualifiedSymbol: "NS.MyClass", + symbolAvailability: new () + ) { + Base = "object", + Interfaces = ImmutableArray.Empty, + Attributes = [ + new ("ObjCBindings.BindingTypeAttribute") + ], + UsingDirectives = new HashSet { "Foundation", "ObjCRuntime", "ObjCBindings" }, + Modifiers = [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword) + ] + }; + Assert.True (binding.IsThreadSafe); + + binding = new Binding ( + bindingInfo: new (new BindingTypeData ()), + name: "MyClass", + @namespace: ["NS"], + fullyQualifiedSymbol: "NS.MyClass", + symbolAvailability: new () + ) { + Base = "object", + Interfaces = ImmutableArray.Empty, + Attributes = [ + new ("ObjCBindings.BindingTypeAttribute") + ], + UsingDirectives = new HashSet { "Foundation", "ObjCRuntime", "ObjCBindings" }, + Modifiers = [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword) + ] + }; + Assert.False (binding.IsThreadSafe); + } class TestDataCodeChangesFromClassDeclaration : IEnumerable { public IEnumerator GetEnumerator () @@ -37,7 +83,7 @@ public partial interface IProtocol { yield return [ emptyInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -69,7 +115,7 @@ internal partial interface IProtocol { yield return [ internalInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -101,7 +147,7 @@ public partial interface IProtocol { yield return [ singlePropertyInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -170,7 +216,7 @@ public partial interface IProtocol { yield return [ singlePropertySmartEnumInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -238,7 +284,7 @@ public partial interface IProtocol { yield return [ singlePropertyEnumInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -302,7 +348,7 @@ public partial interface IProtocol { yield return [ notificationPropertyInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -370,7 +416,7 @@ public partial interface IProtocol { yield return [ multiPropertyInterfaceMissingExport, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -420,6 +466,78 @@ public partial interface IProtocol { } ]; + const string customMarshallingProperty = @" +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial interface MyClass { + [Export (""name"", Flags = Property.CustomMarshalDirective, NativePrefix = ""xamarin_"", Library = ""__Internal"")] + public partial string Name { get; set; } = string.Empty; +} +"; + + yield return [ + customMarshallingProperty, + new Binding ( + bindingInfo: new (new BindingTypeData ()), + name: "MyClass", + @namespace: ["NS"], + fullyQualifiedSymbol: "NS.MyClass", + symbolAvailability: new () + ) { + Base = null, + Interfaces = [], + Attributes = [ + new ("ObjCBindings.BindingTypeAttribute") + ], + UsingDirectives = new HashSet { "ObjCBindings" }, + Modifiers = [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword) + ], + Properties = [ + new ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [ + new ("ObjCBindings.ExportAttribute", ["name", "ObjCBindings.Property.CustomMarshalDirective", "xamarin_", "__Internal"]) + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + SyntaxFactory.Token (SyntaxKind.PartialKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ] + ) { + ExportPropertyData = new ( + selector: "name", + argumentSemantic: ArgumentSemantic.None, + flags: Property.Default | Property.CustomMarshalDirective) { + NativePrefix = "xamarin_", + Library = "__Internal" + } + } + ] + } + ]; + const string multiPropertyInterface = @" using ObjCBindings; @@ -437,7 +555,7 @@ public partial interface IProtocol { yield return [ multiPropertyInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -531,7 +649,7 @@ public partial interface IProtocol { yield return [ singleMethodInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -561,7 +679,7 @@ public partial interface IProtocol { SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ] ), ] @@ -584,7 +702,7 @@ public void SetSurname (string inSurname) {} yield return [ multiMethodInterfaceMissingExport, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -614,7 +732,7 @@ public void SetSurname (string inSurname) {} SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ] ), ] @@ -638,7 +756,7 @@ public partial interface IProtocol { "; yield return [ multiMethodInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -668,7 +786,7 @@ public partial interface IProtocol { SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ] ), new ( @@ -685,7 +803,7 @@ public partial interface IProtocol { SyntaxFactory.Token (SyntaxKind.PartialKeyword), ], parameters: [ - new (position: 0, type: "string", name: "inSurname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "inSurname"), ] ), ] @@ -707,7 +825,7 @@ public partial interface IProtocol { yield return [ singleEventInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -768,7 +886,7 @@ public partial interface IProtocol { yield return [ multiEventInterface, - new CodeChanges ( + new Binding ( bindingInfo: new (new BindingTypeData ()), name: "IProtocol", @namespace: ["NS"], @@ -844,7 +962,7 @@ public partial interface IProtocol { [Theory] [AllSupportedPlatformsClassData] - void CodeChangesFromInterfaceDeclaration (ApplePlatform platform, string inputText, CodeChanges expected) + void CodeChangesFromInterfaceDeclaration (ApplePlatform platform, string inputText, Binding expected) { var (compilation, sourceTrees) = CreateCompilation (platform, sources: inputText); @@ -856,7 +974,7 @@ void CodeChangesFromInterfaceDeclaration (ApplePlatform platform, string inputTe .FirstOrDefault (); Assert.NotNull (node); var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); - var changes = CodeChanges.FromDeclaration (node, semanticModel); + var changes = Binding.FromDeclaration (node, semanticModel); Assert.NotNull (changes); Assert.Equal (expected, changes.Value, comparer); } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodComparerTests.cs index dd757315d893..d53701ada804 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodComparerTests.cs @@ -4,6 +4,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.Macios.Generator.DataModel; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; @@ -253,7 +254,7 @@ public void CompareParameterDiffLength () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ] ); @@ -270,8 +271,8 @@ public void CompareParameterDiffLength () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ); Assert.Equal (x.Parameters.Length.CompareTo (y.Parameters.Length), comparer.Compare (x, y)); @@ -293,7 +294,7 @@ public void CompareDiffParameters () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ] ); @@ -310,7 +311,7 @@ public void CompareDiffParameters () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ); var parameterCompare = new ParameterComparer (); @@ -333,9 +334,7 @@ public void CompareDiffParametersSmartEnum () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "MyEnum", name: "name", isBlittable: false) { - IsSmartEnum = true - }, + new (position: 0, type: ReturnTypeForEnum ("MyEnum", isSmartEnum: true), name: "name"), ] ); @@ -352,9 +351,7 @@ public void CompareDiffParametersSmartEnum () SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "MyEnum", name: "name", isBlittable: false) { - IsSmartEnum = false - }, + new (position: 0, type: ReturnTypeForEnum ("MyEnum"), name: "name"), ] ); var parameterCompare = new ParameterComparer (); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodEqualityComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodEqualityComparerTests.cs index b8c530b4c7ac..2fa98c191ba7 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodEqualityComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodEqualityComparerTests.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using Microsoft.Macios.Generator.DataModel; using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; namespace Microsoft.Macios.Generator.Tests.DataModel; @@ -116,8 +117,8 @@ public void CompareSingleElementDifferentParameterCount () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ) ]; @@ -131,7 +132,7 @@ public void CompareSingleElementDifferentParameterCount () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), ] ) ]; @@ -151,8 +152,8 @@ public void CompareSingleElementDifferentParameterType () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ) ]; @@ -166,8 +167,8 @@ public void CompareSingleElementDifferentParameterType () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -187,8 +188,8 @@ public void CompareDifferentMethodCount () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ), new ( @@ -200,8 +201,8 @@ public void CompareDifferentMethodCount () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -215,8 +216,8 @@ public void CompareDifferentMethodCount () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -236,8 +237,8 @@ public void CompareSameMethodNamesDiffReturnTypes () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -251,8 +252,8 @@ public void CompareSameMethodNamesDiffReturnTypes () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -272,8 +273,8 @@ public void CompareSameMethods () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ), new ( @@ -285,8 +286,8 @@ public void CompareSameMethods () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -300,8 +301,8 @@ public void CompareSameMethods () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ), new ( @@ -313,8 +314,8 @@ public void CompareSameMethods () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -335,8 +336,8 @@ public void CompareSameMethodsDifferentOrder () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ), new ( @@ -348,8 +349,8 @@ public void CompareSameMethodsDifferentOrder () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ) ]; @@ -363,8 +364,8 @@ public void CompareSameMethodsDifferentOrder () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "int", name: "name", isBlittable: false), - new (position: 1, type: "int", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForInt (), name: "name"), + new (position: 1, type: ReturnTypeForInt (), name: "surname"), ] ), new ( @@ -376,8 +377,8 @@ public void CompareSameMethodsDifferentOrder () attributes: [], modifiers: [], parameters: [ - new (position: 0, type: "string", name: "name", isBlittable: false), - new (position: 1, type: "string", name: "surname", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "name"), + new (position: 1, type: ReturnTypeForString (), name: "surname"), ] ), ]; diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests.cs index 444bba85bc98..d1812cf5fea4 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests.cs @@ -1,5 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + +#pragma warning disable APL0003 using System.Collections; using System.Collections.Generic; using System.Linq; @@ -8,6 +10,7 @@ using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; using Microsoft.Macios.Generator.DataModel; +using ObjCRuntime; using Xamarin.Tests; using Xamarin.Utils; using Xunit; @@ -16,6 +19,38 @@ namespace Microsoft.Macios.Generator.Tests.DataModel; public class MethodTests : BaseGeneratorTestClass { + + [Fact] + public void IsThreadSafe () + { + var method = new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + exportMethodData: new ("selector", ArgumentSemantic.None, ObjCBindings.Method.IsThreadSafe), + attributes: [], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [] + ); + Assert.True (method.IsThreadSafe); + + method = new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + exportMethodData: new ("selector", ArgumentSemantic.None, ObjCBindings.Method.Default), + attributes: [], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [] + ); + Assert.False (method.IsThreadSafe); + } class TestDataFromMethodDeclaration : IEnumerable { public IEnumerator GetEnumerator () { @@ -153,7 +188,7 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "input", isBlittable: false), + new (position: 0, type: ReturnTypeForString (), name: "input"), ] ) ]; @@ -181,9 +216,7 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "input", isBlittable: false) { - IsArray = true - } + new (position: 0, type: ReturnTypeForArray ("string"), name: "input") ] ) ]; @@ -211,10 +244,7 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "input", isBlittable: false) { - IsArray = true, - IsNullable = true, - } + new (position: 0, type: ReturnTypeForArray ("string", isNullable: true), name: "input") ] ) ]; @@ -242,10 +272,7 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "input", isBlittable: false) { - IsArray = true, - IsNullable = false, - } + new (position: 0, type: ReturnTypeForArray ("string?"), name: "input") ] ) ]; @@ -273,10 +300,7 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string?", name: "input", isBlittable: false) { - IsArray = true, - IsNullable = true, - } + new (position: 0, type: ReturnTypeForArray ("string?", isNullable: true), name: "input") ] ) ]; @@ -304,9 +328,7 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string[]", name: "input", isBlittable: false) { - IsArray = true - } + new (position: 0, type: ReturnTypeForArray ("string[]"), name: "input") ] ) ]; @@ -337,7 +359,7 @@ public void MyMethod (CustomType input) {} SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.CustomType", name: "input", isBlittable: false), + new (position: 0, type: ReturnTypeForClass ("NS.CustomType"), name: "input"), ] ) ]; @@ -366,10 +388,8 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "input", isBlittable: false), - new (position: 1, type: "string", name: "second", isBlittable: false) { - IsNullable = true, - } + new (position: 0, type: ReturnTypeForString (), name: "input"), + new (position: 1, type: ReturnTypeForString (isNullable: true), name: "second") ] ) ]; @@ -399,8 +419,7 @@ public bool TryGetString (out string? example) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, }, ] @@ -438,7 +457,7 @@ public void MyMethod (in MyStruct data) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.MyStruct", name: "data", isBlittable: false) { + new (position: 0, type: ReturnTypeForStruct ("NS.MyStruct"), name: "data") { ReferenceKind = ReferenceKind.In, }, ] @@ -475,7 +494,7 @@ public void MyMethod (ref MyStruct data) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "NS.MyStruct", name: "data", isBlittable: false) { + new (position: 0, type: ReturnTypeForStruct ("NS.MyStruct"), name: "data") { ReferenceKind = ReferenceKind.Ref, }, ] @@ -511,10 +530,8 @@ public class MyClass { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "input", isBlittable: false), - new (position: 1, type: "string", name: "second", isBlittable: false) { - IsNullable = true, - } + new (position: 0, type: ReturnTypeForString (), name: "input"), + new (position: 1, type: ReturnTypeForString (isNullable: true), name: "second") ] ) ]; @@ -547,8 +564,7 @@ public bool TryGetString ([NotNullWhen (true)] out string? example) { SyntaxFactory.Token (SyntaxKind.PublicKeyword), ], parameters: [ - new (position: 0, type: "string", name: "example", isBlittable: false) { - IsNullable = true, + new (position: 0, type: ReturnTypeForString (isNullable: true), name: "example") { ReferenceKind = ReferenceKind.Out, Attributes = [ new (name: "System.Diagnostics.CodeAnalysis.NotNullWhenAttribute", arguments: ["true"]) @@ -557,6 +573,75 @@ public bool TryGetString ([NotNullWhen (true)] out string? example) { ] ) ]; + + const string returnTypeBindFromAttribute = @" +using System; +using Foundation; +using ObjCBindings; + +namespace NS { + public class MyClass { + [return: BindFrom (typeof(NSNumber))] + public int MyMethod () {} + } +} +"; + + yield return [ + returnTypeBindFromAttribute, + new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForInt (), + symbolAvailability: new (), + exportMethodData: new (), + attributes: [ + new ("ObjCBindings.BindFromAttribute", ["Foundation.NSNumber"]), + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [] + ) { + BindAs = new ("Foundation.NSNumber"), + } + ]; + + const string parameterBindFromAttr = @" +using System; +using Foundation; +using ObjCBindings; + +namespace NS { + public class MyClass { + public void MyMethod ([BindFrom (typeof(NSNumber))] int value) {} + } +} +"; + + yield return [ + parameterBindFromAttr, + new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + exportMethodData: new (), + attributes: [ + ], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [ + new (0, ReturnTypeForInt (), "value") { + Attributes = [ + new ("ObjCBindings.BindFromAttribute", ["Foundation.NSNumber"]), + ], + BindAs = new BindFromData ("Foundation.NSNumber"), + } + ] + ) + ]; } IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ParameterTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ParameterTests.cs new file mode 100644 index 000000000000..da8014f77cc9 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/ParameterTests.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using Microsoft.Macios.Generator.DataModel; +using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; + +namespace Microsoft.Macios.Generator.Tests.DataModel; + +public class ParameterTests { + + class TestDataGetVariableName : IEnumerable { + public IEnumerator GetEnumerator () + { + var exampleParameter = new Parameter (0, ReturnTypeForBool (), "firstParameter"); + yield return [exampleParameter, Parameter.VariableType.Handle, $"{exampleParameter.Name}__handle__"]; + yield return [exampleParameter, Parameter.VariableType.BlockLiteral, $"block_ptr_{exampleParameter.Name}"]; + yield return [exampleParameter, Parameter.VariableType.PrimitivePointer, $"converted_{exampleParameter.Name}"]; + yield return [exampleParameter, Parameter.VariableType.NSArray, $"nsa_{exampleParameter.Name}"]; + yield return [exampleParameter, Parameter.VariableType.NSString, $"ns{exampleParameter.Name}"]; + yield return [exampleParameter, Parameter.VariableType.NSStringStruct, $"_s{exampleParameter.Name}"]; + yield return [exampleParameter, Parameter.VariableType.BindFrom, $"nsb_{exampleParameter.Name}"]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetVariableName))] + void GetNameForVariableTypeTests (Parameter parameter, Parameter.VariableType variableType, string expectedName) + => Assert.Equal (expectedName, parameter.GetNameForVariableType (variableType)); + + class TestDataNeedsNullCheckTests : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + new Parameter (0, ReturnTypeForBool (), "firstParameter"), + false, + ]; + + yield return [ + new Parameter (0, ReturnTypeForInt (), "firstParameter"), + false, + ]; + + yield return [ + new Parameter (0, ReturnTypeForInt (isNullable: true), "firstParameter"), + false, + ]; + + yield return [ + new Parameter (0, ReturnTypeForString (), "firstParameter"), + true, + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("MyStruct"), "firstParameter"), + false, + ]; + + yield return [ + new Parameter (0, ReturnTypeForClass ("MyClass"), "firstParameter") { + ReferenceKind = ReferenceKind.Ref + }, + false, + ]; + + yield return [ + new Parameter (0, ReturnTypeForArray ("MyClass"), "firstParameter"), + true, + ]; + + yield return [ + new Parameter (0, ReturnTypeForInterface ("IMyClass"), "firstParameter"), + true, + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataNeedsNullCheckTests))] + void NeedsNullCheckTests (Parameter parameter, bool expectedNeedsNullCheck) + => Assert.Equal (expectedNeedsNullCheck, parameter.NeedsNullCheck); +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests.cs index 1b89cc212c3b..ef4187730fc2 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests.cs @@ -9,6 +9,7 @@ using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; using Microsoft.Macios.Generator.DataModel; +using ObjCRuntime; using Xamarin.Tests; using Xamarin.Utils; using Xunit; @@ -36,6 +37,34 @@ public void BackingFieldTests (string propertyName) Assert.Equal ($"_{propertyName}", property.BackingField); } + [Fact] + public void IsThreadSafeProperty () + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("myProperty", ArgumentSemantic.None, ObjCBindings.Property.IsThreadSafe) + }; + Assert.True (property.IsThreadSafe); + + property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("myProperty", ArgumentSemantic.None, ObjCBindings.Property.Default) + }; + Assert.False (property.IsThreadSafe); + } + [Fact] public void CompareDiffName () { @@ -444,6 +473,44 @@ public class TestClass { } ]; + const string marshallNativeException = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + + [Export(""name"", Property.MarshalNativeExceptions)] + public string Name { get; } +} +"; + yield return [ + marshallNativeException, + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [ + new ("ObjCBindings.ExportAttribute", ["name", "ObjCBindings.Property.MarshalNativeExceptions"]) + ], + modifiers: [ + SyntaxFactory.Token (kind: SyntaxKind.PublicKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ) + ] + ) { + ExportPropertyData = new (selector: "name", ArgumentSemantic.None, ObjCBindings.Property.MarshalNativeExceptions), + } + ]; + const string valueTypeProperty = @" using System; using ObjCBindings; @@ -839,14 +906,14 @@ public string Name { accessors: [ new ( accessorKind: AccessorKind.Getter, - symbolAvailability: new (), + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), exportPropertyData: null, attributes: [], modifiers: [] ), new ( accessorKind: AccessorKind.Setter, - symbolAvailability: new (), + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), exportPropertyData: null, attributes: [], modifiers: [] @@ -899,7 +966,7 @@ public string Name { ), new ( accessorKind: AccessorKind.Setter, - symbolAvailability: new (), + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), exportPropertyData: null, attributes: [], modifiers: [] @@ -1025,6 +1092,285 @@ public Utils.MyClass Name { ), ]) ]; + + const string autoPropertyGetterWithAttribute = @" +using System.Runtime.Versioning; +using ObjCBindings; + +namespace Test; + +public class TestClass { + const string name = ""Test""; + + [SupportedOSPlatform (""ios"")] + public string Name { + [SupportedOSPlatform (""ios17.0"")] + get; + set; + } +} +"; + getterAvailabilityBuilder.Clear (); + getterAvailabilityBuilder.Add (supportedPlatform: new SupportedOSPlatformData (platformName: "ios17.0")); + yield return [ + autoPropertyGetterWithAttribute, + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), + attributes: [ + new (name: "System.Runtime.Versioning.SupportedOSPlatformAttribute", arguments: ["ios"]), + ], + modifiers: [ + SyntaxFactory.Token (kind: SyntaxKind.PublicKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: getterAvailabilityBuilder.ToImmutable (), + exportPropertyData: null, + attributes: [ + new (name: "System.Runtime.Versioning.SupportedOSPlatformAttribute", arguments: ["ios17.0"]), + ], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ]) + ]; + + const string staticAutoPropertyGetterWithAttribute = @" +using System.Runtime.Versioning; +using ObjCBindings; + +namespace Test; + +public class TestClass { + const string name = ""Test""; + + [SupportedOSPlatform (""ios"")] + public static string Name { + [SupportedOSPlatform (""ios17.0"")] + get; + set; + } +} +"; + getterAvailabilityBuilder.Clear (); + getterAvailabilityBuilder.Add (supportedPlatform: new SupportedOSPlatformData (platformName: "ios17.0")); + yield return [ + staticAutoPropertyGetterWithAttribute, + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), + attributes: [ + new (name: "System.Runtime.Versioning.SupportedOSPlatformAttribute", arguments: ["ios"]), + ], + modifiers: [ + SyntaxFactory.Token (kind: SyntaxKind.PublicKeyword), + SyntaxFactory.Token (kind: SyntaxKind.StaticKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: getterAvailabilityBuilder.ToImmutable (), + exportPropertyData: null, + attributes: [ + new (name: "System.Runtime.Versioning.SupportedOSPlatformAttribute", arguments: ["ios17.0"]), + ], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ]) + ]; + + const string partialStaticAutoPropertyGetterWithAttribute = @" +using System.Runtime.Versioning; +using ObjCBindings; + +namespace Test; + +public class TestClass { + const string name = ""Test""; + + [SupportedOSPlatform (""ios"")] + public static partial string Name { + [SupportedOSPlatform (""ios17.0"")] + get; + set; + } +} +"; + getterAvailabilityBuilder.Clear (); + getterAvailabilityBuilder.Add (supportedPlatform: new SupportedOSPlatformData (platformName: "ios17.0")); + yield return [ + partialStaticAutoPropertyGetterWithAttribute, + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), + attributes: [ + new (name: "System.Runtime.Versioning.SupportedOSPlatformAttribute", arguments: ["ios"]), + ], + modifiers: [ + SyntaxFactory.Token (kind: SyntaxKind.PublicKeyword), + SyntaxFactory.Token (kind: SyntaxKind.StaticKeyword), + SyntaxFactory.Token (kind: SyntaxKind.PartialKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: getterAvailabilityBuilder.ToImmutable (), + exportPropertyData: null, + attributes: [ + new (name: "System.Runtime.Versioning.SupportedOSPlatformAttribute", arguments: ["ios17.0"]), + ], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: propertyAvailabilityBuilder.ToImmutable (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ]) + ]; + + const string nsObjectProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace Test; + +public class TestClass { + + [Export(""name"")] + public NSObject Name { get; } +} +"; + yield return [ + nsObjectProperty, + new Property ( + name: "Name", + returnType: ReturnTypeForNSObject (), + symbolAvailability: new (), + attributes: [ + new (name: "ObjCBindings.ExportAttribute", arguments: ["name"]), + ], + modifiers: [ + SyntaxFactory.Token (kind: SyntaxKind.PublicKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ) + ] + ) { + NeedsBackingField = true, + RequiresDirtyCheck = true, + ExportPropertyData = new (selector: "name"), + } + ]; + + const string nsObjectArrayProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace Test; + +public class TestClass { + + [Export(""name"")] + public NSObject[] Name { get; } +} +"; + yield return [ + nsObjectArrayProperty, + new Property ( + name: "Name", + returnType: ReturnTypeForArray ("Foundation.NSObject"), + symbolAvailability: new (), + attributes: [ + new (name: "ObjCBindings.ExportAttribute", arguments: ["name"]), + ], + modifiers: [ + SyntaxFactory.Token (kind: SyntaxKind.PublicKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ) + ] + ) { + NeedsBackingField = true, + RequiresDirtyCheck = true, + ExportPropertyData = new (selector: "name"), + } + ]; + + const string bindFromAttribute = @" +using System; +using Foundation; +using ObjCBindings; + +namespace Test; + +public class TestClass { + + [Export(""name""), BindFrom (typeof(NSNumber))] + public int Name { get; } +} +"; + yield return [ + bindFromAttribute, + new Property ( + name: "Name", + returnType: ReturnTypeForInt (), + symbolAvailability: new (), + attributes: [ + new (name: "ObjCBindings.ExportAttribute", arguments: ["name"]), + new (name: "ObjCBindings.BindFromAttribute", arguments: ["Foundation.NSNumber"]), + ], + modifiers: [ + SyntaxFactory.Token (kind: SyntaxKind.PublicKeyword), + ], + accessors: [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ) + ] + ) { + ExportPropertyData = new (selector: "name"), + BindAs = new ("Foundation.NSNumber"), + } + ]; } IEnumerator IEnumerable.GetEnumerator () diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoComparerTests.cs index 572008f199ff..297f076e1366 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoComparerTests.cs @@ -15,7 +15,7 @@ public void CompareDiffReturnType () { var x = new TypeInfo ("string"); var y = new TypeInfo ("int"); - Assert.Equal (String.Compare (x.Name, y.Name, StringComparison.Ordinal), compare.Compare (x, y)); + Assert.Equal (String.Compare (x.FullyQualifiedName, y.FullyQualifiedName, StringComparison.Ordinal), compare.Compare (x, y)); } [Fact] diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoTests.cs index cf7d16b940b0..05e9ff31edec 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoTests.cs @@ -322,6 +322,67 @@ public class MyClass { parameters: [] ) ]; + + const string interfaceMethod = @" +using System; +using System.Collections.Generic; + +namespace NS { + public interface IInterface {} + + public class MyClass { + public IInterface MyMethod () {} + } +} +"; + yield return [ + interfaceMethod, + new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForInterface ("NS.IInterface"), + symbolAvailability: new (), + exportMethodData: new (), + attributes: [], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [] + ) + ]; + + const string nativeEnumMethod = @" +using System; +using ObjCRuntime; +using System.Collections.Generic; + +namespace NS { + [Native] + public enum MyEnum : int { + One, + Two + } + + public class MyClass { + public MyEnum MyMethod () {} + } +} +"; + yield return [ + nativeEnumMethod, + new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForEnum ("NS.MyEnum", isNativeEnum: true), + symbolAvailability: new (), + exportMethodData: new (), + attributes: [], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [] + ) + ]; } IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoToMarshallTypeTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoToMarshallTypeTests.cs new file mode 100644 index 000000000000..6f50de75e446 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/TypeInfoToMarshallTypeTests.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using Xunit; + +namespace Microsoft.Macios.Generator.Tests.DataModel; + +public class TypeInfoToMarshallTypeTests : BaseGeneratorTestClass { + + class TestDataToMarshallType : IEnumerable { + public IEnumerator GetEnumerator () + { + const string nfloatProperty = @" +using System; +using System.Runtime.InteropServices; +using Foundation; +using ObjCRuntime; + +namespace NS; + +public class Example { + public nfloat Texturing { get; set; } +} +"; + yield return [nfloatProperty, "nfloat"]; + + const string otherNfloatProperty = @" +using System; +using System.Runtime.InteropServices; +using Foundation; +using ObjCRuntime; + +namespace NS; + +public class Example { + public NFloat Texturing { get; set; } +} +"; + yield return [otherNfloatProperty, "nfloat"]; + + const string systemString = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace NS; + +public class Example { + public string Texturing { get; set; } +} +"; + + yield return [systemString, "NativeHandle"]; + + const string nsstring = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace NS; + +public class Example { + public NSString Texturing { get; set; } +} +"; + + yield return [nsstring, "NativeHandle"]; + + //const string nsobject + + const string nativeEnumInt64 = @" +using System; +using ObjCRuntime; + +namespace NS; + +[Native] +public enum AREnvironmentTexturing : long { + None, + Manual, + Automatic, +} + +public class Example { + public AREnvironmentTexturing Texturing { get; set; } +} +"; + yield return [nativeEnumInt64, "IntPtr"]; + + const string nativeEnumUInt64 = @" +using System; +using ObjCRuntime; + +namespace NS; + +[Native] +public enum AREnvironmentTexturing : ulong { + None, + Manual, + Automatic, +} + +public class Example { + public AREnvironmentTexturing Texturing { get; set; } +} +"; + yield return [nativeEnumUInt64, "UIntPtr"]; + + const string smartEnum = @" +using System; +using ObjCRuntime; +using ObjCBindings; + +namespace NS; + +[BindingType] +public enum AREnvironmentTexturing : ulong { + [Field (""AVCaptureDeviceTypeBuiltInMicrophone"")] + None, +} + +public class Example { + public AREnvironmentTexturing Texturing { get; set; } +} +"; + yield return [smartEnum, "NativeHandle"]; + + const string normalEnum = @" +using System; +using ObjCRuntime; +using ObjCBindings; + +namespace NS; + +public enum AREnvironmentTexturing : ulong { + None, +} + +public class Example { + public AREnvironmentTexturing Texturing { get; set; } +} +"; + + yield return [normalEnum, "ulong"]; + + const string boolProperty = @" +using System; + +namespace NS; + +public class Example { + public bool Texturing { get; set; } +} +"; + yield return [boolProperty, "bool"]; + + const string intProperty = @" +using System; + +namespace NS; + +public class Example { + public int Texturing { get; set; } +} +"; + yield return [intProperty, "int"]; + + const string structureProperty = @" +using System; + +namespace NS; + +public struct Point { + int x; + int y; +} + +public class Example { + public Point Centre { get; set; } +} +"; + yield return [structureProperty, "Point"]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void ToMarshallType (ApplePlatform platform, string inputText, string expectedTypeName) + { + var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); + Assert.Single (syntaxTrees); + var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); + var declaration = syntaxTrees [0].GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + Assert.True (Property.TryCreate (declaration, semanticModel, out var changes)); + Assert.NotNull (changes); + var marshall = changes.Value.ReturnType.ToMarshallType (); + Assert.NotNull (marshall); + Assert.Equal (expectedTypeName, marshall); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryFieldAccessorsTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryFieldAccessorsTests.cs new file mode 100644 index 000000000000..549ee7dc6c53 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryFieldAccessorsTests.cs @@ -0,0 +1,1695 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Context; +using Microsoft.Macios.Generator.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using Xunit; +using static Microsoft.Macios.Generator.Emitters.BindingSyntaxFactory; + +namespace Microsoft.Macios.Generator.Tests.Emitters; + +public class BindingSyntaxFactoryFieldAccessorsTests : BaseGeneratorTestClass { + + class TestDataFieldConstantGetter : IEnumerable { + public IEnumerator GetEnumerator () + { + const string nsStringFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial NSString GenericGray { get; } + + } +} +"; + + yield return [nsStringFieldProperty, + "Dlfcn.GetStringConstant (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\")!;"]; + + const string byteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial byte GenericGray { get; } + + } +} +"; + + yield return [byteFieldProperty, + "Dlfcn.GetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherByteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Byte GenericGray { get; } + + } +} +"; + yield return [otherByteFieldProperty, + "Dlfcn.GetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string sbyteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial sbyte GenericGray { get; } + + } +} +"; + + yield return [sbyteFieldProperty, + "Dlfcn.GetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherSbyteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial SByte GenericGray { get; } + + } +} +"; + + yield return [otherSbyteFieldProperty, + "Dlfcn.GetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string int16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial short GenericGray { get; } + + } +} +"; + + yield return [int16FieldProperty, + "Dlfcn.GetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherInt16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Int16 GenericGray { get; } + + } +} +"; + + yield return [otherInt16FieldProperty, + "Dlfcn.GetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string uint16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial ushort GenericGray { get; } + + } +} +"; + + yield return [uint16FieldProperty, + "Dlfcn.GetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherUint16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial UInt16 GenericGray { get; } + + } +} +"; + + yield return [otherUint16FieldProperty, + "Dlfcn.GetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string int32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial int GenericGray { get; } + + } +} +"; + + yield return [int32FieldProperty, + "Dlfcn.GetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherInt32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Int32 GenericGray { get; } + + } +} +"; + + yield return [otherInt32FieldProperty, + "Dlfcn.GetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string uint32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial uint GenericGray { get; } + + } +} +"; + + yield return [uint32FieldProperty, + "Dlfcn.GetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherUint32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial UInt32 GenericGray { get; } + + } +} +"; + + yield return [otherUint32FieldProperty, + "Dlfcn.GetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string doubleFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial double GenericGray { get; } + + } +} +"; + + yield return [doubleFieldProperty, + "Dlfcn.GetDouble (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherDoubleFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Double GenericGray { get; } + + } +} +"; + + yield return [otherDoubleFieldProperty, + "Dlfcn.GetDouble (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string floatFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial float GenericGray { get; } + + } +} +"; + + yield return [floatFieldProperty, + "Dlfcn.GetFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string otherFloatFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Single GenericGray { get; } + + } +} +"; + + yield return [otherFloatFieldProperty, + "Dlfcn.GetFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string intPtrFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial IntPtr GenericGray { get; } + + } +} +"; + + yield return [intPtrFieldProperty, + "Dlfcn.GetIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string uintPtrFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial UIntPtr GenericGray { get; } + + } +} +"; + + yield return [uintPtrFieldProperty, + "Dlfcn.GetUIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string nintFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial nint GenericGray { get; } + + } +} +"; + + yield return [nintFieldProperty, + "Dlfcn.GetIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string nuintFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial nuint GenericGray { get; } + + } +} +"; + + yield return [nuintFieldProperty, + "Dlfcn.GetUIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string nfloatFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial nfloat GenericGray { get; } + + } +} +"; + + yield return [nfloatFieldProperty, + "Dlfcn.GetNFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string cgsizeFieldProperty = @" +using System; +using Foundation; +using CoreGraphics; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGSize GenericGray { get; } + + } +} +"; + + yield return [cgsizeFieldProperty, + "Dlfcn.GetCGSize (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string cmtagFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CMTag GenericGray { get; } + + } +} +"; + + yield return [cmtagFieldProperty, + "Dlfcn.GetStruct (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + + const string nsArrayFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial NSArray GenericGray { get; } + + } +} +"; + + yield return [nsArrayFieldProperty, + "Runtime.GetNSObject (Dlfcn.GetIndirect (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"))!;"]; + + const string nsNumberFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial NSNumber GenericGray { get; } + + } +} +"; + + yield return [nsNumberFieldProperty, + "Runtime.GetNSObject (Dlfcn.GetIndirect (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"))!;"]; + + const string sbyteEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : sbyte{ + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + sbyteEnumFieldProperty, + "Dlfcn.GetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string byteEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : byte{ + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + byteEnumFieldProperty, + "Dlfcn.GetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string shortEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : short { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + shortEnumFieldProperty, + "Dlfcn.GetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string ushortEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : ushort { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + ushortEnumFieldProperty, + "Dlfcn.GetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string intEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : int { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + intEnumFieldProperty, + "Dlfcn.GetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string uintEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : uint { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + uintEnumFieldProperty, + "Dlfcn.GetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string longEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : long { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + longEnumFieldProperty, + "Dlfcn.GetInt64 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string ulongEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : ulong { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + ulongEnumFieldProperty, + "Dlfcn.GetUInt64 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + ]; + + const string cmTimeFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CMTime GenericGray { get; } + + } +} +"; + + yield return [ + cmTimeFieldProperty, + "*((CoreMedia.CMTime*) Dlfcn.dlsym (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"));" + ]; + + const string whiteFieldProperty = @" +using System; +using AVFoundation; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial AVCaptureWhiteBalanceGains GenericGray { get; } + + } +} +"; + + yield return [ + whiteFieldProperty, + "*((AVFoundation.AVCaptureWhiteBalanceGains*) Dlfcn.dlsym (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"));" + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void FieldConstantGetterTests (ApplePlatform platform, string inputText, string expectedCall) + { + var (compilation, sourceTrees) = + CreateCompilation (platform, sources: inputText); + Assert.Single (sourceTrees); + // get the declarations we want to work with and the semantic model + var node = sourceTrees [0].GetRoot () + .DescendantNodes () + .OfType () + .FirstOrDefault (); + Assert.NotNull (node); + var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); + var context = new RootContext (semanticModel); + Assert.True (Property.TryCreate (node, context, out var property)); + var compilationUnit = FieldConstantGetter (property.Value).ToString (); + var str = compilationUnit.ToString (); + Assert.Equal (expectedCall, FieldConstantGetter (property.Value).ToString ()); + } + + class TestDataFieldConstantSetter : IEnumerable { + public IEnumerator GetEnumerator () + { + const string nsStringFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial NSString GenericGray { get; } + + } +} +"; + + yield return [nsStringFieldProperty, + "value", + "Dlfcn.SetString (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string byteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial byte GenericGray { get; } + + } +} +"; + + yield return [byteFieldProperty, + "value", + "Dlfcn.SetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherByteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Byte GenericGray { get; } + + } +} +"; + yield return [otherByteFieldProperty, + "value", + "Dlfcn.SetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string sbyteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial sbyte GenericGray { get; } + + } +} +"; + + yield return [sbyteFieldProperty, + "value", + "Dlfcn.SetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherSbyteFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial SByte GenericGray { get; } + + } +} +"; + + yield return [otherSbyteFieldProperty, + "value", + "Dlfcn.SetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string int16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial short GenericGray { get; } + + } +} +"; + + yield return [int16FieldProperty, + "value", + "Dlfcn.SetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherInt16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Int16 GenericGray { get; } + + } +} +"; + + yield return [otherInt16FieldProperty, + "value", + "Dlfcn.SetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string uint16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial ushort GenericGray { get; } + + } +} +"; + + yield return [uint16FieldProperty, + "value", + "Dlfcn.SetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherUint16FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial UInt16 GenericGray { get; } + + } +} +"; + + yield return [otherUint16FieldProperty, + "value", + "Dlfcn.SetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string int32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial int GenericGray { get; } + + } +} +"; + + yield return [int32FieldProperty, + "value", + "Dlfcn.SetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherInt32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Int32 GenericGray { get; } + + } +} +"; + + yield return [otherInt32FieldProperty, + "value", + "Dlfcn.SetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string uint32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial uint GenericGray { get; } + + } +} +"; + + yield return [uint32FieldProperty, + "value", + "Dlfcn.SetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherUint32FieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial UInt32 GenericGray { get; } + + } +} +"; + + yield return [otherUint32FieldProperty, + "value", + "Dlfcn.SetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string doubleFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial double GenericGray { get; } + + } +} +"; + + yield return [doubleFieldProperty, + "value", + "Dlfcn.SetDouble (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherDoubleFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Double GenericGray { get; } + + } +} +"; + + yield return [otherDoubleFieldProperty, + "value", + "Dlfcn.SetDouble (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string floatFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial float GenericGray { get; } + + } +} +"; + + yield return [floatFieldProperty, + "value", + "Dlfcn.SetFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string otherFloatFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial Single GenericGray { get; } + + } +} +"; + + yield return [otherFloatFieldProperty, + "value", + "Dlfcn.SetFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string intPtrFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial IntPtr GenericGray { get; } + + } +} +"; + + yield return [intPtrFieldProperty, + "value", + "Dlfcn.SetIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string uintPtrFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial UIntPtr GenericGray { get; } + + } +} +"; + + yield return [uintPtrFieldProperty, + "value", + "Dlfcn.SetUIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string nintFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial nint GenericGray { get; } + + } +} +"; + + yield return [nintFieldProperty, + "value", + "Dlfcn.SetIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string nuintFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial nuint GenericGray { get; } + + } +} +"; + + yield return [nuintFieldProperty, + "value", + "Dlfcn.SetUIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string nfloatFieldProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial nfloat GenericGray { get; } + + } +} +"; + + yield return [nfloatFieldProperty, + "value", + "Dlfcn.SetNFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string cgsizeFieldProperty = @" +using System; +using Foundation; +using CoreGraphics; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGSize GenericGray { get; } + + } +} +"; + + yield return [cgsizeFieldProperty, + "value", + "Dlfcn.SetCGSize (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string cmtagFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CMTag GenericGray { get; } + + } +} +"; + + yield return [ + cmtagFieldProperty, + "value", + "throw new NotSupportedException(\"Setting fields of type 'CoreMedia.CMTag' is not supported.\");"]; + + const string nsArrayFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial NSArray GenericGray { get; } + + } +} +"; + + yield return [nsArrayFieldProperty, + "value", + "Dlfcn.SetArray (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string nsNumberFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial NSNumber GenericGray { get; } + + } +} +"; + + yield return [nsNumberFieldProperty, + "value", + "Dlfcn.SetObject (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", value);"]; + + const string sbyteEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : sbyte{ + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + sbyteEnumFieldProperty, + "value", + "Dlfcn.SetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (sbyte)value);" + ]; + + const string byteEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : byte{ + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + byteEnumFieldProperty, + "value", + "Dlfcn.SetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (byte)value);" + ]; + + const string shortEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : short { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + shortEnumFieldProperty, + "value", + "Dlfcn.SetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (short)value);" + ]; + + const string ushortEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : ushort { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + ushortEnumFieldProperty, + "value", + "Dlfcn.SetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (ushort)value);" + ]; + + const string intEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : int { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + intEnumFieldProperty, + "value", + "Dlfcn.SetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (int)value);" + ]; + + const string uintEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : uint { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + uintEnumFieldProperty, + "value", + "Dlfcn.SetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (uint)value);" + ]; + + const string longEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : long { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + longEnumFieldProperty, + "value", + "Dlfcn.SetInt64 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (long)value);" + ]; + + const string ulongEnumFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + public enum CGColorSpaceGenericGray : ulong { + First, + Second, + } + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CGColorSpaceGenericGray GenericGray { get; } + + } +} +"; + + yield return [ + ulongEnumFieldProperty, + "value", + "Dlfcn.SetUInt64 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\", (ulong)value);" + ]; + + const string cmTimeFieldProperty = @" +using System; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial CMTime GenericGray { get; } + + } +} +"; + + yield return [ + cmTimeFieldProperty, + "value", + "throw new NotSupportedException(\"Setting fields of type 'CoreMedia.CMTime' is not supported.\");"]; + + const string whiteFieldProperty = @" +using System; +using AVFoundation; +using Foundation; +using CoreMedia; +using ObjCBindings; + +namespace CoreGraphics { + + [BindingType] + public partial class CGColorSpaceNames { + + [Field (""kCGColorSpaceGenericGray"")] + public partial AVCaptureWhiteBalanceGains GenericGray { get; } + + } +} +"; + + yield return [ + whiteFieldProperty, + "value", + "throw new NotSupportedException(\"Setting fields of type 'AVFoundation.AVCaptureWhiteBalanceGains' is not supported.\");"]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void FieldConstantSetterTests (ApplePlatform platform, string inputText, string variableName, string expectedCall) + { + var (compilation, sourceTrees) = + CreateCompilation (platform, sources: inputText); + Assert.Single (sourceTrees); + // get the declarations we want to work with and the semantic model + var node = sourceTrees [0].GetRoot () + .DescendantNodes () + .OfType () + .FirstOrDefault (); + Assert.NotNull (node); + var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); + var context = new RootContext (semanticModel); + Assert.True (Property.TryCreate (node, context, out var property)); + Assert.Equal (expectedCall, FieldConstantSetter (property.Value, variableName).ToString ()); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryFieldBackingVariableTests.cs similarity index 52% rename from tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryFieldBackingVariableTests.cs index 8b089a280fc4..fe93860ae24b 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryFieldBackingVariableTests.cs @@ -14,9 +14,9 @@ namespace Microsoft.Macios.Generator.Tests.Emitters; -public class BindingSyntaxFactoryTests : BaseGeneratorTestClass { +public class BindingSyntaxFactoryFieldBackingVariableTests : BaseGeneratorTestClass { - class TestDataFieldConstantGetter : IEnumerable { + class TestDataFieldPropertyBackingVariable : IEnumerable { public IEnumerator GetEnumerator () { const string nsStringFieldProperty = @" @@ -36,8 +36,10 @@ public partial class CGColorSpaceNames { } "; - yield return [nsStringFieldProperty, - "Dlfcn.GetStringConstant (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + nsStringFieldProperty, + "static Foundation.NSString? _GenericGray;" + ]; const string byteFieldProperty = @" using System; @@ -56,8 +58,10 @@ public partial class CGColorSpaceNames { } "; - yield return [byteFieldProperty, - "Dlfcn.GetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + byteFieldProperty, + "static byte _GenericGray;" + ]; const string otherByteFieldProperty = @" using System; @@ -75,8 +79,10 @@ public partial class CGColorSpaceNames { } } "; - yield return [otherByteFieldProperty, - "Dlfcn.GetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherByteFieldProperty, + "static byte _GenericGray;" + ]; const string sbyteFieldProperty = @" using System; @@ -95,8 +101,10 @@ public partial class CGColorSpaceNames { } "; - yield return [sbyteFieldProperty, - "Dlfcn.GetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + sbyteFieldProperty, + "static sbyte _GenericGray;" + ]; const string otherSbyteFieldProperty = @" using System; @@ -115,8 +123,10 @@ public partial class CGColorSpaceNames { } "; - yield return [otherSbyteFieldProperty, - "Dlfcn.GetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherSbyteFieldProperty, + "static sbyte _GenericGray;" + ]; const string int16FieldProperty = @" using System; @@ -135,8 +145,10 @@ public partial class CGColorSpaceNames { } "; - yield return [int16FieldProperty, - "Dlfcn.GetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + int16FieldProperty, + "static short _GenericGray;" + ]; const string otherInt16FieldProperty = @" using System; @@ -155,8 +167,10 @@ public partial class CGColorSpaceNames { } "; - yield return [otherInt16FieldProperty, - "Dlfcn.GetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherInt16FieldProperty, + "static short _GenericGray;" + ]; const string uint16FieldProperty = @" using System; @@ -175,8 +189,10 @@ public partial class CGColorSpaceNames { } "; - yield return [uint16FieldProperty, - "Dlfcn.GetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + uint16FieldProperty, + "static ushort _GenericGray;" + ]; const string otherUint16FieldProperty = @" using System; @@ -195,8 +211,10 @@ public partial class CGColorSpaceNames { } "; - yield return [otherUint16FieldProperty, - "Dlfcn.GetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherUint16FieldProperty, + "static ushort _GenericGray;" + ]; const string int32FieldProperty = @" using System; @@ -215,8 +233,10 @@ public partial class CGColorSpaceNames { } "; - yield return [int32FieldProperty, - "Dlfcn.GetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + int32FieldProperty, + "static int _GenericGray;" + ]; const string otherInt32FieldProperty = @" using System; @@ -235,8 +255,10 @@ public partial class CGColorSpaceNames { } "; - yield return [otherInt32FieldProperty, - "Dlfcn.GetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherInt32FieldProperty, + "static int _GenericGray;" + ]; const string uint32FieldProperty = @" using System; @@ -255,8 +277,10 @@ public partial class CGColorSpaceNames { } "; - yield return [uint32FieldProperty, - "Dlfcn.GetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + uint32FieldProperty, + "static uint _GenericGray;" + ]; const string otherUint32FieldProperty = @" using System; @@ -275,8 +299,10 @@ public partial class CGColorSpaceNames { } "; - yield return [otherUint32FieldProperty, - "Dlfcn.GetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherUint32FieldProperty, + "static uint _GenericGray;" + ]; const string doubleFieldProperty = @" using System; @@ -295,8 +321,10 @@ public partial class CGColorSpaceNames { } "; - yield return [doubleFieldProperty, - "Dlfcn.GetDouble (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + doubleFieldProperty, + "static double _GenericGray;" + ]; const string otherDoubleFieldProperty = @" using System; @@ -315,8 +343,10 @@ public partial class CGColorSpaceNames { } "; - yield return [otherDoubleFieldProperty, - "Dlfcn.GetDouble (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherDoubleFieldProperty, + "static double _GenericGray;" + ]; const string floatFieldProperty = @" using System; @@ -335,8 +365,10 @@ public partial class CGColorSpaceNames { } "; - yield return [floatFieldProperty, - "Dlfcn.GetFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + floatFieldProperty, + "static float _GenericGray;" + ]; const string otherFloatFieldProperty = @" using System; @@ -355,8 +387,10 @@ public partial class CGColorSpaceNames { } "; - yield return [otherFloatFieldProperty, - "Dlfcn.GetFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + otherFloatFieldProperty, + "static float _GenericGray;" + ]; const string intPtrFieldProperty = @" using System; @@ -375,8 +409,11 @@ public partial class CGColorSpaceNames { } "; - yield return [intPtrFieldProperty, - "Dlfcn.GetIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + intPtrFieldProperty, + "static IntPtr _GenericGray;" + ]; + const string uintPtrFieldProperty = @" using System; @@ -395,8 +432,10 @@ public partial class CGColorSpaceNames { } "; - yield return [uintPtrFieldProperty, - "Dlfcn.GetUIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + uintPtrFieldProperty, + "static UIntPtr _GenericGray;" + ]; const string nintFieldProperty = @" using System; @@ -415,8 +454,10 @@ public partial class CGColorSpaceNames { } "; - yield return [nintFieldProperty, - "Dlfcn.GetIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + nintFieldProperty, + "static IntPtr _GenericGray;" + ]; const string nuintFieldProperty = @" using System; @@ -435,8 +476,10 @@ public partial class CGColorSpaceNames { } "; - yield return [nuintFieldProperty, - "Dlfcn.GetUIntPtr (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + nuintFieldProperty, + "static UIntPtr _GenericGray;" + ]; const string nfloatFieldProperty = @" using System; @@ -455,8 +498,10 @@ public partial class CGColorSpaceNames { } "; - yield return [nfloatFieldProperty, - "Dlfcn.GetNFloat (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + nfloatFieldProperty, + "static nfloat? _GenericGray;" + ]; const string cgsizeFieldProperty = @" using System; @@ -476,8 +521,10 @@ public partial class CGColorSpaceNames { } "; - yield return [cgsizeFieldProperty, - "Dlfcn.GetCGSize (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + cgsizeFieldProperty, + "static CoreGraphics.CGSize _GenericGray;" + ]; const string cmtagFieldProperty = @" using System; @@ -497,8 +544,10 @@ public partial class CGColorSpaceNames { } "; - yield return [cmtagFieldProperty, - "Dlfcn.GetStruct (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");"]; + yield return [ + cmtagFieldProperty, + "static CoreMedia.CMTag _GenericGray;" + ]; const string nsArrayFieldProperty = @" using System; @@ -518,8 +567,10 @@ public partial class CGColorSpaceNames { } "; - yield return [nsArrayFieldProperty, - "Runtime.GetNSObject (Dlfcn.GetIndirect (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"))!;"]; + yield return [ + nsArrayFieldProperty, + "static Foundation.NSArray? _GenericGray;" + ]; const string nsNumberFieldProperty = @" using System; @@ -537,40 +588,14 @@ public partial class CGColorSpaceNames { } } -"; - - yield return [nsNumberFieldProperty, - "Runtime.GetNSObject (Dlfcn.GetIndirect (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"))!;"]; - - const string sbyteEnumFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - public enum CGColorSpaceGenericGray : sbyte{ - First, - Second, - } - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CGColorSpaceGenericGray GenericGray { get; } - - } -} "; yield return [ - sbyteEnumFieldProperty, - "Dlfcn.GetSByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" + nsNumberFieldProperty, + "static Foundation.NSNumber? _GenericGray;" ]; - const string byteEnumFieldProperty = @" + const string enumFieldProperty = @" using System; using Foundation; using CoreMedia; @@ -579,147 +604,7 @@ public partial class CGColorSpaceNames { namespace CoreGraphics { public enum CGColorSpaceGenericGray : byte{ - First, - Second, - } - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CGColorSpaceGenericGray GenericGray { get; } - - } -} -"; - - yield return [ - byteEnumFieldProperty, - "Dlfcn.GetByte (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" - ]; - - const string shortEnumFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - public enum CGColorSpaceGenericGray : short { - First, - Second, - } - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CGColorSpaceGenericGray GenericGray { get; } - - } -} -"; - - yield return [ - shortEnumFieldProperty, - "Dlfcn.GetInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" - ]; - - const string ushortEnumFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - public enum CGColorSpaceGenericGray : ushort { - First, - Second, - } - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CGColorSpaceGenericGray GenericGray { get; } - - } -} -"; - - yield return [ - ushortEnumFieldProperty, - "Dlfcn.GetUInt16 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" - ]; - - const string intEnumFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - public enum CGColorSpaceGenericGray : int { - First, - Second, - } - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CGColorSpaceGenericGray GenericGray { get; } - - } -} -"; - - yield return [ - intEnumFieldProperty, - "Dlfcn.GetInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" - ]; - - const string uintEnumFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - public enum CGColorSpaceGenericGray : uint { - First, - Second, - } - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CGColorSpaceGenericGray GenericGray { get; } - - } -} -"; - - yield return [ - uintEnumFieldProperty, - "Dlfcn.GetUInt32 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" - ]; - - const string longEnumFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - public enum CGColorSpaceGenericGray : long { - First, + First, Second, } @@ -734,83 +619,8 @@ public partial class CGColorSpaceNames { "; yield return [ - longEnumFieldProperty, - "Dlfcn.GetInt64 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" - ]; - - const string ulongEnumFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - public enum CGColorSpaceGenericGray : ulong { - First, - Second, - } - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CGColorSpaceGenericGray GenericGray { get; } - - } -} -"; - - yield return [ - ulongEnumFieldProperty, - "Dlfcn.GetUInt64 (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\");" - ]; - - const string cmTimeFieldProperty = @" -using System; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial CMTime GenericGray { get; } - - } -} -"; - - yield return [ - cmTimeFieldProperty, - "*((CoreMedia.CMTime*) Dlfcn.dlsym (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"));" - ]; - - const string whiteFieldProperty = @" -using System; -using AVFoundation; -using Foundation; -using CoreMedia; -using ObjCBindings; - -namespace CoreGraphics { - - [BindingType] - public partial class CGColorSpaceNames { - - [Field (""kCGColorSpaceGenericGray"")] - public partial AVCaptureWhiteBalanceGains GenericGray { get; } - - } -} -"; - - yield return [ - whiteFieldProperty, - "*((AVFoundation.AVCaptureWhiteBalanceGains*) Dlfcn.dlsym (Libraries.CoreGraphics.Handle, \"kCGColorSpaceGenericGray\"));" + enumFieldProperty, + "static CoreGraphics.CGColorSpaceGenericGray _GenericGray;" ]; } @@ -818,7 +628,7 @@ public partial class CGColorSpaceNames { } [Theory] - [AllSupportedPlatformsClassData] + [AllSupportedPlatformsClassData] void FieldConstantGetterTests (ApplePlatform platform, string inputText, string expectedCall) { var (compilation, sourceTrees) = @@ -831,10 +641,8 @@ void FieldConstantGetterTests (ApplePlatform platform, string inputText, string .FirstOrDefault (); Assert.NotNull (node); var semanticModel = compilation.GetSemanticModel (sourceTrees [0]); - var context = new RootBindingContext (semanticModel); + var context = new RootContext (semanticModel); Assert.True (Property.TryCreate (node, context, out var property)); - var compilationUnit = FieldConstantGetter (property.Value).ToString (); - var str = compilationUnit.ToString (); - Assert.Equal (expectedCall, FieldConstantGetter (property.Value).ToString ()); + Assert.Equal (expectedCall, FieldPropertyBackingVariable (property.Value).ToString ()); } } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs new file mode 100644 index 000000000000..e2647ab54caa --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs @@ -0,0 +1,665 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.Macios.Generator.DataModel; +using Xunit; +using static Microsoft.Macios.Generator.Emitters.BindingSyntaxFactory; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; + +namespace Microsoft.Macios.Generator.Tests.Emitters; + +public class BindingSyntaxFactoryObjCRuntimeTests { + + class TestDataCastToNativeTests : IEnumerable { + public IEnumerator GetEnumerator () + { + + // not enum parameter + var boolParam = new Parameter ( + position: 0, + type: ReturnTypeForBool (), + name: "myParam"); + yield return [boolParam, null!]; + + // not smart enum parameter + var enumParam = new Parameter ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", isNativeEnum: false), + name: "myParam"); + + yield return [enumParam, null!]; + + // int64 + var byteEnum = new Parameter ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", isNativeEnum: true, underlyingType: SpecialType.System_Int64), + name: "myParam"); + yield return [byteEnum, "(IntPtr) (long) myParam"]; + + // uint64 + var int64Enum = new Parameter ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", isNativeEnum: true, underlyingType: SpecialType.System_UInt64), + name: "myParam"); + yield return [int64Enum, "(UIntPtr) (ulong) myParam"]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataCastToNativeTests))] + void CastToNativeTests (Parameter parameter, string? expectedCast) + { + var expression = CastToNative (parameter); + if (expectedCast is null) { + Assert.Null (expression); + } else { + Assert.NotNull (expression); + Assert.Equal (expectedCast, expression?.ToString ()); + } + } + + class TestDataCastToPrimitive : IEnumerable { + public IEnumerator GetEnumerator () + { + // not enum parameter + var boolParam = new Parameter ( + position: 0, + type: ReturnTypeForBool (), + name: "myParam"); + yield return [boolParam, null!]; + + var enumParam = new Parameter ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", isNativeEnum: false), + name: "myParam"); + + yield return [enumParam, "(int) myParam"]; + + var byteParam = new Parameter ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", isNativeEnum: false, underlyingType: SpecialType.System_Byte), + name: "myParam"); + + yield return [byteParam, "(byte) myParam"]; + + + var longParam = new Parameter ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", isNativeEnum: false, underlyingType: SpecialType.System_Int64), + name: "myParam"); + + yield return [longParam, "(long) myParam"]; + } + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataCastToPrimitive))] + void CastToPrimitiveTests (Parameter parameter, string? expectedCast) + { + var expression = CastToPrimitive (parameter); + if (expectedCast is null) { + Assert.Null (expression); + } else { + Assert.NotNull (expression); + Assert.Equal (expectedCast, expression?.ToString ()); + } + } + + [Fact] + void CastToByteTests () + { + var boolParameter = new Parameter (0, ReturnTypeForBool (), "myParameter"); + var conditionalExpr = CastToByte (boolParameter); + Assert.NotNull (conditionalExpr); + Assert.Equal ("myParameter ? (byte) 1 : (byte) 0", conditionalExpr.ToString ()); + + var intParameter = new Parameter (1, ReturnTypeForInt (), "myParameter"); + conditionalExpr = CastToByte (intParameter); + Assert.Null (conditionalExpr); + } + + class TestDataGetNSArrayAuxVariableTest : IEnumerable { + public IEnumerator GetEnumerator () + { + // not array + + yield return [ + new Parameter (0, ReturnTypeForInt (isNullable: false), "myParam"), + null!, + false]; + + // not nullable string[] + yield return [ + new Parameter (0, ReturnTypeForArray ("string", isNullable: false), "myParam"), + "var nsa_myParam = NSArray.FromStrings (myParam);", + false]; + + yield return [ + new Parameter (0, ReturnTypeForArray ("string", isNullable: false), "myParam"), + "using var nsa_myParam = NSArray.FromStrings (myParam);", + true]; + + // nullable string [] + yield return [ + new Parameter (0, ReturnTypeForArray ("string", isNullable: true), "myParam"), + "var nsa_myParam = myParam is null ? null : NSArray.FromStrings (myParam);", + false]; + + yield return [ + new Parameter (0, ReturnTypeForArray ("string", isNullable: true), "myParam"), + "using var nsa_myParam = myParam is null ? null : NSArray.FromStrings (myParam);", + true]; + + // nsstrings + + yield return [ + new Parameter (0, ReturnTypeForArray ("NSString", isNullable: false), "myParam"), + "var nsa_myParam = NSArray.FromNSObjects (myParam);", + false]; + + yield return [ + new Parameter (0, ReturnTypeForArray ("NSString", isNullable: false), "myParam"), + "using var nsa_myParam = NSArray.FromNSObjects (myParam);", + true]; + + yield return [ + new Parameter (0, ReturnTypeForArray ("NSString", isNullable: true), "myParam"), + "var nsa_myParam = myParam is null ? null : NSArray.FromNSObjects (myParam);", + false]; + + yield return [ + new Parameter (0, ReturnTypeForArray ("NSString", isNullable: true), "myParam"), + "using var nsa_myParam = myParam is null ? null : NSArray.FromNSObjects (myParam);", + true]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetNSArrayAuxVariableTest))] + void GetNSArrayAuxVariableTests (in Parameter parameter, string? expectedDeclaration, bool withUsing) + { + var declaration = GetNSArrayAuxVariable (in parameter, withUsing: withUsing); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + class TestDataGetHandleAuxVariableTests : IEnumerable { + public IEnumerator GetEnumerator () + { + // nsobject type + yield return [ + new Parameter (0, ReturnTypeForNSObject ("MyNSObject"), "myParam"), + "var myParam__handle__ = myParam.GetHandle ();", + false + ]; + + yield return [ + new Parameter (0, ReturnTypeForNSObject ("MyNSObject"), "myParam"), + "var myParam__handle__ = myParam!.GetNonNullHandle ( nameof (myParam));", + true + ]; + + // interface type + yield return [ + new Parameter (0, ReturnTypeForINativeObject ("MyNativeObject"), "myParam"), + "var myParam__handle__ = myParam.GetHandle ();", + false + ]; + + yield return [ + new Parameter (0, ReturnTypeForINativeObject ("MyNativeObject"), "myParam"), + "var myParam__handle__ = myParam!.GetNonNullHandle ( nameof (myParam));", + true + ]; + + // value type + yield return [ + new Parameter (0, ReturnTypeForBool (), "myParam"), + null!, + false + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetHandleAuxVariableTests))] + void GetHandleAuxVariableTests (in Parameter parameter, string? expectedDeclaration, bool withNullAllowed) + { + var declaration = GetHandleAuxVariable (parameter, withNullAllowed: withNullAllowed); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + class TestDataGetStringAuxVariableTest : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + new Parameter (0, ReturnTypeForString (), "myParam"), + "var nsmyParam = CFString.CreateNative (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForBool (), "myParam"), + null!, + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetStringAuxVariableTest))] + void GetStringAuxVariableTests (in Parameter parameter, string? expectedDeclaration) + { + var declaration = GetStringAuxVariable (parameter); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + class TestDataGetNSNumberAuxVariableTest : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + new Parameter (0, ReturnTypeForInt (), "myParam"), + "var nsb_myParam = NSNumber.FromInt32 (myParam);" + ]; + + yield return [ + new Parameter (0, ReturnTypeForInt (isUnsigned: true), "myParam"), + "var nsb_myParam = NSNumber.FromUInt32 (myParam);" + ]; + + yield return [ + new Parameter (0, ReturnTypeForBool (), "myParam"), + "var nsb_myParam = NSNumber.FromBoolean (myParam);" + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("MyEnum"), "myParam"), + "var nsb_myParam = NSNumber.FromInt32 ((int) myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_Byte), "myParam"), + "var nsb_myParam = NSNumber.FromByte ((byte) myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_SByte), "myParam"), + "var nsb_myParam = NSNumber.FromSByte ((sbyte) myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_Int16), "myParam"), + "var nsb_myParam = NSNumber.FromInt16 ((short) myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_UInt16), "myParam"), + "var nsb_myParam = NSNumber.FromUInt16 ((ushort) myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_Int64), "myParam"), + "var nsb_myParam = NSNumber.FromInt64 ((long) myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_UInt64), "myParam"), + "var nsb_myParam = NSNumber.FromUInt64 ((ulong) myParam);", + ]; + + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetNSNumberAuxVariableTest))] + void GetNSNumberAuxVariableTests (in Parameter parameter, string? expectedDeclaration) + { + var declaration = GetNSNumberAuxVariable (parameter); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + class TestDataGetNSValueAuxVariableTest : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreGraphics.CGAffineTransform"), "myParam"), + "var nsb_myParam = NSValue.FromCGAffineTransform (myParam);" + ]; + yield return [ + new Parameter (0, ReturnTypeForStruct ("Foundation.NSRange"), "myParam"), + "var nsb_myParam = NSValue.FromRange (myParam);" + ]; + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreGraphics.CGVector"), "myParam"), + "var nsb_myParam = NSValue.FromCGVector (myParam);" + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("SceneKit.SCNMatrix4"), "myParam"), + "var nsb_myParam = NSValue.FromSCNMatrix4 (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreLocation.CLLocationCoordinate2D"), "myParam"), + "var nsb_myParam = NSValue.FromMKCoordinate (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("SceneKit.SCNVector3"), "myParam"), + "var nsb_myParam = NSValue.FromVector (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("SceneKit.SCNVector4"), "myParam"), + "var nsb_myParam = NSValue.FromVector (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreGraphics.CGPoint"), "myParam"), + "var nsb_myParam = NSValue.FromCGPoint (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreGraphics.CGRect"), "myParam"), + "var nsb_myParam = NSValue.FromCGRect (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreGraphics.CGSize"), "myParam"), + "var nsb_myParam = NSValue.FromCGSize (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("UIKit.UIEdgeInsets"), "myParam"), + "var nsb_myParam = NSValue.FromUIEdgeInsets (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("UIKit.UIOffset"), "myParam"), + "var nsb_myParam = NSValue.FromUIOffset (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("MapKit.MKCoordinateSpan"), "myParam"), + "var nsb_myParam = NSValue.FromMKCoordinateSpan (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreMedia.CMTimeRange"), "myParam"), + "var nsb_myParam = NSValue.FromCMTimeRange (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreMedia.CMTime"), "myParam"), + "var nsb_myParam = NSValue.FromCMTime (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreMedia.CMTimeMapping"), "myParam"), + "var nsb_myParam = NSValue.FromCMTimeMapping (myParam);", + ]; + + yield return [ + new Parameter (0, ReturnTypeForStruct ("CoreAnimation.CATransform3D"), "myParam"), + "var nsb_myParam = NSValue.FromCATransform3D (myParam);", + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetNSValueAuxVariableTest))] + void GetNSValueAuxVariableTests (in Parameter parameter, string? expectedDeclaration) + { + var declaration = GetNSValueAuxVariable (parameter); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + class TestDataGetNSStringSmartEnumAuxVariableTests : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + new Parameter (0, ReturnTypeForEnum ("CoreAnimation.CATransform3D", isSmartEnum: true), "myParam"), + "var nsb_myParam = myParam.GetConstant ();", + ]; + + yield return [ + new Parameter (0, ReturnTypeForEnum ("CoreAnimation.CATransform3D", isSmartEnum: false), "myParam"), + null! + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetNSStringSmartEnumAuxVariableTests))] + void GetNSStringSmartEnumAuxVariableTests (in Parameter parameter, string? expectedDeclaration) + { + var declaration = GetNSStringSmartEnumAuxVariable (parameter); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + class TestDataGetNSArrayBindFromAuxVariableTests : IEnumerable { + public IEnumerator GetEnumerator () + { + // nsnumber + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForArray ("nint"), + name: "myParam") { + BindAs = new ("Foundation.NSNumber"), + }, + "var nsb_myParam = NSArray.FromNSObjects (obj => new NSNumber (obj), myParam);" + ]; + + // nsvalue + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForArray ("CoreGraphics.CGAffineTransform", isStruct: true), + name: "myParam") { + BindAs = new ("Foundation.NSValue"), + }, + "var nsb_myParam = NSArray.FromNSObjects (obj => new NSValue (obj), myParam);" + ]; + + // smart enum + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForArray ("MySmartEnum", isEnum: true, isSmartEnum: true), + name: "myParam") { + BindAs = new ("Foundation.NSString"), + }, + "var nsb_myParam = NSArray.FromNSObjects (obj => obj.GetConstant(), myParam);" + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetNSArrayBindFromAuxVariableTests))] + void GetNSArrayBindFromAuxVariableTests (in Parameter parameter, string? expectedDeclaration) + { + var declaration = GetNSArrayBindFromAuxVariable (parameter); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + class TestDataGetBindFromAuxVariableTests : IEnumerable { + public IEnumerator GetEnumerator () + { + // nsnumber + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_UInt64), + name: "myParam") { + BindAs = new ("Foundation.NSNumber"), + }, + "var nsb_myParam = NSNumber.FromUInt64 ((ulong) myParam);", + ]; + + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForArray ("nint"), + name: "myParam") { + BindAs = new ("Foundation.NSNumber"), + }, + "var nsb_myParam = NSArray.FromNSObjects (obj => new NSNumber (obj), myParam);" + ]; + + // nsvalue + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForStruct ("CoreAnimation.CATransform3D"), + name: "myParam") { + BindAs = new ("Foundation.NSValue"), + }, + "var nsb_myParam = NSValue.FromCATransform3D (myParam);", + ]; + + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForArray ("CoreGraphics.CGAffineTransform", isStruct: true), + name: "myParam") { + BindAs = new ("Foundation.NSValue"), + }, + "var nsb_myParam = NSArray.FromNSObjects (obj => new NSValue (obj), myParam);" + ]; + + // smart enum + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForEnum ("CoreAnimation.CATransform3D", isSmartEnum: true), + name: "myParam") { + BindAs = new ("Foundation.NSString"), + }, + "var nsb_myParam = myParam.GetConstant ();", + ]; + + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForArray ("MySmartEnum", isEnum: true, isSmartEnum: true), + name: "myParam") { + BindAs = new ("Foundation.NSString"), + }, + "var nsb_myParam = NSArray.FromNSObjects (obj => obj.GetConstant(), myParam);" + ]; + + //missing attr + yield return [ + new Parameter ( + position: 0, + type: ReturnTypeForEnum ("CoreAnimation.CATransform3D", isSmartEnum: true), + name: "myParam"), + null! + ]; + + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetBindFromAuxVariableTests))] + void GetBindFromAuxVariableTests (in Parameter parameter, string? expectedDeclaration) + { + var declaration = GetBindFromAuxVariable (parameter); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + [Fact] + void GetAutoreleasePoolVariableTests () + { + const string expected = "var autorelease_pool = new NSAutoreleasePool ();"; + var declaration = GetAutoreleasePoolVariable (); + Assert.NotNull (declaration); + Assert.Equal (expected, declaration.ToString ()); + } + + [Theory] + [InlineData (PlatformName.iOS, "UIKit.UIApplication.EnsureUIThread ();")] + [InlineData (PlatformName.TvOS, "UIKit.UIApplication.EnsureUIThread ();")] + [InlineData (PlatformName.MacCatalyst, "UIKit.UIApplication.EnsureUIThread ();")] + [InlineData (PlatformName.MacOSX, "AppKit.NSApplication.EnsureUIThread ();")] + [InlineData (PlatformName.WatchOS, null)] + [InlineData (PlatformName.None, null)] + void EnsureUiThreadTests (PlatformName platform, string? expectedDeclaration) + { + var declaration = EnsureUiThread (platform); + if (expectedDeclaration is null) { + Assert.Null (declaration); + } else { + Assert.NotNull (declaration); + Assert.Equal (expectedDeclaration, declaration.ToString ()); + } + } + + [Fact] + void GetExceptionHandleAuxVariableTests () + { + var expected = "IntPtr exception_gchandle = IntPtr.Zero;"; + var declaration = GetExceptionHandleAuxVariable (); + Assert.Equal (expected, declaration.ToString ()); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/EmitterFactoryTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/EmitterFactoryTests.cs index 63af590719e0..125e423f4863 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/EmitterFactoryTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/EmitterFactoryTests.cs @@ -12,7 +12,7 @@ namespace Microsoft.Macios.Generator.Tests.Emitters; public class EmitterFactoryTests : BaseGeneratorTestClass { - CodeChanges CreateSymbol (ApplePlatform platform, string inputText) where T : BaseTypeDeclarationSyntax + Binding CreateSymbol (ApplePlatform platform, string inputText) where T : BaseTypeDeclarationSyntax { var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); Assert.Single (syntaxTrees); @@ -25,7 +25,7 @@ CodeChanges CreateSymbol (ApplePlatform platform, string inputText) where T : var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); var symbol = semanticModel.GetDeclaredSymbol (declaration); Assert.NotNull (symbol); - var changes = CodeChanges.FromDeclaration (declaration, semanticModel); + var changes = Binding.FromDeclaration (declaration, semanticModel); Assert.NotNull (changes); return changes.Value; } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/GetObjCMessageSendMethodNameTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/GetObjCMessageSendMethodNameTests.cs new file mode 100644 index 000000000000..1ce2de7caf41 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/GetObjCMessageSendMethodNameTests.cs @@ -0,0 +1,380 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.IO.Compression; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using Xunit; +using static Microsoft.Macios.Generator.Emitters.BindingSyntaxFactory; + +namespace Microsoft.Macios.Generator.Tests.Emitters; + +public class GetObjCMessageSendMethodNameTests : BaseGeneratorTestClass { + + class TestDataGetObjCMessageSendMethodName : IEnumerable { + public IEnumerator GetEnumerator () + { + const string propertyNSObjectGetter = @" +using System; +using ARKit; +using Foundation; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export(""identifier"")] + public NSUuid Identifier { get; } +} +"; + yield return [propertyNSObjectGetter, "NativeHandle_objc_msgSend", null!, false, false]; + + const string propertyNSObjectGetterSetter = @" +using System; +using ARKit; +using Foundation; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export(""identifier"")] + public NSUuid Identifier { get; set; } +} +"; + yield return [propertyNSObjectGetterSetter, "NativeHandle_objc_msgSend", "void_objc_msgSend_NativeHandle", false, false]; + + const string propertyNSStringGetter = @" +using System; +using ARKit; +using Foundation; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export(""name"")] + public string Name { get; } +} +"; + + yield return [propertyNSStringGetter, "NativeHandle_objc_msgSend", null!, false, false]; + + const string propertyNSStringGetterSetter = @" +using System; +using ARKit; +using Foundation; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export(""name"")] + public string Name { get; set; } +} +"; + + yield return [propertyNSStringGetterSetter, "NativeHandle_objc_msgSend", "void_objc_msgSend_NativeHandle", false, false]; + + const string customMarshall = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export (""transform"")] + NMatrix4 Transform { + [Export ( + ""transform"", + Flags = ObjCBindings.Property.CustomMarshalDirective, + NativePrefix = ""xamarin_simd__"", + Library = ""__Internal"")] + get; + } +} +"; + + yield return [customMarshall, "xamarin_simd__NMatrix4_objc_msgSend", null!, false, false]; + + const string floatPropertyGetterSetter = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + [Export (""radius"")] + float Radius { get; set; } +} +"; + yield return [floatPropertyGetterSetter, "float_objc_msgSend", "void_objc_msgSend_float", false, false]; + + const string nativeEnum = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[Native] +public enum ARAppClipCodeUrlDecodingState : long { + Decoding, + Failed, + Decoded, +} + +[BindingType] +class ARAnchor { + + [Export (""urlDecodingState"")] + ARAppClipCodeUrlDecodingState UrlDecodingState { get; set; } + +} +"; + + yield return [nativeEnum, "IntPtr_objc_msgSend", "void_objc_msgSend_IntPtr", false, false]; + + const string nativeEnumUnsigned = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[Native] +public enum ARAppClipCodeUrlDecodingState : ulong { + Decoding, + Failed, + Decoded, +} + +[BindingType] +class ARAnchor { + + [Export (""urlDecodingState"")] + ARAppClipCodeUrlDecodingState UrlDecodingState { get; set; } + +} +"; + + yield return [nativeEnumUnsigned, "UIntPtr_objc_msgSend", "void_objc_msgSend_UIntPtr", false, false]; + + const string boolProperty = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export (""tracked"")] + bool IsTracked { get; set; } + +} +"; + + yield return [boolProperty, "bool_objc_msgSend", "void_objc_msgSend_bool", false, false]; + + const string nfloatProperty = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export (""tracked"")] + nfloat IsTracked { get; set; } + +} +"; + + yield return [nfloatProperty, "nfloat_objc_msgSend", "void_objc_msgSend_nfloat", false, false]; + + const string nintProperty = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export (""tracked"")] + nint IsTracked { get; set; } + +} +"; + + yield return [nintProperty, "IntPtr_objc_msgSend", "void_objc_msgSend_IntPtr", false, false]; + + const string nuintProperty = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export (""tracked"")] + nuint IsTracked { get; set; } + +} +"; + + yield return [nuintProperty, "UIntPtr_objc_msgSend", "void_objc_msgSend_UIntPtr", false, false]; + + const string cgsizeProperty = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export (""tracked"")] + CGSize IsTracked { get; set; } + +} +"; + + yield return [cgsizeProperty, "CGSize_objc_msgSend", "void_objc_msgSend_CGSize", false, false]; + + const string doubleProperty = @" +using System; +using ARKit; +using Foundation; +using CoreGraphics; +using ObjCRuntime; +using ObjCBindings; + +namepsace NS; + +[BindingType] +class ARAnchor { + + [Export (""tracked"")] + double IsTracked { get; set; } + +} +"; + + yield return [doubleProperty, "Double_objc_msgSend", "void_objc_msgSend_Double", false, false]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + class TestDataGetObjCMessageSendMethodNameSuper : IEnumerable { + public IEnumerator GetEnumerator () + { + var simple = new TestDataGetObjCMessageSendMethodName (); + foreach (var args in simple) { + // modify the first argument to be the correct msg send + args [1] = ((string) args [1]).Replace ("objc_msgSend", "objc_msgSendSuper"); + if (args [2] is not null) + args [2] = ((string) args [2]).Replace ("objc_msgSend", "objc_msgSendSuper"); + args [3] = true; + yield return args; + } + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + class TestDataGetObjCMessageSendMethodNameStret : IEnumerable { + public IEnumerator GetEnumerator () + { + var simple = new TestDataGetObjCMessageSendMethodName (); + foreach (var args in simple) { + // modify the first argument to be the correct msg send + args [1] = ((string) args [1]).Replace ("objc_msgSend", "objc_msgSend_stret"); + if (args [2] is not null) + args [2] = ((string) args [2]).Replace ("objc_msgSend", "objc_msgSend_stret"); + args [4] = true; + yield return args; + } + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + [AllSupportedPlatformsClassData] + [AllSupportedPlatformsClassData] + void GetObjCMessageSendMethodNamePropertiesTests (ApplePlatform platform, string inputText, string expectedGetter, string expectedSetter, bool isSuper, bool isStret) + { + var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); + Assert.Single (syntaxTrees); + var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); + var declaration = syntaxTrees [0].GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + Assert.True (Property.TryCreate (declaration, semanticModel, out var changes)); + Assert.NotNull (changes); + var methods = GetObjCMessageSendMethods (changes.Value, isSuper: isSuper, isStret: isStret); + Assert.Equal (expectedGetter, methods.Getter); + Assert.Equal (expectedSetter, methods.Setter); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/CompilationExtensionsTest.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/CompilationExtensionsTest.cs index 6276f27412c1..8e51bb698397 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/CompilationExtensionsTest.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/CompilationExtensionsTest.cs @@ -1,5 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; using Microsoft.Macios.Generator.Extensions; using Xamarin.Tests; using Xamarin.Utils; @@ -21,4 +25,76 @@ public void GetCurrentPlatformTests (ApplePlatform platform, PlatformName expect var (compilation, _) = CreateCompilation (platform); Assert.Equal (expectedPlatform, compilation.GetCurrentPlatform ()); } + + class TestDataGetUINamespaces : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + ApplePlatform.iOS, + new [] { + "UIKit", + "Twitter", + "NewsstandKit", + "QuickLook", + "EventKitUI", + "AddressBookUI", + "MessageUI", + "PhotosUI", + "HealthKitUI", + "GameKit", + "MapKit" + }]; + + yield return [ + ApplePlatform.TVOS, + new [] { + "UIKit", + "PhotosUI", + "GameKit", + "MapKit", + }]; + + yield return [ + ApplePlatform.MacOSX, + new [] { + "AppKit", + "QuickLook", + "PhotosUI", + "GameKit", + "MapKit", + }]; + + yield return [ + ApplePlatform.MacCatalyst, + new [] { + "AppKit", + "UIKit", + "QuickLook", + "EventKitUI", + "MessageUI", + "PhotosUI", + "HealthKitUI", + "GameKit", + "MapKit", + }]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataGetUINamespaces))] + public void GetUINamespacesTests (ApplePlatform platform, string [] expectedNamespaces) + { + var collectionComparer = new CollectionComparer (StringComparer.Ordinal); + // we need a source to trigger the parsing. Otherwise the compilation will have no syntax + // trees and therefore no preprocessor symbols + const string dummyClass = @" +using System; + +public class DummyClass {} +"; + var (compilation, _) = CreateCompilation (platform, sources: dummyClass); + Assert.True (collectionComparer.Equals (expectedNamespaces, compilation.GetUINamespaces (force: true))); + } } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/EnumExtensionTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/EnumExtensionTests.cs new file mode 100644 index 000000000000..f6553d75bd88 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/EnumExtensionTests.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#pragma warning disable APL0003 + +using System; +using Microsoft.Macios.Generator.Extensions; +using Xunit; + +namespace Microsoft.Macios.Generator.Tests.Extensions; + +public class EnumExtensionTests { + + [Theory] + [InlineData (ObjCBindings.Property.Notification, false)] + [InlineData (ObjCBindings.Property.CustomMarshalDirective, true)] + [InlineData (ObjCBindings.Method.Default, false)] + [InlineData (ObjCBindings.Method.CustomMarshalDirective, true)] + [InlineData (StringComparison.Ordinal, false)] + public void HasCustomMarshalDirective (T enumValue, bool expected) where T : Enum + => Assert.Equal (enumValue.HasCustomMarshalDirective (), expected); + + [Theory] + [InlineData (ObjCBindings.Property.Notification, false)] + public void HasMarshalNativeExceptions (T enumValue, bool expected) where T : Enum + => Assert.Equal (enumValue.HasMarshalNativeExceptions (), expected); +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsInheritanceTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsInheritanceTests.cs index ba791b750b0e..67a65964decb 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsInheritanceTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsInheritanceTests.cs @@ -27,7 +27,13 @@ namespace NS; public class TestClass {} "; - yield return [simpleClass, false, false, new [] { "object" }, new string [] { }]; + yield return [ + simpleClass, + false, + false, + false, + new [] { "object" }, + new string [] { }]; const string genericClass = @" using System; @@ -36,7 +42,13 @@ namespace NS; public class TestClass where T Enum {} "; - yield return [genericClass, false, false, new [] { "object" }, new string [] { }]; + yield return [ + genericClass, + false, + false, + false, + new [] { "object" }, + new string [] { }]; const string singleParent = @" using System; @@ -47,7 +59,13 @@ public class Parent {} public class TestClass : Parent {} "; - yield return [singleParent, false, false, new [] { "NS.Parent", "object" }, new string [] { }]; + yield return [ + singleParent, + false, + false, + false, + new [] { "NS.Parent", "object" }, + new string [] { }]; const string genericParent = @" using System; @@ -58,7 +76,13 @@ public class Parent where T object {} public class TestClass : Parent {} "; - yield return [genericParent, false, false, new [] { "NS.Parent", "object" }, new string [] { }]; + yield return [ + genericParent, + false, + false, + false, + new [] { "NS.Parent", "object" }, + new string [] { }]; const string multiParent = @" using System; @@ -70,7 +94,12 @@ public class Parent1 : Parent0 {} public class TestClass : Parent1 {} "; - yield return [multiParent, false, false, new [] { "NS.Parent1", "NS.Parent0", "object" }, new string [] { }]; + yield return [multiParent, + false, + false, + false, + new [] { "NS.Parent1", "NS.Parent0", "object" }, + new string [] { }]; const string singleInterface = @" using System; @@ -81,7 +110,13 @@ public interface IInterface {} public class TestClass : IInterface {} "; - yield return [singleInterface, false, false, new [] { "object" }, new [] { "NS.IInterface" }]; + yield return [ + singleInterface, + false, + false, + false, + new [] { "object" }, + new [] { "NS.IInterface" }]; const string genericInterface = @" using System; @@ -92,7 +127,13 @@ public interface IInterface where T : object {} public class TestClass : IInterface {} "; - yield return [genericInterface, false, false, new [] { "object" }, new [] { "NS.IInterface" }]; + yield return [ + genericInterface, + false, + false, + false, + new [] { "object" }, + new [] { "NS.IInterface" }]; const string severalInterfaces = @" using System; @@ -104,7 +145,13 @@ public interface IInterface2 {} public class TestClass : IInterface1, IInterface2 {} "; - yield return [severalInterfaces, false, false, new [] { "object" }, new [] { "NS.IInterface1", "NS.IInterface2" }]; + yield return [ + severalInterfaces, + false, + false, + false, + new [] { "object" }, + new [] { "NS.IInterface1", "NS.IInterface2" }]; const string severalGenericInterfaces = @" using System; @@ -115,7 +162,12 @@ public interface IInterface1 where T : object {} public class TestClass : IInterface1, IInterface1 {} "; - yield return [severalGenericInterfaces, false, false, new [] { "object" }, new [] { "NS.IInterface1", "NS.IInterface1" }]; + yield return [severalGenericInterfaces, + false, + false, + false, + new [] { "object" }, + new [] { "NS.IInterface1", "NS.IInterface1" }]; const string parentSingleInterface = @" using System; @@ -127,7 +179,13 @@ public class Parent : IInterface {} public class TestClass : Parent {} "; - yield return [parentSingleInterface, false, false, new [] { "NS.Parent", "object" }, new [] { "NS.IInterface" }]; + yield return [ + parentSingleInterface, + false, + false, + false, + new [] { "NS.Parent", "object" }, + new [] { "NS.IInterface" }]; const string nsObjectChild = @" using System; @@ -149,6 +207,7 @@ protected AVCaptureDataOutputSynchronizer (NSObjectFlag t) : base (t) yield return [nsObjectChild, true, true, + false, new [] { "Foundation.NSObject", "object" }, new [] { "ObjCRuntime.INativeObject", @@ -180,6 +239,7 @@ public partial class Child : AVCaptureDataOutputSynchronizer {} yield return [nsObjectNestedChild, true, true, + false, new [] { "NS.AVCaptureDataOutputSynchronizer", "Foundation.NSObject", "object" }, new [] { "ObjCRuntime.INativeObject", @@ -209,10 +269,27 @@ protected AVCaptureDataOutputSynchronizer (NSObjectFlag t) : base (t) yield return [nativeObjectInterface, false, true, + false, new [] { "object" }, new [] { "ObjCRuntime.INativeObject", }]; + + const string dictionaryContainer = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace NS; +public partial class SKCloudServiceSetupOptions : DictionaryContainer { } +"; + + yield return [dictionaryContainer, + false, + false, + true, + new [] { "Foundation.DictionaryContainer", "object" }, + new string [] { }]; } IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); @@ -221,7 +298,8 @@ protected AVCaptureDataOutputSynchronizer (NSObjectFlag t) : base (t) [Theory] [AllSupportedPlatformsClassData] void GetInheritance (ApplePlatform platform, string inputText, - bool expectedIsNSObject, bool expectedIsNativeObject, string [] expectedParents, string [] expectedInterfaces) + bool expectedIsNSObject, bool expectedIsNativeObject, bool expectedDictionaryContainer, + string [] expectedParents, string [] expectedInterfaces) { var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); Assert.Single (syntaxTrees); @@ -237,11 +315,13 @@ void GetInheritance (ApplePlatform platform, string inputText, symbol.GetInheritance ( isNSObject: out var isNsObject, isNativeObject: out var isNativeObject, + isDictionaryContainer: out var isDictionaryContainer, parents: out var parents, interfaces: out var interfaces); Assert.Equal (expectedIsNSObject, isNsObject); Assert.Equal (expectedIsNativeObject, isNativeObject); Assert.Equal (expectedParents, parents); Assert.Equal (expectedInterfaces, interfaces); + Assert.Equal (expectedDictionaryContainer, isDictionaryContainer); } } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsSizeTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsSizeTests.cs new file mode 100644 index 000000000000..04e73950fcdf --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsSizeTests.cs @@ -0,0 +1,493 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using ObjCRuntime; +using Xamarin.Tests; +using Xamarin.Utils; +using Xunit; +using Microsoft.Macios.Generator.Extensions; + +namespace Microsoft.Macios.Generator.Tests.Extensions; + +public class TypeSymbolExtensionsSizeTests : BaseGeneratorTestClass { + + + class TestDataTryGetBuiltInTypeSize : IEnumerable { + public IEnumerator GetEnumerator () + { + // create properties so that we can get the return symbol and use it to calculate the size, + // we make sure that the result is the same as the one returned by the Stret.cs code. + const string nfloatProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + NFloat Test { get; set; } +} +"; + yield return [nfloatProperty, typeof (NFloat)]; + + const string charProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + char Test { get; set; } +} +"; + yield return [charProperty, typeof (Char)]; + + const string boolProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + bool Test { get; set; } +} +"; + yield return [boolProperty, typeof (Boolean)]; + + const string sbyteProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + sbyte Test { get; set; } +} +"; + yield return [sbyteProperty, typeof (SByte)]; + + const string byteProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + byte Test { get; set; } +} +"; + yield return [byteProperty, typeof (Byte)]; + + const string singleProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + Single Test { get; set; } +} +"; + yield return [singleProperty, typeof (Single)]; + + const string intProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + int Test { get; set; } +} +"; + yield return [intProperty, typeof (Int32)]; + + const string uintProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + uint Test { get; set; } +} +"; + yield return [uintProperty, typeof (UInt32)]; + + const string doubleProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + double Test { get; set; } +} +"; + yield return [doubleProperty, typeof (Double)]; + + const string int64Property = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + long Test { get; set; } +} +"; + yield return [int64Property, typeof (Int64)]; + + const string uint64Property = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + ulong Test { get; set; } +} +"; + yield return [uint64Property, typeof (UInt64)]; + + const string intPtrProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + IntPtr Test { get; set; } +} +"; + yield return [intPtrProperty, typeof (IntPtr)]; + + const string uIntPtrProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + UIntPtr Test { get; set; } +} +"; + yield return [uIntPtrProperty, typeof (UIntPtr)]; + + const string nintProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + nint Test { get; set; } +} +"; + yield return [nintProperty, typeof (nint)]; + + const string nuintProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + nuint Test { get; set; } +} +"; + yield return [nuintProperty, typeof (nuint)]; + + const string floatProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + float Test { get; set; } +} +"; + yield return [floatProperty, typeof (float)]; + + const string stringProperty = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +public class TestClass { + string Test { get; set; } +} +"; + yield return [stringProperty, typeof (string)]; + + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + public void TryGetBuiltInTypeSizeTests (ApplePlatform platform, string inputText, Type type) + { + var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); + Assert.Single (syntaxTrees); + var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); + var declaration = syntaxTrees [0].GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + // 32bit + var expectedResult = Stret.IsBuiltInType (type, false, out var expectedTypeSize); + var result = symbol.Type.TryGetBuiltInTypeSize (false, out var returnTypeSize); + Assert.Equal (expectedResult, result); + Assert.Equal (expectedTypeSize, returnTypeSize); + + // 64bit + var expectedResult64 = Stret.IsBuiltInType (type, false, out var expectedTypeSize64); + var result64 = symbol.Type.TryGetBuiltInTypeSize (false, out var returnTypeSize64); + Assert.Equal (expectedResult64, result64); + Assert.Equal (expectedTypeSize64, returnTypeSize64); + } + + class TestDataGetValueTypeSizeTests : IEnumerable { + + [StructLayout (LayoutKind.Sequential)] + public struct AVSampleCursorSyncInfo { + [MarshalAs (UnmanagedType.I1)] + public bool IsFullSync; + + [MarshalAs (UnmanagedType.I1)] + public bool IsPartialSync; + + [MarshalAs (UnmanagedType.I1)] + public bool IsDroppable; + } + + [StructLayout (LayoutKind.Sequential)] + public struct AVSampleCursorDependencyInfo { + [MarshalAs (UnmanagedType.I1)] + public bool IndicatesWhetherItHasDependentSamples; + + [MarshalAs (UnmanagedType.I1)] + public bool HasDependentSamples; + + [MarshalAs (UnmanagedType.I1)] + public bool IndicatesWhetherItDependsOnOthers; + + [MarshalAs (UnmanagedType.I1)] + public bool DependsOnOthers; + + [MarshalAs (UnmanagedType.I1)] + public bool IndicatesWhetherItHasRedundantCoding; + + [MarshalAs (UnmanagedType.I1)] + public bool HasRedundantCoding; + } + + [StructLayout (LayoutKind.Sequential)] + public struct AVSampleCursorStorageRange { + public long Offset; + public long Length; + } + + [StructLayout (LayoutKind.Sequential)] + public struct AVSampleCursorChunkInfo { + public long SampleCount; + + [MarshalAs (UnmanagedType.I1)] + public bool HasUniformSampleSizes; + + [MarshalAs (UnmanagedType.I1)] + public bool HasUniformSampleDurations; + + [MarshalAs (UnmanagedType.I1)] + public bool HasUniformFormatDescriptions; + } + + public IEnumerator GetEnumerator () + { + // duplicate the definition of the above structs and ensure that we do get the same values + const string avSampleCursorSyncInfo = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +[StructLayout (LayoutKind.Sequential)] +public struct AVSampleCursorSyncInfo { + [MarshalAs (UnmanagedType.I1)] + public bool IsFullSync; + + [MarshalAs (UnmanagedType.I1)] + public bool IsPartialSync; + + [MarshalAs (UnmanagedType.I1)] + public bool IsDroppable; +} +"; + yield return [ + avSampleCursorSyncInfo, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorSyncInfo), + fieldTypes: new (), + is_64_bits: false, + generator: new object ()), + false]; + + yield return [ + avSampleCursorSyncInfo, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorSyncInfo), + fieldTypes: new (), + is_64_bits: true, + generator: new object ()), + true]; + + const string avSampleCursorDependencyInfo = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +[StructLayout (LayoutKind.Sequential)] +public struct AVSampleCursorDependencyInfo { + [MarshalAs (UnmanagedType.I1)] + public bool IndicatesWhetherItHasDependentSamples; + + [MarshalAs (UnmanagedType.I1)] + public bool HasDependentSamples; + + [MarshalAs (UnmanagedType.I1)] + public bool IndicatesWhetherItDependsOnOthers; + + [MarshalAs (UnmanagedType.I1)] + public bool DependsOnOthers; + + [MarshalAs (UnmanagedType.I1)] + public bool IndicatesWhetherItHasRedundantCoding; + + [MarshalAs (UnmanagedType.I1)] + public bool HasRedundantCoding; +} +"; + + yield return [ + avSampleCursorDependencyInfo, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorDependencyInfo), + fieldTypes: new (), + is_64_bits: false, + generator: new object ()), + false]; + + yield return [ + avSampleCursorDependencyInfo, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorDependencyInfo), + fieldTypes: new (), + is_64_bits: true, + generator: new object ()), + true]; + + const string avsampleCursorStorageRange = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + +[StructLayout (LayoutKind.Sequential)] +public struct AVSampleCursorStorageRange { + public long Offset; + public long Length; +} +"; + + yield return [ + avsampleCursorStorageRange, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorStorageRange), + fieldTypes: new (), + is_64_bits: false, + generator: new object ()), + false]; + + yield return [ + avsampleCursorStorageRange, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorStorageRange), + fieldTypes: new (), + is_64_bits: true, + generator: new object ()), + true]; + + const string avsampleCursorChunkInfo = @" +using System; +using System.Runtime.InteropServices; + +namespace NS; + + +[StructLayout (LayoutKind.Sequential)] +public struct AVSampleCursorChunkInfo { + public long SampleCount; + + [MarshalAs (UnmanagedType.I1)] + public bool HasUniformSampleSizes; + + [MarshalAs (UnmanagedType.I1)] + public bool HasUniformSampleDurations; + + [MarshalAs (UnmanagedType.I1)] + public bool HasUniformFormatDescriptions; +} +"; + + yield return [ + avsampleCursorChunkInfo, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorChunkInfo), + fieldTypes: new (), + is_64_bits: false, + generator: new object ()), + false]; + + yield return [ + avsampleCursorChunkInfo, + Stret.GetValueTypeSize ( + type: typeof (AVSampleCursorChunkInfo), + fieldTypes: new (), + is_64_bits: true, + generator: new object ()), + true]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + public void GetValueTypeSizeTests (ApplePlatform platform, string inputText, int expectedSize, bool is64Bits) + { + var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); + Assert.Single (syntaxTrees); + var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); + var declaration = syntaxTrees [0].GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + var x = symbol.GetValueTypeSize (new (), false); + Assert.Equal (expectedSize, symbol.GetValueTypeSize (new (), is64Bits)); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsTests.cs index 6b7eee836438..0b7181058c48 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Extensions/TypeSymbolExtensionsTests.cs @@ -117,7 +117,7 @@ public void Method(){} } } "; - Func getNestedMethod = + Func getNestedMethod = rootNode => rootNode.DescendantNodes ().OfType ().LastOrDefault (); var nestedMethodNestedClassParents = new [] { "ChildClass", "ParentClass" }; yield return [nestedMethodNestedClass, getNestedMethod, nestedMethodNestedClassParents]; @@ -152,7 +152,7 @@ public void Method(){} yield return [nestedNamespacesNestedClass, getNestedMethod, nestedNamespacesParents]; - Func getEnumValue = + Func getEnumValue = rootNode => rootNode.DescendantNodes ().OfType ().LastOrDefault (); const string enumValueNested = @" using System; @@ -169,6 +169,26 @@ public enum MyEnum { "; var enumParensts = new [] { "MyEnum", "ChildClass", "ParentClass" }; yield return [enumValueNested, getEnumValue, enumParensts]; + + Func getGetterValue = + rootNode => rootNode.DescendantNodes ().OfType ().LastOrDefault (); + const string propertyGetter = @" +using System; + +namespace Test; + +public class ParentClass { + public class ChildClass { + public int Property { + get { + return 0; + } + } + } +} +"; + var getterParents = new [] { "Property", "ChildClass", "ParentClass" }; + yield return [propertyGetter, getGetterValue, getterParents]; } IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); @@ -177,7 +197,7 @@ public enum MyEnum { [Theory] [AllSupportedPlatformsClassData] public void GetParentTests (ApplePlatform platform, string inputText, - Func getNode, string [] expectedParents) + Func getNode, string [] expectedParents) { var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); Assert.Single (syntaxTrees); @@ -1683,4 +1703,161 @@ void IsBlittable (ApplePlatform platform, string inputText, bool expectedResult) Assert.Equal (expectedResult, symbol.Type.IsBlittable ()); } + class TestDataIsWrapped : IEnumerable { + public IEnumerator GetEnumerator () + { + const string stringProperty = @" +using System; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public string Property { get; set; } +} +"; + yield return [stringProperty, false]; + + const string nsUuidProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public NSUuid Property { get; set; } +} +"; + yield return [nsUuidProperty, true]; + + const string nmatrix4Property = @" +using System; +using CoreGraphics; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public NMatrix4 Property { get; set; } +} +"; + + yield return [nmatrix4Property, false]; + + const string nativeHandleProperty = @" +using System; +using ObjCRuntime; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public NativeHandle Property { get; set; } +} +"; + yield return [nativeHandleProperty, false]; + + const string nsZoneProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public NSZone Property { get; set; } +} +"; + yield return [nsZoneProperty, false]; + + const string nsobjectProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public NSObject Property { get; set; } +} +"; + yield return [nsobjectProperty, true]; + + const string nssetProperty = @" +using System; +using Foundation; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public NSSet Property { get; set; } +} +"; + yield return [nssetProperty, true]; + + + const string mtlDeviceProperty = @" +using System; +using Metal; +using ObjCBindings; + +namespace NS; + +[BindingType] +public partial class MyClass { + public IMTLDevice Property { get; set; } +} +"; + yield return [mtlDeviceProperty, true]; + + const string EnumProperty = @" +using System; +using System.Runtime.InteropServices; +using ObjCBindings; + +namespace NS; + +public enum MyEnum : ulong { + First, + Second, +} + +[BindingType] +public partial class MyClass { + public MyEnum Property { get; set; } +} +"; + yield return [EnumProperty, false]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void IsWrapped (ApplePlatform platform, string inputText, bool expectedResult) + { + var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); + Assert.Single (syntaxTrees); + var declaration = syntaxTrees [0].GetRoot () + .DescendantNodes () + .OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); + Assert.NotNull (semanticModel); + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + Assert.Equal (expectedResult, symbol.Type.IsWrapped ()); + } + } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Formatters/SmartEnumFormatterTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Formatters/SmartEnumFormatterTests.cs index 3293894cb3b9..a75616cfc6e1 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Formatters/SmartEnumFormatterTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Formatters/SmartEnumFormatterTests.cs @@ -73,7 +73,7 @@ public void ToDeclarationTests (ApplePlatform platform, string inputText, string Assert.NotNull (declaration); var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); Assert.NotNull (semanticModel); - var changes = CodeChanges.FromDeclaration (declaration, semanticModel); + var changes = Binding.FromDeclaration (declaration, semanticModel); Assert.NotNull (changes); var classDeclaration = changes.ToSmartEnumExtensionDeclaration (className); Assert.NotNull (classDeclaration); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/TabbedStringBuilderTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/IO/TabbedStringBuilderTests.cs similarity index 62% rename from tests/rgen/Microsoft.Macios.Generator.Tests/TabbedStringBuilderTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/IO/TabbedStringBuilderTests.cs index 0f37aa02be93..e78f81e48157 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/TabbedStringBuilderTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/IO/TabbedStringBuilderTests.cs @@ -1,14 +1,16 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; + using System.Collections.Generic; using System.ComponentModel; using System.Text; +using System.Threading.Tasks; using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.IO; using Xunit; -namespace Microsoft.Macios.Generator.Tests; +namespace Microsoft.Macios.Generator.Tests.IO; public class TabbedStringBuilderTests { StringBuilder sb; @@ -22,12 +24,12 @@ public TabbedStringBuilderTests () [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void ConstructorNotBlockTest (uint tabCount, string expectedTabs) + public void ConstructorNotBlockTest (int tabCount, string expectedTabs) { string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { - block.AppendLine ("Test"); - result = block.ToString (); + block.WriteLine ("Test"); + result = block.ToCode (); } Assert.Equal ($"{expectedTabs}Test\n", result); @@ -37,12 +39,12 @@ public void ConstructorNotBlockTest (uint tabCount, string expectedTabs) [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void ConstructorBlockTest (uint tabCount, string expectedTabs) + public void ConstructorBlockTest (int tabCount, string expectedTabs) { string result; using (var block = new TabbedStringBuilder (sb, tabCount, true)) { - block.AppendLine ("Test"); - result = block.ToString (); + block.WriteLine ("Test"); + result = block.ToCode (); } Assert.Equal ($"{expectedTabs}{{\n{expectedTabs}\tTest\n{expectedTabs}}}\n", result); @@ -52,12 +54,28 @@ public void ConstructorBlockTest (uint tabCount, string expectedTabs) [InlineData (0)] [InlineData (1)] [InlineData (5)] - public void AppendLineTest (uint tabCount) + public void AppendLineTest (int tabCount) { string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { - block.AppendLine (); - result = block.ToString (); + block.WriteLine (); + result = block.ToCode (); + } + + // an empty line should have not tabs + Assert.Equal ("\n", result); + } + + [Theory] + [InlineData (0)] + [InlineData (1)] + [InlineData (5)] + public async Task AppendLineTestAsync (int tabCount) + { + string result; + using (var block = new TabbedStringBuilder (sb, tabCount)) { + await block.WriteLineAsync (); + result = block.ToCode (); } // an empty line should have not tabs @@ -68,12 +86,27 @@ public void AppendLineTest (uint tabCount) [InlineData ("// test comment", 0, "")] [InlineData ("var t = 1;", 1, "\t")] [InlineData ("Console.WriteLine (\"1\");", 5, "\t\t\t\t\t")] - public void AppendLineStringTest (string line, uint tabCount, string expectedTabs) + public void AppendLineStringTest (string line, int tabCount, string expectedTabs) { string result; using (var block = new TabbedStringBuilder (sb, tabCount, true)) { - block.AppendLine (line); - result = block.ToString (); + block.WriteLine (line); + result = block.ToCode (); + } + + Assert.Equal ($"{expectedTabs}{{\n{expectedTabs}\t{line}\n{expectedTabs}}}\n", result); + } + + [Theory] + [InlineData ("// test comment", 0, "")] + [InlineData ("var t = 1;", 1, "\t")] + [InlineData ("Console.WriteLine (\"1\");", 5, "\t\t\t\t\t")] + public async Task AppendLineStringTestAsync (string line, int tabCount, string expectedTabs) + { + string result; + using (var block = new TabbedStringBuilder (sb, tabCount, true)) { + await block.WriteLineAsync (line); + result = block.ToCode (); } Assert.Equal ($"{expectedTabs}{{\n{expectedTabs}\t{line}\n{expectedTabs}}}\n", result); @@ -83,7 +116,7 @@ public void AppendLineStringTest (string line, uint tabCount, string expectedTab [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void AppendInterpolatedLineTest (uint tabCount, string expectedTabs) + public void AppendInterpolatedLineTest (int tabCount, string expectedTabs) { string result; var val1 = "Hello"; @@ -92,8 +125,8 @@ public void AppendInterpolatedLineTest (uint tabCount, string expectedTabs) var line = "Hello World!"; var expected = $"{expectedTabs}{{\n{expectedTabs}\t{line}\n{expectedTabs}}}\n"; using (var block = new TabbedStringBuilder (sb, tabCount, true)) { - block.AppendLine ($"{val1} {val2}{val3}"); - result = block.ToString (); + block.WriteLine ($"{val1} {val2}{val3}"); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -104,7 +137,7 @@ public void AppendInterpolatedLineTest (uint tabCount, string expectedTabs) [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void AppendRawTest (uint tabCount, string expectedTabs) + public void AppendRawTest (int tabCount, string expectedTabs) { var input = @" ## Raw string @@ -124,8 +157,8 @@ 3. And all lines should have the correct tabs "; string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { - block.AppendRaw (input); - result = block.ToString (); + block.WriteRaw (input); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -135,13 +168,44 @@ 3. And all lines should have the correct tabs [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void AppendGeneratedCodeAttributeTest (uint tabCount, string expectedTabs) + public async Task AppendRawTestAsync (int tabCount, string expectedTabs) + { + var input = @" +## Raw string +Because we are using a raw string we expected: + 1. The string to be split in lines + 2. All lines should have the right indentation + - This means nested one + 3. And all lines should have the correct tabs +"; + var expected = $@" +{expectedTabs}## Raw string +{expectedTabs}Because we are using a raw string we expected: +{expectedTabs} 1. The string to be split in lines +{expectedTabs} 2. All lines should have the right indentation +{expectedTabs} - This means nested one +{expectedTabs} 3. And all lines should have the correct tabs +"; + string result; + using (var block = new TabbedStringBuilder (sb, tabCount)) { + await block.WriteRawAsync (input); + result = block.ToCode (); + } + + Assert.Equal (expected, result); + } + + [Theory] + [InlineData (0, "")] + [InlineData (1, "\t")] + [InlineData (5, "\t\t\t\t\t")] + public void AppendGeneratedCodeAttributeTest (int tabCount, string expectedTabs) { var expected = $"{expectedTabs}[BindingImpl (BindingImplOptions.GeneratedCode)]\n"; string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { block.AppendGeneratedCodeAttribute (false); - result = block.ToString (); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -151,14 +215,14 @@ public void AppendGeneratedCodeAttributeTest (uint tabCount, string expectedTabs [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void AppendGeneratedCodeAttributeOptimizableTest (uint tabCount, string expectedTabs) + public void AppendGeneratedCodeAttributeOptimizableTest (int tabCount, string expectedTabs) { var expected = $"{expectedTabs}[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]\n"; string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { block.AppendGeneratedCodeAttribute (); - result = block.ToString (); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -168,13 +232,31 @@ public void AppendGeneratedCodeAttributeOptimizableTest (uint tabCount, string e [InlineData (EditorBrowsableState.Advanced, 0, "")] [InlineData (EditorBrowsableState.Never, 1, "\t")] [InlineData (EditorBrowsableState.Always, 5, "\t\t\t\t\t")] - public void AppendEditorBrowsableAttributeTest (EditorBrowsableState state, uint tabCount, string expectedTabs) + public void AppendEditorBrowsableAttributeTest (EditorBrowsableState state, int tabCount, string expectedTabs) { var expected = $"{expectedTabs}[EditorBrowsable (EditorBrowsableState.{state})]\n"; string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { block.AppendEditorBrowsableAttribute (state); - result = block.ToString (); + result = block.ToCode (); + } + + Assert.Equal (expected, result); + } + + [Theory] + [InlineData (0, "")] + [InlineData (1, "\t")] + [InlineData (5, "\t\t\t\t\t")] + public void AppendNotificationAdviceTests (int tabCount, string expectedTabs) + { + var className = "TestClass"; + var notificationName = "DidWriteAttribute"; + var expected = $"{expectedTabs}[Advice (\"Use '{className}.Notifications.{notificationName}' helper method instead.\")]\n"; + string result; + using (var block = new TabbedStringBuilder (sb, tabCount)) { + block.AppendNotificationAdvice (className, notificationName); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -184,13 +266,13 @@ public void AppendEditorBrowsableAttributeTest (EditorBrowsableState state, uint [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void AppendDesignatedInitializer (uint tabCount, string expectedTabs) + public void AppendDesignatedInitializer (int tabCount, string expectedTabs) { var expected = $"{expectedTabs}[DesignatedInitializer]\n"; string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { block.AppendDesignatedInitializer (); - result = block.ToString (); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -200,7 +282,7 @@ public void AppendDesignatedInitializer (uint tabCount, string expectedTabs) [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void CreateEmptyBlockTest (uint tabCount, string expectedTabs) + public void CreateEmptyBlockTest (int tabCount, string expectedTabs) { var blockContent = "// the test"; var expected = $@"{expectedTabs}{{ @@ -210,10 +292,10 @@ public void CreateEmptyBlockTest (uint tabCount, string expectedTabs) string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { using (var nested = block.CreateBlock (true)) { - nested.AppendLine (blockContent); + nested.WriteLine (blockContent); } - result = block.ToString (); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -223,7 +305,7 @@ public void CreateEmptyBlockTest (uint tabCount, string expectedTabs) [InlineData (0, "", "if (true)")] [InlineData (1, "\t", "using (var t = new StringBuilder)")] [InlineData (5, "\t\t\t\t\t", "fixed (*foo)")] - public void CreateBlockTest (uint tabCount, string expectedTabs, string blockType) + public void CreateBlockTest (int tabCount, string expectedTabs, string blockType) { var blockContent = "// the test"; var expected = $@"{expectedTabs}{blockType} @@ -234,10 +316,10 @@ public void CreateBlockTest (uint tabCount, string expectedTabs, string blockTyp string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { using (var nested = block.CreateBlock (blockType, true)) { - nested.AppendLine (blockContent); + nested.WriteLine (blockContent); } - result = block.ToString (); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -247,7 +329,7 @@ public void CreateBlockTest (uint tabCount, string expectedTabs, string blockTyp [InlineData (0, "")] [InlineData (1, "\t")] [InlineData (5, "\t\t\t\t\t")] - public void WriteHeaderTest (uint tabCount, string expectedTabs) + public void WriteHeaderTest (int tabCount, string expectedTabs) { var expected = $@"{expectedTabs}// @@ -257,7 +339,7 @@ public void WriteHeaderTest (uint tabCount, string expectedTabs) string result; using (var block = new TabbedStringBuilder (sb, tabCount)) { block.WriteHeader (); - result = block.ToString (); + result = block.ToCode (); } Assert.Equal (expected, result); @@ -314,7 +396,7 @@ void AppendMemberAvailabilityTest (SymbolAvailability availability, string expec { var block = new TabbedStringBuilder (sb); block.AppendMemberAvailability (availability); - var result = block.ToString (); + var result = block.ToCode (); Assert.Equal (expectedString, result); } @@ -323,9 +405,33 @@ public void ClearTests () { var block = new TabbedStringBuilder (sb); var line = "My Line"; - block.Append (line); - Assert.Equal (line, block.ToString ()); + block.Write (line); + Assert.Equal (line, block.ToCode ()); block.Clear (); - Assert.Equal (string.Empty, block.ToString ()); + Assert.Equal (string.Empty, block.ToCode ()); + } + + [Fact] + public void CreateBlockStringArray () + { + var expecteString = +@"using (var m1 = new MemoryStream()) +using (var m2 = new MemoryStream()) +using (var m3 = new MemoryStream()) +{ + // this is an example with several usings +} +"; + var baseBlock = new TabbedStringBuilder (sb); + // create a list of lines to get the new block + var usingStatements = new [] { + "using (var m1 = new MemoryStream())", + "using (var m2 = new MemoryStream())", + "using (var m3 = new MemoryStream())", + }; + using (var usingBlock = baseBlock.CreateBlock (usingStatements, true)) { + usingBlock.WriteLine ("// this is an example with several usings"); + } + Assert.Equal (expecteString, baseBlock.ToCode ()); } } diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj b/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj index 9571632f8d71..974bac298d84 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj @@ -7,6 +7,11 @@ true NU1608 Microsoft.Macios.Generator.Tests + RGEN + + + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)\..\..\..\src')) + rsp/dotnet @@ -27,6 +32,9 @@ + + external\ObjCRuntime\Stret.cs + external\Configuration.cs @@ -59,4 +67,12 @@ + + + + + + + + diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/TestDataFactory.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/TestDataFactory.cs index f64d79ad80e8..784c91fcccaa 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/TestDataFactory.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/TestDataFactory.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + #pragma warning disable APL0003 using Microsoft.CodeAnalysis; using TypeInfo = Microsoft.Macios.Generator.DataModel.TypeInfo; @@ -7,12 +8,11 @@ namespace Microsoft.Macios.Generator.Tests; static class TestDataFactory { - - public static TypeInfo ReturnTypeForString () + public static TypeInfo ReturnTypeForString (bool isNullable = false) => new ( name: "string", specialType: SpecialType.System_String, - isNullable: false, + isNullable: isNullable, isBlittable: false, isSmartEnum: false, isArray: false, @@ -35,58 +35,66 @@ public static TypeInfo ReturnTypeForString () IsINativeObject = false, }; - public static TypeInfo ReturnTypeForInt (bool isNullable = false) - => new ( - name: "int", - specialType: SpecialType.System_Int32, + public static TypeInfo ReturnTypeForInt (bool isNullable = false, bool keepInterfaces = false, + bool isUnsigned = false) + { + var typeName = isUnsigned ? "uint" : "int"; + var metadataName = isUnsigned ? "UInt32" : "Int32"; + var type = new TypeInfo ( + name: typeName, + specialType: isUnsigned ? SpecialType.System_UInt32 : SpecialType.System_Int32, isBlittable: !isNullable, - isNullable: isNullable + isNullable: isNullable, + isStruct: true ) { Parents = ["System.ValueType", "object"], - Interfaces = isNullable + Interfaces = isNullable && !keepInterfaces ? [] : [ - "System.IComparable", - "System.IComparable", + "System.IComparable", + $"System.IComparable<{typeName}>", "System.IConvertible", - "System.IEquatable", + $"System.IEquatable<{typeName}>", "System.IFormattable", - "System.IParsable", + $"System.IParsable<{typeName}>", "System.ISpanFormattable", - "System.ISpanParsable", + $"System.ISpanParsable<{typeName}>", "System.IUtf8SpanFormattable", - "System.IUtf8SpanParsable", - "System.Numerics.IAdditionOperators", - "System.Numerics.IAdditiveIdentity", - "System.Numerics.IBinaryInteger", - "System.Numerics.IBinaryNumber", - "System.Numerics.IBitwiseOperators", - "System.Numerics.IComparisonOperators", - "System.Numerics.IEqualityOperators", - "System.Numerics.IDecrementOperators", - "System.Numerics.IDivisionOperators", - "System.Numerics.IIncrementOperators", - "System.Numerics.IModulusOperators", - "System.Numerics.IMultiplicativeIdentity", - "System.Numerics.IMultiplyOperators", - "System.Numerics.INumber", - "System.Numerics.INumberBase", - "System.Numerics.ISubtractionOperators", - "System.Numerics.IUnaryNegationOperators", - "System.Numerics.IUnaryPlusOperators", - "System.Numerics.IShiftOperators", - "System.Numerics.IMinMaxValue", - "System.Numerics.ISignedNumber" - ], + $"System.IUtf8SpanParsable<{typeName}>", + $"System.Numerics.IAdditionOperators<{typeName}, {typeName}, {typeName}>", + $"System.Numerics.IAdditiveIdentity<{typeName}, {typeName}>", + $"System.Numerics.IBinaryInteger<{typeName}>", + $"System.Numerics.IBinaryNumber<{typeName}>", + $"System.Numerics.IBitwiseOperators<{typeName}, {typeName}, {typeName}>", + $"System.Numerics.IComparisonOperators<{typeName}, {typeName}, bool>", + $"System.Numerics.IEqualityOperators<{typeName}, {typeName}, bool>", + $"System.Numerics.IDecrementOperators<{typeName}>", + $"System.Numerics.IDivisionOperators<{typeName}, {typeName}, {typeName}>", + $"System.Numerics.IIncrementOperators<{typeName}>", + $"System.Numerics.IModulusOperators<{typeName}, {typeName}, {typeName}>", + $"System.Numerics.IMultiplicativeIdentity<{typeName}, {typeName}>", + $"System.Numerics.IMultiplyOperators<{typeName}, {typeName}, {typeName}>", + $"System.Numerics.INumber<{typeName}>", + $"System.Numerics.INumberBase<{typeName}>", + $"System.Numerics.ISubtractionOperators<{typeName}, {typeName}, {typeName}>", + $"System.Numerics.IUnaryNegationOperators<{typeName}, {typeName}>", + $"System.Numerics.IUnaryPlusOperators<{typeName}, {typeName}>", + $"System.Numerics.IShiftOperators<{typeName}, {typeName}, {typeName}>", + $"System.Numerics.IMinMaxValue<{typeName}>", + $"System.Numerics.ISignedNumber<{typeName}>" + ], MetadataName = "Int32", }; + return type; + } public static TypeInfo ReturnTypeForIntPtr (bool isNullable = false) => new ( name: "nint", specialType: SpecialType.System_IntPtr, isBlittable: !isNullable, - isNullable: isNullable + isNullable: isNullable, + isStruct: true ) { Parents = ["System.ValueType", "object"], Interfaces = isNullable @@ -125,13 +133,15 @@ public static TypeInfo ReturnTypeForIntPtr (bool isNullable = false) "System.Runtime.Serialization.ISerializable" ], MetadataName = "IntPtr", + IsNativeIntegerType = !isNullable, }; public static TypeInfo ReturnTypeForBool () => new ( name: "bool", specialType: SpecialType.System_Boolean, - isBlittable: false + isBlittable: false, + isStruct: true ) { Parents = ["System.ValueType", "object"], Interfaces = [ @@ -146,29 +156,44 @@ public static TypeInfo ReturnTypeForBool () }; public static TypeInfo ReturnTypeForVoid () - => new ("void", SpecialType.System_Void) { - Parents = ["System.ValueType", "object"], - }; + => new ("void", SpecialType.System_Void, isStruct: true) { Parents = ["System.ValueType", "object"], }; - public static TypeInfo ReturnTypeForClass (string className) + public static TypeInfo ReturnTypeForClass (string className, bool isNullable = false) => new ( name: className, + isReferenceType: true, + isNullable: isNullable + ) { Parents = ["object"] }; + + public static TypeInfo ReturnTypeForGeneric (string genericName, bool isNullable = false) + => new ( + name: genericName, + isReferenceType: false, + isNullable: isNullable + ); + + public static TypeInfo ReturnTypeForInterface (string interfaceName) + => new ( + name: interfaceName, isReferenceType: true ) { - Parents = ["object"] + Parents = [], + IsInterface = true, }; - public static TypeInfo ReturnTypeForStruct (string structName) + public static TypeInfo ReturnTypeForStruct (string structName, bool isBlittable = false) => new ( - name: structName - ) { - Parents = ["System.ValueType", "object"] - }; + name: structName, + isBlittable: isBlittable, + isStruct: true + ) { Parents = ["System.ValueType", "object"] }; - public static TypeInfo ReturnTypeForEnum (string enumName, bool isSmartEnum = false) + public static TypeInfo ReturnTypeForEnum (string enumName, bool isSmartEnum = false, bool isNativeEnum = false, + bool isNullable = false, bool isBlittable = true, SpecialType underlyingType = SpecialType.System_Int32) => new ( name: enumName, - isBlittable: true, + isNullable: isNullable, + isBlittable: isBlittable, isSmartEnum: isSmartEnum ) { Parents = [ @@ -182,17 +207,26 @@ public static TypeInfo ReturnTypeForEnum (string enumName, bool isSmartEnum = fa "System.IFormattable", "System.ISpanFormattable" ], - EnumUnderlyingType = SpecialType.System_Int32, + IsNativeEnum = isNativeEnum, + EnumUnderlyingType = underlyingType, }; - public static TypeInfo ReturnTypeForArray (string type, bool isNullable = false, bool isBlittable = false) + public static TypeInfo ReturnTypeForArray (string type, + bool isNullable = false, + bool isBlittable = false, + bool isEnum = false, + bool isSmartEnum = false, + bool isStruct = false) => new ( name: type, isNullable: isNullable, isBlittable: isBlittable, isArray: true, - isReferenceType: true + isReferenceType: true, + isSmartEnum: isSmartEnum, + isStruct: isStruct ) { + EnumUnderlyingType = isEnum ? SpecialType.System_Int32 : null, Parents = ["System.Array", "object"], Interfaces = [ $"System.Collections.Generic.IList<{type}>", @@ -205,4 +239,135 @@ public static TypeInfo ReturnTypeForArray (string type, bool isNullable = false, "System.ICloneable" ] }; + + public static TypeInfo ReturnTypeForAction () + => new ( + name: "System.Action", + isNullable: false, + isBlittable: false, + isArray: false, + isReferenceType: true + ) { + Parents = [ + "System.MulticastDelegate", + "System.Delegate", + "object" + ], + Interfaces = [ + "System.ICloneable", + "System.Runtime.Serialization.ISerializable", + ] + }; + + public static TypeInfo ReturnTypeForAction (params string [] parameters) + => new ( + name: $"System.Action<{string.Join (", ", parameters)}>", + isNullable: false, + isBlittable: false, + isArray: false, + isReferenceType: true + ) { + Parents = [ + "System.MulticastDelegate", + "System.Delegate", + "object" + ], + Interfaces = [ + "System.ICloneable", + "System.Runtime.Serialization.ISerializable", + ] + }; + + public static TypeInfo ReturnTypeForFunc (params string [] parameters) + => new ( + name: $"System.Func<{string.Join (", ", parameters)}>", + isNullable: false, + isBlittable: false, + isArray: false, + isReferenceType: true + ) { + Parents = [ + "System.MulticastDelegate", + "System.Delegate", + "object" + ], + Interfaces = [ + "System.ICloneable", + "System.Runtime.Serialization.ISerializable", + ] + }; + + public static TypeInfo ReturnTypeForDelegate (string delegateName) + => new ( + name: delegateName, + isNullable: false, + isBlittable: false, + isArray: false, + isReferenceType: true + ) { + Parents = [ + "System.MulticastDelegate", + "System.Delegate", + "object" + ], + Interfaces = [ + "System.ICloneable", + "System.Runtime.Serialization.ISerializable", + ] + }; + + public static TypeInfo ReturnTypeForNSObject (string? nsObjectName = null, bool isNullable = false, bool isApiDefinition = false) + => new ( + name: nsObjectName ?? "Foundation.NSObject", + isNullable: isNullable, + isArray: false, + isReferenceType: true + ) { + IsNSObject = true, + IsINativeObject = true, + Parents = nsObjectName is null ? ["object"] : ["Foundation.NSObject", "object"], + Interfaces = isApiDefinition + ? [ + "ObjCRuntime.INativeObject", + "Foundation.INSObjectFactory", + ] + : [ + "ObjCRuntime.INativeObject", + $"System.IEquatable<{nsObjectName ?? "Foundation.NSObject"}>", + "System.IDisposable", + "Foundation.INSObjectFactory", + "Foundation.INSObjectProtocol" + ] + }; + + public static TypeInfo ReturnTypeForINativeObject (string nativeObjectName, bool isNullable = false) + => new ( + name: nativeObjectName, + isNullable: isNullable, + isArray: false + ) { + IsNSObject = true, + IsINativeObject = true, + Parents = ["object"], + Interfaces = ["ObjCRuntime.INativeObject"] + }; + + public static TypeInfo ReturnTypeForNSString (bool isNullable = false) + => new ( + name: "Foundation.NSString", + isNullable: isNullable, + isArray: false, isReferenceType: true) { + IsNSObject = true, + IsINativeObject = true, + Parents = [ + "Foundation.NSObject", + "object" + ], + Interfaces = [ + "Foundation.INSCopying", + "Foundation.INSSecureCoding", + "ObjCRuntime.INativeObject", + "Foundation.INSObjectFactory" + ] + }; } diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AsyncDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AsyncDataTests.cs new file mode 100644 index 000000000000..f2b27f9c0b37 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AsyncDataTests.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class AsyncDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string path = "/some/random/path.cs"; + + const string simpleAsyncMethod = @" +using System; +using AppKit; +using Foundation; +using ObjCRuntime; + +namespace Test; + +[NoMacCatalyst] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface NSTableViewDiffableDataSource { + + [Export (""applySnapshot:animatingDifferences:completion:"")] + [Async] + void ApplySnapshot (NSObject snapshot, bool animatingDifferences, [NullAllowed] Action completion); +} +"; + yield return [(Source: simpleAsyncMethod, Path: path), new AsyncData ()]; + + const string asyncResultTypeName = @" +using System; +using AppKit; +using Foundation; +using ObjCRuntime; + +namespace Test; + +[NoMacCatalyst] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface NSTableViewDiffableDataSource { + + [Export (""applySnapshot:animatingDifferences:completion:"")] + [Async (ResultTypeName=""NSSpellCheckerCandidates"")] + void ApplySnapshot (NSObject snapshot, bool animatingDifferences, [NullAllowed] Action completion); +} +"; + + yield return [(Source: asyncResultTypeName, Path: path), + new AsyncData { + ResultTypeName = "NSSpellCheckerCandidates" + }]; + + const string asyncMethodName = @" +using System; +using AppKit; +using Foundation; +using ObjCRuntime; + +namespace Test; + +[NoMacCatalyst] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface NSTableViewDiffableDataSource { + + [Export (""applySnapshot:animatingDifferences:completion:"")] + [Async (""ApplyTheSnapshotAsync"")] + void ApplySnapshot (NSObject snapshot, bool animatingDifferences, [NullAllowed] Action completion); +} +"; + + yield return [(Source: asyncMethodName, Path: path), + new AsyncData { + MethodName = "ApplyTheSnapshotAsync" + }]; + + const string asyncTypeOf = @" +using System; +using AppKit; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public class SampleResult {} + +[NoMacCatalyst] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface NSTableViewDiffableDataSource { + + [Export (""applySnapshot:animatingDifferences:completion:"")] + [Async (ResultType = typeof (SampleResult))] + void ApplySnapshot (NSObject snapshot, bool animatingDifferences, [NullAllowed] Action completion); +} +"; + + yield return [(Source: asyncTypeOf, Path: path), + new AsyncData { + ResultType = "Test.SampleResult" + }]; + + const string postResult = @" +using System; +using AppKit; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public class SampleResult {} + +[NoMacCatalyst] +[BaseType (typeof (NSObject))] +[DisableDefaultCtor] +interface NSTableViewDiffableDataSource { + + [Export (""applySnapshot:animatingDifferences:completion:"")] + [Async (ResultTypeName = ""NSUrlSessionDataTaskRequest"", PostNonResultSnippet = ""result.Resume ();"")] + void ApplySnapshot (NSObject snapshot, bool animatingDifferences, [NullAllowed] Action completion); +} +"; + + yield return [(Source: postResult, Path: path), + new AsyncData { + ResultTypeName = "NSUrlSessionDataTaskRequest", + PostNonResultSnippet = "result.Resume ();" + }]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, AsyncData expectedData) + => AssertTryCreate (platform, source, AttributesNames.AsyncAttribute, + expectedData, AsyncData.TryParse); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AttributeParsingTestClass.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AttributeParsingTestClass.cs new file mode 100644 index 000000000000..b28fdda704a4 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AttributeParsingTestClass.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class AttributeParsingTestClass : BaseTransformerTestClass { + + internal void AssertTryCreate (ApplePlatform platform, (string Source, string Path) source, + string attributeName, T expectedData, TryParseDelegate tryParse, bool lastOrDefault = false) + where T : struct + where TR : MemberDeclarationSyntax + { + // create a compilation used to create the transformer + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + TR? declaration = null; + if (lastOrDefault) { + declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + } else { + declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + } + + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + var attribute = symbol.GetAttribute (attributeName, tryParse); + Assert.NotNull (attribute); + Assert.Equal (expectedData, attribute.Value); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AvailabilityTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AvailabilityTests.cs new file mode 100644 index 000000000000..ec7d680fc4fd --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/AvailabilityTests.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.Extensions; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class AvailabilityTests : BaseTransformerTestClass { + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string path = "/some/random/path.cs"; + var builder = SymbolAvailability.CreateBuilder (); + + const string allPlatformsIncluded = @" +using System; +using ObjCRuntime; +using Foundation; + +namespace Test; + +[DisableDefaultCtor] +[Abstract] // abstract class that should not be used directly +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + builder.Add (new SupportedOSPlatformData ("ios")); + builder.Add (new SupportedOSPlatformData ("tvos")); + builder.Add (new SupportedOSPlatformData ("macos")); + builder.Add (new SupportedOSPlatformData ("maccatalyst")); + yield return [(Source: allPlatformsIncluded, Path: path), builder.ToImmutable ()]; + + builder.Clear (); + const string singlePlatformRemoved = @" +using System; +using ObjCRuntime; +using Foundation; + +namespace Test; + +[NoTV] +[DisableDefaultCtor] +[Abstract] // abstract class that should not be used directly +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + + builder.Add (new SupportedOSPlatformData ("ios")); + builder.Add (new UnsupportedOSPlatformData ("tvos")); + builder.Add (new SupportedOSPlatformData ("macos")); + builder.Add (new SupportedOSPlatformData ("maccatalyst")); + yield return [(Source: singlePlatformRemoved, Path: path), builder.ToImmutable ()]; + + + builder.Clear (); + const string onePlatformSpecificVersion = @" +using System; +using ObjCRuntime; +using Foundation; + +namespace Test; + +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] // abstract class that should not be used directly +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + + builder.Add (new SupportedOSPlatformData ("ios")); + builder.Add (new SupportedOSPlatformData ("tvos")); + builder.Add (new SupportedOSPlatformData ("macos")); + builder.Add (new SupportedOSPlatformData ("maccatalyst13.1")); + yield return [(Source: onePlatformSpecificVersion, Path: path), builder.ToImmutable ()]; + + builder.Clear (); + const string allPlatformsRemovedButOne = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV, NoMacCatalyst, NoiOS] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + + builder.Add (new UnsupportedOSPlatformData ("ios")); + builder.Add (new UnsupportedOSPlatformData ("tvos")); + builder.Add (new SupportedOSPlatformData ("macos")); + builder.Add (new UnsupportedOSPlatformData ("maccatalyst")); + yield return [(Source: allPlatformsRemovedButOne, Path: path), builder.ToImmutable ()]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, SymbolAvailability expectedData) + { + var compilation = CreateCompilation (platform, sources: source); + var x = compilation.GetDiagnostics (); + var syntaxTree = compilation.SyntaxTrees.FirstOrDefault (t => t.FilePath == source.Path); + Assert.NotNull (syntaxTree); + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + + // the transformation does not care about the parents, we want the exact same as was added by + // the developer. + var availability = symbol.GetAvailabilityForSymbol (); + Assert.Equal (expectedData, availability); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BackingFieldTypeDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BackingFieldTypeDataTests.cs new file mode 100644 index 000000000000..fe4284847468 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BackingFieldTypeDataTests.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class BackingFieldTypeDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + const string nsnumberBackingFieldType = @" +using System; +using Foundation; +using ObjCRuntime; + +[NoTV, Mac (15, 0), NoiOS, NoMacCatalyst] +[BackingFieldType (typeof (NSNumber))] +public enum ASAuthorizationProviderExtensionEncryptionAlgorithm { + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmECDHE_A256GCM"")] + EcdheA256Gcm, + + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmHPKE_P256_SHA256_AES_GCM_256"")] + HpkeP256Sha256AesGcm256, + + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmHPKE_P384_SHA384_AES_GCM_256"")] + HpkeP384Sha384AesGcm256, + + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmHPKE_Curve25519_SHA256_ChachaPoly"")] + HpkeCurve25519Sha256ChachaPoly, +} +"; + yield return [(Source: nsnumberBackingFieldType, Path: path), new BackingFieldTypeData ("Foundation.NSNumber")]; + + const string nsstringBackingFieldType = @" +using System; +using Foundation; +using ObjCRuntime; + +[NoTV, Mac (15, 0), NoiOS, NoMacCatalyst] +[BackingFieldType (typeof (NSString))] +public enum ASAuthorizationProviderExtensionEncryptionAlgorithm { + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmECDHE_A256GCM"")] + EcdheA256Gcm, + + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmHPKE_P256_SHA256_AES_GCM_256"")] + HpkeP256Sha256AesGcm256, + + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmHPKE_P384_SHA384_AES_GCM_256"")] + HpkeP384Sha384AesGcm256, + + [Field (""ASAuthorizationProviderExtensionEncryptionAlgorithmHPKE_Curve25519_SHA256_ChachaPoly"")] + HpkeCurve25519Sha256ChachaPoly, +} +"; + yield return [(Source: nsstringBackingFieldType, Path: path), new BackingFieldTypeData ("Foundation.NSString")]; + + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, BackingFieldTypeData expectedData) + => AssertTryCreate (platform, source, AttributesNames.BackingFieldTypeAttribute, + expectedData, BackingFieldTypeData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BaseTypeDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BaseTypeDataTests.cs new file mode 100644 index 000000000000..7b8480bdd945 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BaseTypeDataTests.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class BaseTypeDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + + const string simpleBaseType = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + yield return [(Source: simpleBaseType, Path: path), new BaseTypeData ("Foundation.NSObject")]; + + const string baseTypeWithName = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject), Name =""MyObjcName"")] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + yield return [ + (Source: baseTypeWithName, Path: path), + new BaseTypeData ("Foundation.NSObject") { + Name = "MyObjcName", + }]; + + const string baseTypeWithEvents = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoiOS] +[NoMacCatalyst] +[BaseType (typeof (NSObject))] +[Model] +[Protocol] +interface NSAnimationDelegate {} + +[BaseType (typeof (NSObject), Delegates = new string [] { ""WeakDelegate"" }, Events = new Type [] { typeof (NSAnimationDelegate) })] +interface NSAnimation : NSCoding, NSCopying { + [Export (""startAnimation"")] + void StartAnimation (); +} +"; + yield return [ + (Source: baseTypeWithEvents, Path: path), + new BaseTypeData ("Foundation.NSObject") { + Delegates = ["WeakDelegate"], + Events = ["Test.NSAnimationDelegate"] + } + ]; + + const string singleton = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject), Singleton = true)] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + yield return [ + (Source: singleton, Path: path), + new BaseTypeData ("Foundation.NSObject") { + Singleton = true + }]; + + const string keepRefUntil = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[BaseType (typeof (NSObject), KeepRefUntil = ""Dismissed"")] +[Deprecated (PlatformName.iOS, 8, 3, message: ""Use 'UIAlertController' with 'UIAlertControllerStyle.ActionSheet' instead."")] +[MacCatalyst (13, 1)] +[Deprecated (PlatformName.MacCatalyst, 13, 1, message: ""Use 'UIAlertController' with 'UIAlertControllerStyle.ActionSheet' instead."")] +interface UIActionSheet { +} +"; + yield return [ + (Source: keepRefUntil, Path: path), + new BaseTypeData ("Foundation.NSObject") { + KeepRefUntil = "Dismissed", + }]; + + const string isStubClass = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject), IsStubClass = true)] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + yield return [ + (Source: isStubClass, Path: path), + new BaseTypeData ("Foundation.NSObject") { + IsStubClass = true + }]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, BaseTypeData expectedData) + => AssertTryCreate (platform, source, AttributesNames.BaseTypeAttribute, + expectedData, BaseTypeData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindAsDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindAsDataTests.cs new file mode 100644 index 000000000000..2a0bf1f0c234 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindAsDataTests.cs @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class BindAsDataTests : BaseTransformerTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + + const string bindAsProperty = @" +using System; +using Foundation; +using ObjCRuntime; +using CoreMedia; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator { + [BindAs (typeof (CMVideoDimensions []))] + [Export (""supportedMaxPhotoDimensions"")] + NSValue [] SupportedMaxPhotoDimensions { get; } +} +"; + + yield return [ + PropertyDeclaration (IdentifierName ("string"), Identifier ("Hello")), + (Source: bindAsProperty, Path: path), + new BindAsData ("CoreMedia.CMVideoDimensions[]")]; + + + const string bindAsReturnMethod = @" +using System; +using Foundation; +using ObjCRuntime; +using CoreMedia; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator { + [return: BindAs (typeof (NSLinguisticTag []))] + [Export (""linguisticTagsInRange:scheme:options:orthography:tokenRanges:"")] + NSString [] GetLinguisticTags (NSRange range, NSString scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue [] tokenRanges); +} +"; + + yield return [ + MethodDeclaration (PredefinedType (Token (SyntaxKind.StringKeyword)), Identifier ("Hello")), + (Source: bindAsReturnMethod, Path: path), + new BindAsData ("Foundation.NSLinguisticTag[]")]; + + + const string parameterBindAs = @" +using System; +using Foundation; +using ObjCRuntime; +using CoreMedia; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator { + [Export (""linguisticTagsInRange:scheme:options:orthography:tokenRanges:"")] + NSString [] GetLinguisticTags ([BindAs (typeof (ushort?))] NSString scheme); +} +"; + var parameter = Parameter (Identifier ("variable")) + .WithType (PredefinedType (Token (SyntaxKind.StringKeyword))); + yield return [ + parameter, + (Source: parameterBindAs, Path: path), + new BindAsData ("ushort?")]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, T _, (string Source, string Path) source, BindAsData expectedData) + where T : CSharpSyntaxNode + { + // create a compilation used to create the transformer + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + var attribute = symbol.GetAttribute (AttributesNames.BindAsAttribute, BindAsData.TryParse); + Assert.NotNull (attribute); + Assert.Equal (expectedData, attribute.Value); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindDataTests.cs new file mode 100644 index 000000000000..10d0b49d301a --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/BindDataTests.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class BindDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + var simpleBind = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Bind (""someSelector"")] + void Prepare (); +} +"; + + yield return [(Sorunce: simpleBind, Path: path), new BindData ("someSelector")]; + + var virtualBind = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Bind (""someSelector"", Virtual = true)] + void Prepare (); +} +"; + + yield return [(Sorunce: virtualBind, Path: path), new BindData ("someSelector", true)]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, + BindData expectedData) + => AssertTryCreate (platform, source, AttributesNames.BindAttribute, + expectedData, BindData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterDataTests.cs new file mode 100644 index 000000000000..26db124492f7 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterDataTests.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; +using MethodAttributes = Mono.Cecil.MethodAttributes; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class CoreImageFilterDataTests : AttributeParsingTestClass { + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string path = "/some/random/path.cs"; + + const string simpleCoreImageFilter = @" +using System; +using CoreImage; +using Foundation; +using ObjCRuntime; + +namespace NS; + +[CoreImageFilter] +[BaseType (typeof (CIFilter))] +interface CIAccordionFoldTransition : CIAccordionFoldTransitionProtocol { + [CoreImageFilterProperty (""inputNumberOfFolds"")] + int NumberOfFolds { get; set; } +} +"; + + yield return [(Source: simpleCoreImageFilter, Path: path), new CoreImageFilterData () { }]; + + const string coreImageFilterWithProperties = @" +using CoreImage; +using Foundation; +using ObjCRuntime; +using Mono.Cecil; + +namespace NS; + +[CoreImageFilter (IntPtrCtorVisibility = MethodAttributes.Family)] // was already protected in classic +[BaseType (typeof (CIFilter))] +interface CICompositingFilter : CIAccordionFoldTransitionProtocol { + + [CoreImageFilterProperty (""inputImage"")] + CIImage InputImage { get; set; } + + [CoreImageFilterProperty (""inputBackgroundImage"")] + CIImage BackgroundImage { get; set; } +} +"; + + yield return [(Source: coreImageFilterWithProperties, Path: path), new CoreImageFilterData () { IntPtrCtorVisibility = MethodAttributes.Family }]; + + const string allProperties = @" +using CoreImage; +using Foundation; +using ObjCRuntime; +using Mono.Cecil; + +namespace NS; + +[CoreImageFilter (DefaultCtorVisibility = MethodAttributes.Private, IntPtrCtorVisibility = MethodAttributes.Family, StringCtorVisibility = MethodAttributes.Family)] // was already protected in classic +[BaseType (typeof (CIFilter))] +interface CICompositingFilter : CIAccordionFoldTransitionProtocol { + + [CoreImageFilterProperty (""inputImage"")] + CIImage InputImage { get; set; } + + [CoreImageFilterProperty (""inputBackgroundImage"")] + CIImage BackgroundImage { get; set; } +} +"; + + yield return [(Source: allProperties, Path: path), + new CoreImageFilterData () { + IntPtrCtorVisibility = MethodAttributes.Family, + DefaultCtorVisibility = MethodAttributes.Private, + StringCtorVisibility = MethodAttributes.Family, + }]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, CoreImageFilterData expectedData) + => AssertTryCreate (platform, source, AttributesNames.CoreImageFilterAttribute, + expectedData, CoreImageFilterData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterPropertyTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterPropertyTests.cs new file mode 100644 index 000000000000..dc4b37f0238b --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/CoreImageFilterPropertyTests.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class CoreImageFilterPropertyTests : AttributeParsingTestClass { + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string path = "/some/random/path.cs"; + + const string coreImageFilterWithProperties = @" +using CoreImage; +using Foundation; +using ObjCRuntime; +using Mono.Cecil; + +namespace NS; + +[CoreImageFilter (IntPtrCtorVisibility = MethodAttributes.Family)] // was already protected in classic +[BaseType (typeof (CIFilter))] +interface CICompositingFilter : CIAccordionFoldTransitionProtocol { + + [CoreImageFilterProperty (""inputBackgroundImage"")] + CIImage BackgroundImage { get; set; } +} +"; + yield return [ + (Source: coreImageFilterWithProperties, Path: path), + new CoreImageFilterPropertyData ("inputBackgroundImage") + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, + CoreImageFilterPropertyData expectedData) + => AssertTryCreate (platform, source, AttributesNames.CoreImageFilterPropertyAttribute, + expectedData, CoreImageFilterPropertyData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ErrorDomainDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ErrorDomainDataTests.cs new file mode 100644 index 000000000000..3a1ef8433ba0 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ErrorDomainDataTests.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class ErrorDomainDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + const string simpleErrorDomain = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace NS; + +[Native] +[ErrorDomain (""AVKitErrorDomain"")] +public enum AVKitError : long { + None = 0, + Unknown = -1000, + PictureInPictureStartFailed = -1001, + ContentRatingUnknown = -1100, + ContentDisallowedByPasscode = -1101, + ContentDisallowedByProfile = -1102, + RecordingFailed = -1200, +} +"; + yield return [(Sorunce: simpleErrorDomain, Path: path), new ErrorDomainData ("AVKitErrorDomain")]; + + const string errorWithLibDomain = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace NS; + +[Native] +[ErrorDomain (""AVKitErrorDomain"", LibraryName = ""AVKit"")] +public enum AVKitError : long { + None = 0, + Unknown = -1000, + PictureInPictureStartFailed = -1001, + ContentRatingUnknown = -1100, + ContentDisallowedByPasscode = -1101, + ContentDisallowedByProfile = -1102, + RecordingFailed = -1200, +} +"; + yield return [(Sorunce: errorWithLibDomain, Path: path), new ErrorDomainData ("AVKitErrorDomain", "AVKit")]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, + ErrorDomainData expectedData) + => AssertTryCreate (platform, source, AttributesNames.ErrorDomainAttribute, + expectedData, ErrorDomainData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ExportDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ExportDataTests.cs new file mode 100644 index 000000000000..620432fd448c --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ExportDataTests.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using ObjCRuntime; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class ExportDataTests : AttributeParsingTestClass { + + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string selectorOnly = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"")] + void Prepare (); +} +"; + yield return [(Source: selectorOnly, Path: "/some/random/path.cs"), new ExportData (selector: "prepare")]; + + const string selectorWithArgumentSemantic = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare"", ArgumentSemantic.Retain)] + void Prepare (); +} +"; + yield return [(Source: selectorWithArgumentSemantic, Path: "/some/random/path.cs"), new ExportData (selector: "prepare", argumentSemantic: ArgumentSemantic.Retain)]; + + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, ExportData expectedData) + => AssertTryCreate (platform, source, AttributesNames.ExportAttribute, + expectedData, ExportData.TryParse, lastOrDefault: false); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/FieldDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/FieldDataTests.cs new file mode 100644 index 000000000000..16a31f98884c --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/FieldDataTests.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class FieldDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string symbolOnly = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Field (""prepare"")] + void Prepare { get; } +} +"; + yield return [(Source: symbolOnly, Path: "/some/random/path.cs"), new FieldData ("prepare")]; + + const string symbolAndLibrary = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Field (""prepare"", ""LibraryName"")] + void Prepare { get; } +} +"; + yield return [(Source: symbolAndLibrary, Path: "/some/random/path.cs"), new FieldData ("prepare", "LibraryName")]; + + const string symbolAndLibraryNamed = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Field (""prepare"", LibraryName = ""LibraryName"")] + void Prepare { get; } +} +"; + yield return [(Source: symbolAndLibraryNamed, Path: "/some/random/path.cs"), new FieldData ("prepare", "LibraryName")]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, FieldData expectedData) + => AssertTryCreate (platform, source, AttributesNames.FieldAttribute, + expectedData, FieldData.TryParse, lastOrDefault: false); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NativeDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NativeDataTests.cs new file mode 100644 index 000000000000..96a4e438527e --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NativeDataTests.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class NativeDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + var simnpleNativeEnum = @" +using System; +using Foundation; +using ObjCRuntime; + +[Native] +public enum AVAudioQuality : long { + Min = 0, + Low = 0x20, + Medium = 0x40, + High = 0x60, + Max = 0x7F, +} +"; + + yield return [(Sorunce: simnpleNativeEnum, Path: path), new NativeData ()]; + + var nativeEnumWithName = @" +using System; +using Foundation; +using ObjCRuntime; + +[Native (""Test"")] +public enum AVAudioQuality : long { + Min = 0, + Low = 0x20, + Medium = 0x40, + High = 0x60, + Max = 0x7F, +} +"; + + yield return [(Sorunce: nativeEnumWithName, Path: path), new NativeData ("Test")]; + + var nativeEnumWithNameNamed = @" +using System; +using Foundation; +using ObjCRuntime; + +[Native (NativeName = ""Test"")] +public enum AVAudioQuality : long { + Min = 0, + Low = 0x20, + Medium = 0x40, + High = 0x60, + Max = 0x7F, +} +"; + + yield return [(Sorunce: nativeEnumWithNameNamed, Path: path), new NativeData ("Test")]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, + NativeData expectedData) + => AssertTryCreate (platform, source, AttributesNames.NativeAttribute, + expectedData, NativeData.TryParse, lastOrDefault: true); + +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NotificationDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NotificationDataTests.cs new file mode 100644 index 000000000000..fa4ef7f6ad81 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/NotificationDataTests.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class NotificationDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string path = "/some/random/path.cs"; + + // simple notification + const string simpleNotification = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoMacCatalyst] +[BaseType (typeof (NSView))] +partial interface NSSplitView { + [Notification] + [Field (""NSSplitViewWillResizeSubviewsNotification"")] + NSString NSSplitViewWillResizeSubviewsNotification { get; } +} +"; + yield return [(Source: simpleNotification, Path: path), new NotificationData (null, null)]; + + // notification type + const string notificationWithType = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +class MyNotification {} + +[NoMacCatalyst] +[BaseType (typeof (NSView))] +partial interface NSSplitView { + [Notification (typeof (MyNotification))] + [Field (""NSSplitViewWillResizeSubviewsNotification"")] + NSString NSSplitViewWillResizeSubviewsNotification { get; } +} +"; + + yield return [(Source: notificationWithType, Path: path), new NotificationData ("Test.MyNotification", null)]; + + // notification center + const string notificationWithCenter = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +class MyNotification {} + +[NoMacCatalyst] +[BaseType (typeof (NSView))] +partial interface NSSplitView { + [Notification (""SharedWorkspace.NotificationCenter"")] + [Field (""NSSplitViewWillResizeSubviewsNotification"")] + NSString NSSplitViewWillResizeSubviewsNotification { get; } +} +"; + yield return [(Source: notificationWithCenter, Path: path), new NotificationData (null, "SharedWorkspace.NotificationCenter")]; + + // both + const string notificationWithBoth = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +class MyNotification {} + +[NoMacCatalyst] +[BaseType (typeof (NSView))] +partial interface NSSplitView { + [Notification (typeof (MyNotification), ""SharedWorkspace.NotificationCenter"")] + [Field (""NSSplitViewWillResizeSubviewsNotification"")] + NSString NSSplitViewWillResizeSubviewsNotification { get; } +} +"; + yield return [(Source: notificationWithBoth, Path: path), new NotificationData ("Test.MyNotification", "SharedWorkspace.NotificationCenter")]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, + NotificationData expectedData) + => AssertTryCreate (platform, source, AttributesNames.NotificationAttribute, + expectedData, NotificationData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/SnippetDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/SnippetDataTests.cs new file mode 100644 index 000000000000..156898bd07e6 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/SnippetDataTests.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class SnippetDataTests : AttributeParsingTestClass { + class TestDataTryCreate : IEnumerable { + + public IEnumerator GetEnumerator () + { + const string path = "/some/random/path.cs"; + + const string disposeAttribute = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[BaseType (typeof (NSControl))] +[Dispose (""dispatcher = null;"", Optimizable = true)] +interface NSButton { } +"; + + yield return [(Source: disposeAttribute, Path: path), new SnippetData ("dispatcher = null;", true)]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, SnippetData expectedData) + => AssertTryCreate (platform, source, AttributesNames.DisposeAttribute, + expectedData, SnippetData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/StrongDictionaryDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/StrongDictionaryDataTests.cs new file mode 100644 index 000000000000..2428c0efb325 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/StrongDictionaryDataTests.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class StrongDictionaryDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + const string path = "/some/random/path.cs"; + + const string strongDictionary = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[StrongDictionary (""AVCapturePhotoSettingsThumbnailFormatKeys"")] +interface AVCapturePhotoSettingsThumbnailFormat { + NSString Codec { get; set; } + NSNumber Width { get; set; } + NSNumber Height { get; set; } +} +"; + + yield return [(Source: strongDictionary, Path: path), new StrongDictionaryData ("AVCapturePhotoSettingsThumbnailFormatKeys")]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, StrongDictionaryData expectedData) + => AssertTryCreate (platform, source, AttributesNames.StrongDictionaryAttribute, + expectedData, StrongDictionaryData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ThreadSafeDataTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ThreadSafeDataTests.cs new file mode 100644 index 000000000000..dd8310a2c9f7 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Attributes/ThreadSafeDataTests.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Attributes; + +public class ThreadSafeDataTests : AttributeParsingTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + + const string threadSageMethod = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare""), ThreadSafe] + void Prepare (); +} +"; + + yield return [(Source: threadSageMethod, Path: path), new ThreadSafeData ()]; + + const string notThreadSafeMethod = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [Export (""prepare""), ThreadSafe (false)] + void Prepare (); +} +"; + + yield return [(Source: notThreadSafeMethod, Path: path), new ThreadSafeData (false)]; + + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, ThreadSafeData expectedData) + => AssertTryCreate (platform, source, AttributesNames.ThreadSafeAttribute, + expectedData, ThreadSafeData.TryParse, lastOrDefault: true); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs new file mode 100644 index 000000000000..26cbb1c29421 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.Macios.Transformer.Extensions; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests; + +/// +/// Base class that allows to test the transformer. +/// +public class BaseTransformerTestClass { + + // list of the defines for each platform, this is passed to the parser to ensure that + // we are testing the platforms as if they were being compiled. + readonly Dictionary platformDefines = new () { + { ApplePlatform.iOS, new [] { "__IOS__" } }, + { ApplePlatform.TVOS, new [] { "__TVOS__" } }, + { ApplePlatform.MacOSX, new [] { "__MACOS__" } }, + { ApplePlatform.MacCatalyst, new [] { "__MACCATALYST__" } }, + }; + + protected Compilation CreateCompilation (ApplePlatform platform, [CallerMemberName] string name = "", params (string Source, string Path) [] sources) + { + // get the dll for the current platform, this is needed because that way we will get the attributes that + // are used in the old dlls that are needed to test the transformer. + var targetFramework = TargetFramework.GetTargetFramework (platform, isDotNet: true); + var workingDirectory = Path.Combine (Configuration.SourceRoot, "src"); + if (!Configuration.TryGetApiDefinitionRsp (targetFramework, out var rspFile)) { + Assert.Fail ($"Could not find rsp file for {targetFramework}"); + } + + var parseResult = CSharpCommandLineParser.Default.ParseRsp ( + rspFile, workingDirectory, Configuration.DotNetBclDir); + + // add NET to the preprocessor directives + var preprocessorDirectives = parseResult.ParseOptions.PreprocessorSymbolNames.ToList (); + preprocessorDirectives.Add ("NET"); + + // fixing the parsing options, we must have an issue in the rsp + var updatedParseOptions = parseResult.ParseOptions + .WithLanguageVersion (LanguageVersion.Latest) + .WithPreprocessorSymbols (preprocessorDirectives) + .WithDocumentationMode (DocumentationMode.None); + + var references = parseResult.GetReferences (workingDirectory, Configuration.DotNetBclDir).ToList (); + // add the mono cecil assembly, which we are missing in the api compilation rsp + references.Add (MetadataReference.CreateFromFile (typeof (Mono.Cecil.Cil.OpCode).Assembly.Location)); + var parsedSource = parseResult.GetSourceFiles (updatedParseOptions).ToList (); + foreach (var (source, path) in sources) { + parsedSource.Add (CSharpSyntaxTree.ParseText (source, updatedParseOptions, path)); + } + + return CSharpCompilation.Create ( + assemblyName: name, + syntaxTrees: parsedSource, + references: references, + options: parseResult.CompilationOptions); + } + +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/MethodTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/MethodTests.cs new file mode 100644 index 000000000000..cb83b8919bb7 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/MethodTests.cs @@ -0,0 +1,495 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using Token = System.CommandLine.Parsing.Token; + +namespace Microsoft.Macios.Transformer.Tests.DataModel; + +public class MethodTests : BaseTransformerTestClass { + + [Theory] + [InlineData ("Hello", false)] + [InlineData ("Constructor", true)] + public void IsConstructorTests (string methodName, bool expectedResult) + { + var method = new Method ( + type: "TestClass", + name: methodName, + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + attributes: new (), + parameters: []); + Assert.Equal (expectedResult, method.IsConstructor); + } + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + var availabilityBuilder = SymbolAvailability.CreateBuilder (); + availabilityBuilder.Add (new SupportedOSPlatformData ("ios")); + availabilityBuilder.Add (new SupportedOSPlatformData ("tvos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("macos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("maccatalyst")); + + const string simpleMethod = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Export (""play"")] + public void Play (); +} +"; + yield return [ + (Source: simpleMethod, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: []) { + ExportMethodData = new ("play"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.VirtualKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + + const string abstractMethod = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Abstract, Export (""play"")] + public void Play (); +} +"; + + yield return [ + (Source: abstractMethod, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: []) { + ExportMethodData = new ("play"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.AbstractKeyword), + ] + } + ]; + + const string internalAbstractMethod = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Internal, Abstract, Export (""play"")] + public void Play (); +} +"; + + yield return [ + (Source: internalAbstractMethod, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: []) { + ExportMethodData = new ("play"), + Modifiers = [ + Token (SyntaxKind.InternalKeyword), + Token (SyntaxKind.AbstractKeyword), + ] + } + ]; + + const string newMethod = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [New, Export (""play"")] + public void Play (); +} +"; + yield return [ + (Source: newMethod, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: []) { + ExportMethodData = new ("play"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.NewKeyword), + Token (SyntaxKind.VirtualKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + + const string overrideMethod = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Override, Export (""play"")] + public void Play (); +} +"; + + yield return [ + (Source: overrideMethod, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: []) { + ExportMethodData = new ("play"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.OverrideKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + + const string intReturnMethod = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Export (""play"")] + public int Play (); +} +"; + + yield return [ + (Source: intReturnMethod, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForInt (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: []) { + ExportMethodData = new ("play"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.VirtualKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + + const string nullableIntReturnMethod = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Export (""play"")] + [return: NullAllowed] + public int Play (); +} +"; + + yield return [ + (Source: nullableIntReturnMethod, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForInt (isNullable: true, keepInterfaces: true), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: []) { + ExportMethodData = new ("play"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.VirtualKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + + const string stringParameter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Override, Export (""play:"")] + public void Play (string name); +} +"; + + yield return [ + (Source: stringParameter, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: [ + new (0, ReturnTypeForString (), "name"), + ]) { + ExportMethodData = new ("play:"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.OverrideKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + + const string nullableStringParameter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Override, Export (""play:"")] + public void Play ([NullAllowed] string name); +} +"; + + yield return [ + (Source: nullableStringParameter, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: [ + new (0, ReturnTypeForString (isNullable: true), "name") { + Attributes = [ + new ("NullAllowedAttribute"), + ] + }, + ]) { + ExportMethodData = new ("play:"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.OverrideKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + + const string severalParameter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Override, Export (""play:"")] + public void Play (string name, int age); +} +"; + + yield return [ + (Source: severalParameter, Path: path), + new Method ( + type: "AVPlayer", + name: "Play", + returnType: ReturnTypeForVoid (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + parameters: [ + new (0, ReturnTypeForString (), "name"), + new (1, ReturnTypeForInt (), "age"), + ]) { + ExportMethodData = new ("play:"), + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.OverrideKeyword), + Token (SyntaxKind.PartialKeyword), + ] + } + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, Method expectedData) + { + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + Assert.NotNull (declaration); + Assert.True (Method.TryCreate (declaration, semanticModel, out var method)); + Assert.Equal (expectedData, method); + } + + class TestDataToConstructor : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + new Method ( + type: "MyType", + name: "SomeMethodName", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + attributes: new (), + parameters: ImmutableArray.Empty), + null! + ]; + + yield return [ + new Method ( + type: "MyType", + name: "Constructor", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + attributes: new (), + parameters: ImmutableArray.Empty), + new Constructor ( + type: "MyType", + symbolAvailability: new (), + attributes: [], + modifiers: [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.PartialKeyword)], + parameters: []) + ]; + + yield return [ + new Method ( + type: "MyType", + name: "Constructor", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + attributes: new (), + parameters: []) { + Modifiers = [ + Token (SyntaxKind.InternalKeyword), + Token (SyntaxKind.VirtualKeyword), + Token (SyntaxKind.PartialKeyword) + ] + }, + new Constructor ( + type: "MyType", + symbolAvailability: new (), + attributes: [], + modifiers: [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.PartialKeyword)], + parameters: []) + ]; + + yield return [ + new Method ( + type: "MyType", + name: "Constructor", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + attributes: new (), + parameters: []) { + Modifiers = [ + Token (SyntaxKind.ProtectedKeyword), + Token (SyntaxKind.VirtualKeyword), + Token (SyntaxKind.PartialKeyword) + ] + }, + new Constructor ( + type: "MyType", + symbolAvailability: new (), + attributes: [], + modifiers: [Token (SyntaxKind.ProtectedKeyword), Token (SyntaxKind.PartialKeyword)], + parameters: []) + ]; + + yield return [ + new Method ( + type: "MyType", + name: "Constructor", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + attributes: new (), + parameters: [ + new Parameter (0, ReturnTypeForString (), "name") + ]), + new Constructor ( + type: "MyType", + symbolAvailability: new (), + attributes: [], + modifiers: [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.PartialKeyword)], + parameters: [ + new Parameter (0, ReturnTypeForString (), "name") + ]) + ]; + + yield return [ + new Method ( + type: "MyType", + name: "Constructor", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + attributes: new (), + parameters: [ + new Parameter (0, ReturnTypeForString (), "name"), + new Parameter (1, ReturnTypeForString (isNullable: true), "surname") + ]), + new Constructor ( + type: "MyType", + symbolAvailability: new (), + attributes: [], + modifiers: [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.PartialKeyword)], + parameters: [ + new Parameter (0, ReturnTypeForString (), "name"), + new Parameter (1, ReturnTypeForString (isNullable: true), "surname") + ]) + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataToConstructor))] + void ToConstructorTests (Method method, Constructor? expectedConstructor) + => Assert.Equal (expectedConstructor, method.ToConstructor ()); + +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/ParameterTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/ParameterTests.cs new file mode 100644 index 000000000000..1e7e1afeb194 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/ParameterTests.cs @@ -0,0 +1,339 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; + +namespace Microsoft.Macios.Transformer.Tests.DataModel; + +public class ParameterTests : BaseTransformerTestClass { + + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + + const string simpleValueParameter = @" +using System; + +namespace Test; + +public class MyClass () { + + public void Hello (int value) { } +} +"; + + yield return [ + (Source: simpleValueParameter, Path: path), + new Parameter (0, ReturnTypeForInt (), "value") + ]; + + const string nullableValueParameter = @" +using System; +using ObjCRuntime; + +namespace Test; + +public class MyClass () { + + public void Hello ([NullAllowed] int value) { } +} +"; + + yield return [ + (Source: nullableValueParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForInt (isNullable: true, keepInterfaces: true), + name: "value") { + Attributes = [ + new (name: "NullAllowedAttribute"), + ] + } + ]; + + const string arrayValueParameter = @" +using System; +using ObjCRuntime; + +namespace Test; + +public class MyClass () { + + public void Hello (int[] value) { } +} +"; + yield return [ + (Source: arrayValueParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForArray ("int", isBlittable: true), + name: "value") + ]; + + const string nullableArrayValueParameter = @" +using System; +using ObjCRuntime; + +namespace Test; + +public class MyClass () { + + public void Hello ([NullAllowed] int[] value) { } +} +"; + yield return [ + (Source: nullableArrayValueParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForArray ("int", isBlittable: false, isNullable: true), + name: "value") { + Attributes = [ + new (name: "NullAllowedAttribute"), + ], + } + ]; + + const string referenceParameter = @" +using System; +using ObjCRuntime; + +namespace Test; + +public class MyClass () { + + public void Hello (string value) { } +} +"; + yield return [ + (Source: referenceParameter, Path: path), + new Parameter (0, ReturnTypeForString (), "value") + ]; + + const string nullableReferenceParameter = @" +using System; +using ObjCRuntime; + +namespace Test; + +public class MyClass () { + + public void Hello ([NullAllowed] string value) { } +} +"; + yield return [ + (Source: nullableReferenceParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForString (isNullable: true), + name: "value") { + Attributes = [ + new (name: "NullAllowedAttribute"), + ] + } + ]; + + const string nsobjectParameter = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public class MyClass () { + + public void Hello (NSObject value) { } +} +"; + + yield return [ + (Source: nsobjectParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForNSObject (isApiDefinition: true), + name: "value") + ]; + + + const string enumParameter = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public enum MyEnum { + One, + Two, + Three +} + +public class MyClass () { + + public void Hello (MyEnum value) { } +} +"; + yield return [ + (Source: enumParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForEnum ("Test.MyEnum", underlyingType: SpecialType.System_Int32), + name: "value") + ]; + + const string nullableEnumParameter = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public enum MyEnum { + One, + Two, + Three +} + +public class MyClass () { + public void Hello ([NullAllowed] MyEnum value) { } +} +"; + yield return [ + (Source: nullableEnumParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForEnum ("Test.MyEnum", isNullable: true, isBlittable: false, underlyingType: SpecialType.System_Int32), + name: "value") { + Attributes = [ + new (name: "NullAllowedAttribute"), + ] + } + ]; + + const string nativeEnumParameter = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace Test; + +[Native] +public enum MyEnum { + One, + Two, + Three +} + +public class MyClass () { + public void Hello (MyEnum value) { } +} +"; + yield return [ + (Source: nativeEnumParameter, Path: path), + new Parameter ( + position: 0, + type: ReturnTypeForEnum ("Test.MyEnum", isNativeEnum: true, underlyingType: SpecialType.System_Int32), + name: "value") + ]; + + const string blittableStructParam = @" +using System; +using System.Runtime.InteropServices; +using Foundation; +using ObjCRuntime; + +namespace Test; + +[StructLayout(LayoutKind.Sequential)] +public struct MyEnum { + public int First { get; } + public int Second { get; } +} + +public class MyClass () { + public void Hello (MyEnum value) { } +} +"; + yield return [ + (Source: blittableStructParam, Path: path), + new Parameter (0, ReturnTypeForStruct ("Test.MyEnum", isBlittable: true), "value") + ]; + + + const string nonBlittableStructParam = @" +using System; +using System.Runtime.InteropServices; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public struct MyEnum { + public int First { get; } + public int Second { get; } +} + +public class MyClass () { + public void Hello (MyEnum value) { } +} +"; + yield return [ + (Source: nonBlittableStructParam, Path: path), + new Parameter (0, ReturnTypeForStruct ("Test.MyEnum"), "value") + ]; + + const string interfaceParameter = @" +using System; +using System.Runtime.InteropServices; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public interface IMyInterface { } + +public class MyClass () { + public void Hello (IMyInterface value) { } +} +"; + yield return [ + (Source: interfaceParameter, Path: path), + new Parameter (0, ReturnTypeForInterface ("Test.IMyInterface"), "value") + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, Parameter expectedData) + { + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + Assert.True (Parameter.TryCreate (symbol, declaration, semanticModel, out var parameter)); + Assert.Equal (expectedData, parameter); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/PropertyTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/PropertyTests.cs new file mode 100644 index 000000000000..3ae1ec3ce27a --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/PropertyTests.cs @@ -0,0 +1,319 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Transformer.Attributes; +using Xamarin.Tests; +using Xamarin.Utils; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Transformer.Tests.DataModel; + +public class PropertyTests : BaseTransformerTestClass { + + class TestDataTryCreateProperties : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + var availabilityBuilder = SymbolAvailability.CreateBuilder (); + availabilityBuilder.Add (new SupportedOSPlatformData ("ios")); + availabilityBuilder.Add (new SupportedOSPlatformData ("tvos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("macos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("maccatalyst")); + + const string simpleGetter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Export (""name"")] + string Name { get; } +} +"; + yield return [ + (Source: simpleGetter, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) + ]) { + ExportPropertyData = new ("name"), + } + ]; + + const string simpleGetterSetter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Export (""name"")] + string Name { get; set; } +} +"; + yield return [ + (Source: simpleGetterSetter, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()), + new Accessor ( + accessorKind: AccessorKind.Setter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) + ]) { + ExportPropertyData = new ("name"), + } + ]; + + const string staticSimpleGetterSetter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Static, Export (""name"")] + string Name { get; set; } +} +"; + yield return [ + (Source: staticSimpleGetterSetter, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()), + new Accessor ( + accessorKind: AccessorKind.Setter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) + ]) { + Modifiers = [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + ExportPropertyData = new ("name"), + } + ]; + + const string abstractSimpleGetterSetter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Abstract, Export (""name"")] + string Name { get; set; } +} +"; + yield return [ + (Source: abstractSimpleGetterSetter, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()), + new Accessor ( + accessorKind: AccessorKind.Setter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) + ]) { + Modifiers = [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.AbstractKeyword)], + ExportPropertyData = new ("name"), + } + ]; + + const string accessorsWithExport = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Export (""name"")] + string Name { + [Export (""getName"")] + get; + [Export (""setName"")] + set; + } +} +"; + yield return [ + (Source: accessorsWithExport, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForString (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) { + ExportPropertyData = new ("getName") + }, + new Accessor ( + accessorKind: AccessorKind.Setter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) { + ExportPropertyData = new ExportData ("setName") + } + ]) { + Modifiers = [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)], + ExportPropertyData = new ("name"), + } + ]; + + const string nullableSimpleGetterSetter = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [NullAllowed, Export (""name"")] + string Name { get; set; } +} +"; + yield return [ + (Source: nullableSimpleGetterSetter, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForString (isNullable: true), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()), + new Accessor ( + accessorKind: AccessorKind.Setter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) + ]) { + ExportPropertyData = new ("name"), + } + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + class TestDataTryCreateFields : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + var availabilityBuilder = SymbolAvailability.CreateBuilder (); + availabilityBuilder.Add (new SupportedOSPlatformData ("ios")); + availabilityBuilder.Add (new SupportedOSPlatformData ("tvos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("macos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("maccatalyst")); + + const string simpleField = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Field (""ConstantField"")] + NSString Name { get; } +} +"; + yield return [ + (Source: simpleField, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForNSString (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) + ]) { + Modifiers = [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + ExportFieldData = new ("ConstantField"), + } + ]; + + const string fieldWithLibrary = @" +using System; +using Foundation; +using ObjCRuntime; + +interface AVPlayer { + [Field (""ConstantField"", ""LibraryName"")] + NSString Name { get; } +} +"; + yield return [ + (Source: fieldWithLibrary, Path: path), + new Property ( + name: "Name", + returnType: ReturnTypeForNSString (), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new (), + accessors: [ + new Accessor ( + accessorKind: AccessorKind.Getter, + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) + ]) { + Modifiers = [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + ExportFieldData = new ("ConstantField", "LibraryName"), + } + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, Property expectedData) + { + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + Assert.NotNull (declaration); + Assert.True (Property.TryCreate (declaration, semanticModel, out var property)); + Assert.Equal (expectedData, property); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs new file mode 100644 index 000000000000..07396190bfc6 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Transformer.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Transformer.Tests.DataModel; + +public class SmartEnumTests : BaseTransformerTestClass { + + readonly BindingEqualityComparer comparer = new (); + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + var availabilityBuilder = SymbolAvailability.CreateBuilder (); + availabilityBuilder.Add (new SupportedOSPlatformData ("ios")); + availabilityBuilder.Add (new SupportedOSPlatformData ("tvos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("macos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("maccatalyst")); + + const string smartEnum = @" +using System; +using Foundation; +using ObjCRutime; + +namespace AVFoundation; + +public enum AVCaptureDeviceType { + + [Field (""AVCaptureDeviceTypeBuiltInMicrophone"")] + BuiltInMicrophone, + + [Field (""AVCaptureDeviceTypeBuiltInWideAngleCamera"")] + BuiltInWideAngleCamera, + + [Field (""AVCaptureDeviceTypeBuiltInTelephotoCamera"")] + BuiltInTelephotoCamera, +} +"; + + yield return [ + (Source: smartEnum, Path: path), + new Binding ( + symbolName: "AVCaptureDeviceType", + @namespace: ["AVFoundation"], + fullyQualifiedSymbol: "AVFoundation.AVCaptureDeviceType", + info: new BindingInfo (null, BindingType.SmartEnum), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) { + Base = "System.Enum", + Modifiers = [Token (SyntaxKind.PublicKeyword)], + EnumMembers = [ + new EnumMember ( + name: "BuiltInMicrophone", + libraryName: "AVFoundation", + libraryPath: null, + fieldData: new ("AVCaptureDeviceTypeBuiltInMicrophone"), + symbolAvailability: availabilityBuilder.ToImmutable ()), + new EnumMember ( + name: "BuiltInWideAngleCamera", + libraryName: "AVFoundation", + libraryPath: null, + fieldData: new ("AVCaptureDeviceTypeBuiltInWideAngleCamera"), + symbolAvailability: availabilityBuilder.ToImmutable ()), + new EnumMember ( + name: "BuiltInTelephotoCamera", + libraryName: "AVFoundation", + libraryPath: null, + fieldData: new ("AVCaptureDeviceTypeBuiltInTelephotoCamera"), + symbolAvailability: availabilityBuilder.ToImmutable ()), + ], + UsingDirectives = new HashSet { "System", "Foundation", "ObjCRutime" }, + } + ]; + + const string missingField = @" +using System; +using Foundation; +using ObjCRutime; + +namespace AVFoundation; + +public enum AVCaptureDeviceType { + + [Field (""AVCaptureDeviceTypeBuiltInMicrophone"")] + BuiltInMicrophone, + + [Field (""AVCaptureDeviceTypeBuiltInWideAngleCamera"")] + BuiltInWideAngleCamera, + + // missing attr, this should be ignored + BuiltInTelephotoCamera, +} +"; + + yield return [ + (Source: missingField, Path: path), + + new Binding ( + symbolName: "AVCaptureDeviceType", + @namespace: ["AVFoundation"], + fullyQualifiedSymbol: "AVFoundation.AVCaptureDeviceType", + info: new BindingInfo (null, BindingType.SmartEnum), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new ()) { + Base = "System.Enum", + Modifiers = [Token (SyntaxKind.PublicKeyword)], + EnumMembers = [ + new EnumMember ( + name: "BuiltInMicrophone", + libraryName: "AVFoundation", + libraryPath: null, + fieldData: new ("AVCaptureDeviceTypeBuiltInMicrophone"), + symbolAvailability: availabilityBuilder.ToImmutable ()), + new EnumMember ( + name: "BuiltInWideAngleCamera", + libraryName: "AVFoundation", + libraryPath: null, + fieldData: new ("AVCaptureDeviceTypeBuiltInWideAngleCamera"), + symbolAvailability: availabilityBuilder.ToImmutable ()), + ], + UsingDirectives = new HashSet { "System", "Foundation", "ObjCRutime" }, + } + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, Binding expectedData) + { + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + + var binding = new Binding (declaration, symbol, new (semanticModel)); + Assert.Equal (expectedData, binding, comparer); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Extensions/TypeSymbolExtensionsTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/Extensions/TypeSymbolExtensionsTests.cs new file mode 100644 index 000000000000..dd8dc1b2ceee --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Extensions/TypeSymbolExtensionsTests.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Extensions; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests.Extensions; + +public class TypeSymbolExtensionsTests : BaseTransformerTestClass { + + class TestDataIsSmartEnum : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + + const string normalEnum = @" +using System; + +namespace Test; + +public enum MyEnum { + First, + Second, + Last, +} +"; + yield return [(Source: normalEnum, Path: path), false]; + + const string traditionalSmartEnum = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public enum MyEnum { + [Field (""FirstEnum""] + First, + [Field (""Second""] + Second, + [Field (""Last""] + Last, +} +"; + + yield return [(Source: traditionalSmartEnum, Path: path), true]; + + const string partialSmartEnum = @" +using System; +using Foundation; +using ObjCRuntime; + +namespace Test; + +public enum MyEnum { + First, + Second, + [Field (""Last""] + Last, +} +"; + + // should not be very common, nevertheless test for it. + yield return [(Source: partialSmartEnum, Path: path), true]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void IsSmartEnumTests (ApplePlatform platform, (string Source, string Path) source, bool expectedResult) + { + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + var isSmartEnum = symbol.IsSmartEnum (); + Assert.Equal (expectedResult, symbol.IsSmartEnum ()); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/IO/TabbedStreamWriterTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/IO/TabbedStreamWriterTests.cs new file mode 100644 index 000000000000..1fa3bd7692a1 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/IO/TabbedStreamWriterTests.cs @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.Macios.Generator.IO; + +namespace Microsoft.Macios.Transformer.Tests.IO; + +public class TabbedStreamWriterTests : IDisposable { + readonly string tempFile = Path.GetTempFileName (); + + public void Dispose () + { + if (File.Exists (tempFile)) + File.Delete (tempFile); + } + + string ReadFile () + { + using var reader = new StreamReader (tempFile); + return reader.ReadToEnd (); + } + + [Theory] + [InlineData (0, "")] + [InlineData (1, "\t")] + [InlineData (5, "\t\t\t\t\t")] + public void ConstructorNotBlockTest (int tabCount, string expectedTabs) + { + using (var block = new TabbedStreamWriter (tempFile, tabCount)) { + block.WriteLine ("Test"); + } + Assert.Equal ($"{expectedTabs}Test\n", ReadFile ()); + } + + [Theory] + [InlineData (0, "")] + [InlineData (1, "\t")] + [InlineData (5, "\t\t\t\t\t")] + public void ConstructorBlockTest (int tabCount, string expectedTabs) + { + using (var block = new TabbedStreamWriter (tempFile, tabCount, true)) { + block.WriteLine ("Test"); + } + + Assert.Equal ($"{expectedTabs}{{\n{expectedTabs}\tTest\n{expectedTabs}}}\n", ReadFile ()); + } + + [Fact] + public void ConstructorBlockNestedTest () + { + using (var block = new TabbedStreamWriter (tempFile, 0, false)) { + block.WriteLine ("// create the first block"); + using (var block2 = block.CreateBlock ("using (var test1 = new Test ())", true)) { + block2.WriteLine ("// call in first block"); + } + block.WriteLine (); + block.WriteLine ("// create second block"); + using (var block3 = block.CreateBlock ("using (var test2 = new Test ())", true)) { + block3.WriteLine ("// create nested block"); + using (var block4 = block3.CreateBlock ("using (var test3 = new Test ())", true)) { + block4.WriteLine ("// code inside test2.test3"); + } + } + } + + const string expectedResult = @"// create the first block +using (var test1 = new Test ()) +{ + // call in first block +} + +// create second block +using (var test2 = new Test ()) +{ + // create nested block + using (var test3 = new Test ()) + { + // code inside test2.test3 + } +} +"; + Assert.Equal (expectedResult, ReadFile ()); + } + + [Fact] + public async Task ConstructorBlockNestedAsyncTest () + { + await using (var block = new TabbedStreamWriter (tempFile, 0, false)) { + await block.WriteLineAsync ("// create the first block"); + await using (var block2 = block.CreateBlock ("using (var test1 = new Test ())", true)) { + await block2.WriteLineAsync ("// call in first block"); + } + await block.WriteLineAsync (); + await block.WriteLineAsync ("// create second block"); + await using (var block3 = block.CreateBlock ("using (var test2 = new Test ())", true)) { + await block3.WriteLineAsync ("// create nested block"); + await using (var block4 = block3.CreateBlock ("using (var test3 = new Test ())", true)) { + await block4.WriteLineAsync ("// code inside test2.test3"); + } + } + } + + const string expectedResult = @"// create the first block +using (var test1 = new Test ()) +{ + // call in first block +} + +// create second block +using (var test2 = new Test ()) +{ + // create nested block + using (var test3 = new Test ()) + { + // code inside test2.test3 + } +} +"; + Assert.Equal (expectedResult, ReadFile ()); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj b/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj index e676a0a7b310..0c7e46734484 100644 --- a/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj @@ -1,58 +1,74 @@ - - - - net$(BundledNETCoreAppTargetFrameworkVersion) - enable - enable - false - - - - - - - - - - - - - - - - - - - - external\Configuration.cs - - - external\ConfigurationXUnit.cs - - - external\Profile.cs - - - external\ExecutionHelper.cs - - - external\ApplePlatform.cs - - - external\TargetFramework.cs - - - external\StringUtils.cs - - - external\Execution.cs - - - external\SdkVersions.cs - - - external\Cache.cs - - + + + + net$(BundledNETCoreAppTargetFrameworkVersion) + enable + enable + false + + + $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)\..\..\..\src')) + build/dotnet + + + + true + + + + true + + + + + + + + + + + + + + + + + + + + + + external\Configuration.cs + + + external\ConfigurationXUnit.cs + + + external\Profile.cs + + + external\ExecutionHelper.cs + + + external\StringUtils.cs + + + external\Execution.cs + + + external\Cache.cs + + + external\TestDataFactory.cs + + + + + + + + + + diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/SyntaxTreeExtensions.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/SyntaxTreeExtensions.cs new file mode 100644 index 000000000000..5fec426dc818 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/SyntaxTreeExtensions.cs @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.CodeAnalysis; + +namespace Microsoft.Macios.Transformer.Tests; + +public static class SyntaxTreeExtensions { + + public static SyntaxTree? ForSource (this IEnumerable trees, (string Source, string Path) source) + => trees.FirstOrDefault (t => t.FilePath == source.Path); +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/TransformerTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/TransformerTests.cs new file mode 100644 index 000000000000..a4cf60bac078 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/TransformerTests.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Transformer.Workers; +using Xamarin.Tests; +using Xamarin.Utils; + +namespace Microsoft.Macios.Transformer.Tests; + +public class TransformerTests : BaseTransformerTestClass, IDisposable { + string targetDirectory; + + public TransformerTests () + { + targetDirectory = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ()); + Directory.CreateDirectory (targetDirectory); + } + + + class TestDataSkipTests : IEnumerable { + public IEnumerator GetEnumerator () + { + const string sampleCode = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV] +[MacCatalyst (13, 1)] +[DisableDefaultCtor] +[Abstract] +[BaseType (typeof (NSObject))] +interface UIFeedbackGenerator : UIInteraction { + + [iOS (17, 5), MacCatalyst (17, 5)] + [Static] + [Export (""feedbackGeneratorForView:"")] + UIFeedbackGenerator GetFeedbackGenerator (UIView forView); + + [Export (""prepare"")] + void Prepare (); +} +"; + // correct path, not namespaces, do not skip and destination + yield return [(sampleCode, "/some/random/path.cs"), null!, false, "Test"]; + + // correct path, namespaces, do not skip and destination + yield return [(sampleCode, "/some/random/path.cs"), new [] { "Test" }, false, "Test"]; + + // correct path, namespaces, do not skip and destination + yield return [(sampleCode, "/some/random/path.cs"), new [] { "UIKit" }, true, null!]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + public void SkipTests (ApplePlatform platform, (string Source, string Path) source, string []? targetNamespaces, + bool expectedResult, string? expectedDestination) + { + // create a compilation used to create the transformer + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + + var transformer = new Transformer (targetDirectory, [(platform, compilation)], targetNamespaces); + if (expectedDestination is not null) + expectedDestination = Path.Combine (targetDirectory, expectedDestination); + Assert.Equal (expectedResult, transformer.Skip (syntaxTree, symbol, out var destination)); + Assert.Equal (expectedDestination, destination); + } + + class TestDataSelectTopicTests : IEnumerable { + public IEnumerator GetEnumerator () + { + const string path = "/path/to/source.cs"; + const string errorDomain = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV, NoMacCatalyst, iOS (18, 2)] +[ErrorDomain (""UIApplicationCategoryDefaultErrorDomain"")] +[Native] +public enum UIApplicationCategoryDefaultErrorCode : long { + RateLimited = 1, +} +"; + + yield return [(errorDomain, path), nameof (ErrorDomainTransformer)]; + + const string smartEnum = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +public enum UIAccessibilityTraits : long { + [Field (""UIAccessibilityTraitNone"")] + None, + + [Field (""UIAccessibilityTraitButton"")] + Button, + + [Field (""UIAccessibilityTraitLink"")] + Link, + + [Field (""UIAccessibilityTraitHeader"")] + Header, + + [Field (""UIAccessibilityTraitSearchField"")] + SearchField, +} +"; + + yield return [(smartEnum, path), nameof (SmartEnumTransformer)]; + + const string normalEnum = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +public enum UIAccessibilityTraits : long { + None, + Button, + Link, + Header, + SearchField, +} +"; + + yield return [(normalEnum, path), nameof (CopyTransformer)]; + + const string category = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[TV (18, 0), iOS (18, 0), MacCatalyst (18, 0)] +[Category] +[BaseType (typeof (NSObject))] +interface NSObject_UIAccessibilityHitTest { + [Export (""accessibilityHitTest:withEvent:"")] + [return: NullAllowed] + NSObject AccessibilityHitTest (CGPoint point, [NullAllowed] UIEvent withEvent); +} +"; + + yield return [(category, path), nameof (CategoryTransformer)]; + + const string baseType = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[TV (18, 0), iOS (18, 0), MacCatalyst (18, 0)] +[BaseType (typeof (NSObject))] +interface UIZoomTransitionInteractionContext { + [Export (""location"")] + CGPoint Location { get; } + + [Export (""velocity"")] + CGVector Velocity { get; } + + [Export (""willBegin"")] + bool WillBegin { get; } +} +"; + + yield return [(baseType, path), nameof (ClassTransformer)]; + + const string protocol = @" +using System; +using Foundation; +using ObjCRuntime; +using UIKit; + +namespace Test; + +[NoTV, NoMacCatalyst, iOS (18, 0)] +[Protocol (BackwardsCompatibleCodeGeneration = false), Model] +[BaseType (typeof (NSObject))] +interface UITextFormattingViewControllerDelegate { + [Abstract] + [Export (""textFormattingViewController:didChangeValue:"")] + void DidChangeValue (UITextFormattingViewController viewController, UITextFormattingViewControllerChangeValue changeValue); + + [Export (""textFormattingViewController:shouldPresentFontPicker:"")] + bool ShouldPresentFontPicker (UITextFormattingViewController viewController, UIFontPickerViewController fontPicker); + + [Export (""textFormattingViewController:shouldPresentColorPicker:"")] + bool ShouldPresentColorPicker (UITextFormattingViewController viewController, UIColorPickerViewController colorPicker); + + [Export (""textFormattingDidFinish:"")] + void TextFormattingDidFinish (UITextFormattingViewController viewController); +} +"; + + yield return [(protocol, path), nameof (ProtocolTransformer)]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + public void SelectTopicTests (ApplePlatform platform, (string Source, string Path) source, string expectedTopic) + { + // create a compilation used to create the transformer + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + + // there is not need for a transformer, we are just testing the topic selection + Assert.Equal (expectedTopic, Transformer.SelectTopic (symbol)); + } + + public void Dispose () + { + // remove the temporary directory + Directory.Delete (targetDirectory, recursive: true); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/UnitTest1.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/UnitTest1.cs deleted file mode 100644 index 327ca91936b7..000000000000 --- a/tests/rgen/Microsoft.Macios.Transformer.Tests/UnitTest1.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -namespace Microsoft.Macios.Transformer.Tests; - -public class UnitTest1 { - [Fact] - public void Test1 () - { - Assert.True (true); - } -} diff --git a/tests/xharness/Harness.cs b/tests/xharness/Harness.cs index c9bcac43b55f..cf277f1021ef 100644 --- a/tests/xharness/Harness.cs +++ b/tests/xharness/Harness.cs @@ -357,28 +357,28 @@ void PopulateUnitTestProjects () Label = TestLabel.Generator, ProjectPath = Path.GetFullPath (Path.Combine (HarnessConfiguration.RootDirectory, "bgen", "bgen-tests.csproj")), Name = "BGen tests", - Timeout = (TimeSpan?) null, + Timeout = (TimeSpan?) TimeSpan.FromMinutes (30), Filter = "", }, new { Label = TestLabel.Generator, ProjectPath = Path.GetFullPath (Path.Combine (HarnessConfiguration.RootDirectory, "rgen", "Microsoft.Macios.Generator.Tests", "Microsoft.Macios.Generator.Tests.csproj")), Name = "Roslyn Generator tests", - Timeout = (TimeSpan?) null, + Timeout = (TimeSpan?) TimeSpan.FromMinutes (30), Filter = "", }, new { Label = TestLabel.Generator, ProjectPath = Path.GetFullPath (Path.Combine (HarnessConfiguration.RootDirectory, "rgen", "Microsoft.Macios.Bindings.Analyzer.Tests", "Microsoft.Macios.Bindings.Analyzer.Tests.csproj")), Name = "Roslyn Analyzer tests", - Timeout = (TimeSpan?) null, + Timeout = (TimeSpan?) TimeSpan.FromMinutes (30), Filter = "", }, new { Label = TestLabel.Generator, ProjectPath = Path.GetFullPath (Path.Combine (HarnessConfiguration.RootDirectory, "rgen", "Microsoft.Macios.Transformer.Tests", "Microsoft.Macios.Transformer.Tests.csproj")), Name = "Roslyn Transformer tests", - Timeout = (TimeSpan?) null, + Timeout = (TimeSpan?) TimeSpan.FromMinutes (30), Filter = "", }, new { diff --git a/tools/devops/automation/build-cronjob.yml b/tools/devops/automation/build-cronjob.yml index a632e6b367b7..8a6b275a06ce 100644 --- a/tools/devops/automation/build-cronjob.yml +++ b/tools/devops/automation/build-cronjob.yml @@ -32,12 +32,6 @@ resources: ref: refs/heads/main endpoint: xamarin - - repository: sdk-insertions - type: github - name: xamarin/sdk-insertions - ref: refs/heads/main - endpoint: xamarin - - repository: maccore type: github name: xamarin/maccore diff --git a/tools/devops/automation/build-lego.yml b/tools/devops/automation/build-lego.yml index 56cc2451538b..cdd253a86a6c 100644 --- a/tools/devops/automation/build-lego.yml +++ b/tools/devops/automation/build-lego.yml @@ -26,12 +26,6 @@ resources: ref: refs/heads/main endpoint: xamarin - - repository: sdk-insertions - type: github - name: xamarin/sdk-insertions - ref: refs/heads/main - endpoint: xamarin - - repository: maccore type: github name: xamarin/maccore diff --git a/tools/devops/automation/build-pipeline.yml b/tools/devops/automation/build-pipeline.yml index de5ac8964149..b62c7b670dfa 100644 --- a/tools/devops/automation/build-pipeline.yml +++ b/tools/devops/automation/build-pipeline.yml @@ -14,7 +14,7 @@ parameters: - name: macOSName # comes from the build agent demand named macOS.Name displayName: Name of the version of macOS to use type: string - default: 'Sonoma' + default: 'Sequoia' - name: runGovernanceTests displayName: Run Governance Checks @@ -129,12 +129,6 @@ resources: ref: refs/heads/main endpoint: xamarin - - repository: sdk-insertions - type: github - name: xamarin/sdk-insertions - ref: refs/heads/main - endpoint: xamarin - - repository: maccore type: github name: xamarin/maccore @@ -153,7 +147,6 @@ resources: variables: - ${{ if contains(variables['Build.DefinitionName'], 'private') }}: - template: templates/vsts-variables.yml - - template: templates/common/vs-release-vars.yml@sdk-insertions - template: templates/variables/common.yml - template: templates/variables/api-scan.yml - template: templates/variables/signing.yml @@ -163,9 +156,6 @@ variables: value: true trigger: - # because we are building for developers branches, batch the builds to use - # less resources. Otherwise, we would be building for every commit. - batch: true branches: include: - '*' @@ -218,7 +208,6 @@ extends: - repository: maccore exclude: - repository: yaml-templates - - repository: sdk-insertions - repository: macios-adr # macios-adr has it's own build pipeline and should not be included in the source analysis stages: - template: templates/main-stage.yml diff --git a/tools/devops/automation/build-pull-request.yml b/tools/devops/automation/build-pull-request.yml index ee0b940d0a0c..32d67a95e133 100644 --- a/tools/devops/automation/build-pull-request.yml +++ b/tools/devops/automation/build-pull-request.yml @@ -15,7 +15,7 @@ parameters: - name: macOSName # comes from the build agent demand named macOS.Name displayName: Name of the version of macOS to use type: string - default: 'Sonoma' + default: 'Sequoia' - name: runGovernanceTests displayName: Run Governance Checks @@ -120,12 +120,6 @@ resources: ref: refs/heads/main endpoint: xamarin - - repository: sdk-insertions - type: github - name: xamarin/sdk-insertions - ref: refs/heads/main - endpoint: xamarin - - repository: maccore type: github name: xamarin/maccore @@ -144,7 +138,6 @@ resources: variables: - template: templates/variables/common.yml - template: templates/variables/api-scan.yml -- template: templates/common/vs-release-vars.yml@sdk-insertions - name: Packaging.EnableSBOMSigning value: false @@ -154,6 +147,8 @@ trigger: branches: include: - refs/heads/dev/* + - refs/heads/darc-* + - refs/heads/backport-pr-* pr: autoCancel: true @@ -204,7 +199,6 @@ extends: - repository: maccore exclude: - repository: yaml-templates - - repository: sdk-insertions - repository: macios-adr # macios-adr has it's own build pipeline and should not be included in the source analysis stages: - template: templates/main-stage.yml diff --git a/tools/devops/automation/publish-pr-html-results.yml b/tools/devops/automation/publish-pr-html-results.yml index dd237a74855b..0822d729458a 100644 --- a/tools/devops/automation/publish-pr-html-results.yml +++ b/tools/devops/automation/publish-pr-html-results.yml @@ -17,12 +17,6 @@ resources: ref: refs/heads/main endpoint: xamarin - - repository: sdk-insertions - type: github - name: xamarin/sdk-insertions - ref: refs/heads/main - endpoint: xamarin - - repository: maccore type: github name: xamarin/maccore diff --git a/tools/devops/automation/run-post-ci-build-vs-insertion.yml b/tools/devops/automation/run-post-ci-build-vs-insertion.yml index 08afda9d5b46..b2ba7336592e 100644 --- a/tools/devops/automation/run-post-ci-build-vs-insertion.yml +++ b/tools/devops/automation/run-post-ci-build-vs-insertion.yml @@ -75,7 +75,6 @@ extends: - repository: maccore exclude: - repository: yaml-templates - - repository: sdk-insertions - repository: macios-adr # macios-adr has it's own build pipeline and should not be included in the source analysis stages: - template: templates/release/vs-insertion-prep.yml diff --git a/tools/devops/automation/scripts/GitHub.psm1 b/tools/devops/automation/scripts/GitHub.psm1 index d9fd7f62e56f..1feeee779fec 100644 --- a/tools/devops/automation/scripts/GitHub.psm1 +++ b/tools/devops/automation/scripts/GitHub.psm1 @@ -904,6 +904,12 @@ function Get-GitHubPRsForHash { # loop over the result and remove all the extra noise we are not interested in $prs = [System.Collections.ArrayList]@() foreach ($prInfo in $request) { + $state = $prInfo.state + if ($state -ne "open") { + Write-Host "Skipping PR #$($prInfo.number) because it is not open" + continue + } + # only returns those PRS whose status is open $number = $prInfo.number Write-Host "Found PR #$number for commit $hash" $prs.Add($number) > $null diff --git a/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml b/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml index 991def1ca58b..3a22e978aa6e 100644 --- a/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml +++ b/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml @@ -11,7 +11,7 @@ parameters: - name: macOSName # comes from the build agent demand named macOS.Name displayName: Name of the version of macOS to use type: string - default: 'Sonoma' + default: 'Sequoia' - name: pool type: string diff --git a/tools/devops/automation/templates/pipelines/build-pipeline.yml b/tools/devops/automation/templates/pipelines/build-pipeline.yml index 7271c276caff..9ac13c79d5de 100644 --- a/tools/devops/automation/templates/pipelines/build-pipeline.yml +++ b/tools/devops/automation/templates/pipelines/build-pipeline.yml @@ -11,7 +11,7 @@ parameters: - name: macOSName # comes from the build agent demand named macOS.Name displayName: Name of the version of macOS to use type: string - default: 'Sonoma' + default: 'Sequoia' - name: pool type: string @@ -143,12 +143,6 @@ resources: ref: refs/heads/main endpoint: xamarin - - repository: sdk-insertions - type: github - name: xamarin/sdk-insertions - ref: refs/heads/main - endpoint: xamarin - - repository: maccore type: github name: xamarin/maccore diff --git a/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml b/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml index b87e0def11af..210d8a997969 100644 --- a/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml +++ b/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml @@ -14,7 +14,7 @@ parameters: - name: macOSName # comes from the build agent demand named macOS.Name displayName: Name of the version of macOS to use type: string - default: 'Sonoma' + default: 'Sequoia' - name: runTests displayName: Run Simulator Tests diff --git a/tools/devops/automation/templates/release/vs-insertion-prep.yml b/tools/devops/automation/templates/release/vs-insertion-prep.yml index af72c61d5c67..41246b8963e0 100644 --- a/tools/devops/automation/templates/release/vs-insertion-prep.yml +++ b/tools/devops/automation/templates/release/vs-insertion-prep.yml @@ -52,6 +52,7 @@ stages: # Check - "xamarin-macios (Prepare Release Sign NuGets)" - template: sign-artifacts/jobs/v2.yml@yaml-templates parameters: + timeoutInMinutes: 120 use1ESTemplate: true uploadBinlogs: true uploadPrefix: ${{ parameters.uploadPrefix }} From a5640073bf501125b6c9fa05c7d8c055f7cf6f2a Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Wed, 12 Feb 2025 21:07:04 +0100 Subject: [PATCH 4/5] Back to main --- eng/Version.Details.xml | 8 +- eng/Versions.props | 6 +- eng/common/internal/Tools.csproj | 10 - eng/common/template-guidance.md | 2 +- global.json | 2 +- src/CoreFoundation/CFProxySupport.cs | 113 +-- src/CoreGraphics/CGAffineTransform.cs | 8 + src/CoreGraphics/CGColor.cs | 4 + src/CoreGraphics/CGColorConversionInfo.cs | 4 + src/CoreGraphics/CGContext.cs | 36 +- src/CoreGraphics/CGDisplay.cs | 4 + src/CoreGraphics/CGImage.cs | 4 + src/CoreGraphics/CGPath.cs | 40 + src/CoreMedia/CMAttachmentBearer.cs | 2 - src/CoreMedia/CMBlockBuffer.cs | 6 - src/CoreMedia/CMBufferQueue.cs | 90 -- src/CoreMedia/CMCustomBlockAllocator.cs | 32 - src/CoreMedia/CMFormatDescription.cs | 26 - src/CoreMedia/CMSampleBuffer.cs | 89 +- src/CoreMedia/CMSync.cs | 211 ----- src/CoreMedia/CMTextMarkupAttributes.cs | 4 - src/CoreMedia/CMTime.cs | 14 - src/CoreMedia/CoreMedia.cs | 36 - src/CoreVideo/CVBuffer.cs | 44 - src/CoreVideo/CVDisplayLink.cs | 237 ----- src/CoreVideo/CVImageBuffer.cs | 35 - src/CoreVideo/CVMetalBuffer.cs | 8 - src/CoreVideo/CVMetalBufferCache.cs | 8 - src/CoreVideo/CVMetalTexture.cs | 8 - src/CoreVideo/CVMetalTextureCache.cs | 4 - src/CoreVideo/CVOpenGLESTexture.cs | 5 - src/CoreVideo/CVOpenGLESTextureCache.cs | 5 - src/CoreVideo/CVPixelBuffer.cs | 50 +- src/CoreVideo/CVPixelBufferAttributes.cs | 4 - src/CoreVideo/CVPixelBufferIOSurface.cs | 10 - src/CoreVideo/CVPixelBufferPool.cs | 11 - src/CoreVideo/CVPixelBufferPoolSettings.cs | 4 - src/CoreVideo/CVPixelFormatDescription.cs | 19 +- src/CoreVideo/CVPixelFormatType.cs | 14 - src/CoreVideo/CVTime.cs | 2 - src/CoreVideo/CoreVideo.cs | 16 - src/Intents/INBillTypeResolutionResult.cs | 39 - src/Intents/INCallRecord.cs | 2 + .../INCallRecordTypeResolutionResult.cs | 43 - ...INCarAirCirculationModeResolutionResult.cs | 40 - ...CirculationModeResolutionResult.watchOS.cs | 60 -- .../INCarAudioSourceResolutionResult.cs | 39 - ...NCarAudioSourceResolutionResult.watchOS.cs | 56 -- src/Intents/INCarDefrosterResolutionResult.cs | 39 - .../INCarDefrosterResolutionResult.watchOS.cs | 55 -- src/Intents/INCarSeatResolutionResult.cs | 38 - .../INCarSeatResolutionResult.watchOS.cs | 55 -- .../INCarSignalOptionsResolutionResult.cs | 39 - src/Intents/INCompat.cs | 37 - .../INGetCarLockStatusIntentResponse.cs | 28 - .../INGetCarPowerLevelStatusIntentResponse.cs | 34 - src/Intents/INIntentResolutionResult.cs | 16 +- src/Intents/INInteraction.cs | 5 +- ...MessageAttributeOptionsResolutionResult.cs | 45 - .../INMessageAttributeResolutionResult.cs | 45 - .../INPaymentStatusResolutionResult.cs | 39 - src/Intents/INPerson.cs | 16 - src/Intents/INPlayMediaIntentResponse.cs | 2 + src/Intents/INPriceRange.cs | 19 +- src/Intents/INRadioTypeResolutionResult.cs | 39 - .../INRadioTypeResolutionResult.watchOS.cs | 55 -- .../INRelativeReferenceResolutionResult.cs | 39 - ...lativeReferenceResolutionResult.watchOS.cs | 55 -- .../INRelativeSettingResolutionResult.cs | 39 - ...RelativeSettingResolutionResult.watchOS.cs | 55 -- src/Intents/INRideOption.cs | 20 - src/Intents/INSaveProfileInCarIntent.cs | 30 - src/Intents/INSearchCallHistoryIntent.cs | 6 +- src/Intents/INSetCarLockStatusIntent.cs | 7 - .../INSetClimateSettingsInCarIntent.cs | 8 +- .../INSetDefrosterSettingsInCarIntent.cs | 8 +- src/Intents/INSetProfileInCarIntent.cs | 27 +- src/Intents/INSetSeatSettingsInCarIntent.cs | 8 +- src/Intents/INSpeakableString.cs | 31 - src/Intents/INStartWorkoutIntent.cs | 13 +- .../INWorkoutGoalUnitTypeResolutionResult.cs | 39 - .../INWorkoutLocationTypeResolutionResult.cs | 39 - src/ObjCBindings/ExportTag.cs | 39 +- src/Social/Enums.cs | 14 - src/Social/SLComposeViewController.cs | 4 +- src/Social/SLRequest.cs | 45 - src/UIKit/UIEnums.cs | 1 + src/WebKit/WKPreferences.cs | 5 - src/foundation.cs | 9 + src/frameworks.sources | 29 - src/intents.cs | 872 ++---------------- src/metal.cs | 4 - .../DataModel/Binding.Generator.cs | 30 + .../DataModel/Binding.cs | 29 - .../DataModel/Constructor.Generator.cs | 2 +- .../DataModel/Method.Generator.cs | 57 +- .../DataModel/Parameter.Generator.cs | 7 +- .../DataModel/Property.Generator.cs | 50 +- .../DataModel/TypeInfo.Generator.cs | 14 +- .../BindingSyntaxFactory.ObjCRuntime.cs | 21 + .../Extensions/SemanticModelExtensions.cs | 30 +- .../AttributesNames.cs | 2 +- .../DataModel/Binding.Transformer.cs | 162 +++- .../DataModel/Method.Transformer.cs | 2 +- .../DataModel/ModifiersFlags.cs | 75 +- .../DataModel/Property.Transformer.cs | 2 +- .../TransformerBindingEqualityComparer.cs | 23 + src/rsp/dotnet/macos-defines-dotnet.rsp | 1 + src/social.cs | 39 + tests/cecil-tests/ApiAvailabilityTest.cs | 10 - .../ConstructorTest.KnownFailures.cs | 3 - .../Documentation.KnownFailures.txt | 40 +- .../SetHandleTest.KnownFailures.cs | 1 - tests/common/MonoTouch.Dialog/Elements.cs | 329 +------ .../MonoTouch.Dialog/Elements/ElementBadge.cs | 156 ---- .../MonoTouch.Dialog/Utilities/ImageLoader.cs | 352 ------- tests/dotnet/UnitTests/BundleStructureTest.cs | 13 - tests/dotnet/UnitTests/ProjectTest.cs | 23 +- tests/dotnet/UnitTests/WindowsTest.cs | 11 - .../DeviceDiscoveryExtension/DDDeviceTest.cs | 8 +- .../DDDevicePickerViewControllerTest.cs | 12 +- tests/monotouch-test/Foundation/CookieTest.cs | 2 + .../FromDeclarationTests.cs} | 36 +- .../MethodTests/GeneralMethodTests.cs | 46 + .../{ => MethodTests}/MethodComparerTests.cs | 3 +- .../MethodEqualityComparerTests.cs | 3 +- .../MethodTests/NeedsTempReturnTests.cs | 213 +++++ .../FromDeclarationTests.cs} | 418 +-------- .../PropertyTests/GeneralPropertyTests.cs | 427 +++++++++ .../PropertyTests/NeedsTempReturnTests.cs | 183 ++++ .../PropertiesEqualityComparerTests.cs | 3 +- .../BindingSyntaxFactoryObjCRuntimeTests.cs | 147 ++- .../DataModel/BindingTests.cs | 415 +++++++++ .../{MethodTests.cs => GeneralTests.cs} | 2 +- .../DataModel/SmartEnumTests.cs | 2 +- tests/xharness/Jenkins/TestServer.cs | 26 +- tools/dotnet-linker/CecilExtensions.cs | 13 +- .../Steps/ManagedRegistrarLookupTablesStep.cs | 26 +- .../Steps/ManagedRegistrarStep.cs | 11 +- 139 files changed, 2319 insertions(+), 4727 deletions(-) delete mode 100644 src/Intents/INBillTypeResolutionResult.cs delete mode 100644 src/Intents/INCallRecordTypeResolutionResult.cs delete mode 100644 src/Intents/INCarAirCirculationModeResolutionResult.cs delete mode 100644 src/Intents/INCarAirCirculationModeResolutionResult.watchOS.cs delete mode 100644 src/Intents/INCarAudioSourceResolutionResult.cs delete mode 100644 src/Intents/INCarAudioSourceResolutionResult.watchOS.cs delete mode 100644 src/Intents/INCarDefrosterResolutionResult.cs delete mode 100644 src/Intents/INCarDefrosterResolutionResult.watchOS.cs delete mode 100644 src/Intents/INCarSeatResolutionResult.cs delete mode 100644 src/Intents/INCarSeatResolutionResult.watchOS.cs delete mode 100644 src/Intents/INCarSignalOptionsResolutionResult.cs delete mode 100644 src/Intents/INCompat.cs delete mode 100644 src/Intents/INGetCarLockStatusIntentResponse.cs delete mode 100644 src/Intents/INGetCarPowerLevelStatusIntentResponse.cs delete mode 100644 src/Intents/INMessageAttributeOptionsResolutionResult.cs delete mode 100644 src/Intents/INMessageAttributeResolutionResult.cs delete mode 100644 src/Intents/INPaymentStatusResolutionResult.cs delete mode 100644 src/Intents/INRadioTypeResolutionResult.cs delete mode 100644 src/Intents/INRadioTypeResolutionResult.watchOS.cs delete mode 100644 src/Intents/INRelativeReferenceResolutionResult.cs delete mode 100644 src/Intents/INRelativeReferenceResolutionResult.watchOS.cs delete mode 100644 src/Intents/INRelativeSettingResolutionResult.cs delete mode 100644 src/Intents/INRelativeSettingResolutionResult.watchOS.cs delete mode 100644 src/Intents/INRideOption.cs delete mode 100644 src/Intents/INSaveProfileInCarIntent.cs delete mode 100644 src/Intents/INSpeakableString.cs delete mode 100644 src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs delete mode 100644 src/Intents/INWorkoutLocationTypeResolutionResult.cs create mode 100644 src/rgen/Microsoft.Macios.Transformer/DataModel/TransformerBindingEqualityComparer.cs delete mode 100644 tests/common/MonoTouch.Dialog/Elements/ElementBadge.cs delete mode 100644 tests/common/MonoTouch.Dialog/Utilities/ImageLoader.cs rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{MethodTests.cs => MethodTests/FromDeclarationTests.cs} (93%) create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/GeneralMethodTests.cs rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{ => MethodTests}/MethodComparerTests.cs (99%) rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{ => MethodTests}/MethodEqualityComparerTests.cs (99%) create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/NeedsTempReturnTests.cs rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{PropertyTests.cs => PropertyTests/FromDeclarationTests.cs} (73%) create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/GeneralPropertyTests.cs create mode 100644 tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/NeedsTempReturnTests.cs rename tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/{ => PropertyTests}/PropertiesEqualityComparerTests.cs (98%) create mode 100644 tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/BindingTests.cs rename tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/{MethodTests.cs => GeneralTests.cs} (99%) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 73611fcc814f..a008969b42fa 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -87,9 +87,9 @@ - + https://github.com/dotnet/arcade - 8cc6ecd76c24ef6665579a5c5e386a211a1e7c54 + bac7e1caea791275b7c3ccb4cb75fd6a04a26618 https://github.com/dotnet/templating @@ -99,9 +99,9 @@ https://github.com/dotnet/xharness cf1b2925785f504d4d52773bcab470044e35ea15 - + https://github.com/dotnet/arcade - 8cc6ecd76c24ef6665579a5c5e386a211a1e7c54 + bac7e1caea791275b7c3ccb4cb75fd6a04a26618 diff --git a/eng/Versions.props b/eng/Versions.props index 9fb05e16f127..a52769d87194 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -5,15 +5,15 @@ 9.0.102-servicing.24610.2 9.0.0 9.0.0-alpha.1.23556.4 - 9.0.0-beta.25058.5 + 9.0.0-beta.25077.4 8.0.0-beta.24413.2 9.0.0 8.0.0-rtm.23511.3 9.0.0-rc.2.24462.10 7.0.100-alpha.1.21601.1 0.11.5-alpha.24515.1 - 10.0.0-prerelease.25103.1 - 9.0.0-beta.25058.5 + 10.0.0-prerelease.24610.1 + 9.0.0-beta.25077.4 $(MicrosoftNETWorkloadEmscriptenCurrentManifest80100Version) $(MicrosoftNETWorkloadEmscriptenCurrentManifest80100Version) diff --git a/eng/common/internal/Tools.csproj b/eng/common/internal/Tools.csproj index 32f79dfb3402..feaa6d20812d 100644 --- a/eng/common/internal/Tools.csproj +++ b/eng/common/internal/Tools.csproj @@ -15,16 +15,6 @@ - - - - https://devdiv.pkgs.visualstudio.com/_packaging/dotnet-core-internal-tooling/nuget/v3/index.json; - - - $(RestoreSources); - https://devdiv.pkgs.visualstudio.com/_packaging/VS/nuget/v3/index.json; - - diff --git a/eng/common/template-guidance.md b/eng/common/template-guidance.md index 5ef6c30ba924..98bbc1ded0ba 100644 --- a/eng/common/template-guidance.md +++ b/eng/common/template-guidance.md @@ -57,7 +57,7 @@ extends: Note: Multiple outputs are ONLY applicable to 1ES PT publishing (only usable when referencing `templates-official`). -# Development notes +## Development notes **Folder / file structure** diff --git a/global.json b/global.json index 15f15446e735..24b50ad27ca4 100644 --- a/global.json +++ b/global.json @@ -6,6 +6,6 @@ "dotnet": "9.0.102-servicing.24610.2" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.25058.5" + "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.25077.4" } } diff --git a/src/CoreFoundation/CFProxySupport.cs b/src/CoreFoundation/CFProxySupport.cs index 24cdf7178f35..49ae75369036 100644 --- a/src/CoreFoundation/CFProxySupport.cs +++ b/src/CoreFoundation/CFProxySupport.cs @@ -36,9 +36,7 @@ using System.Runtime.Versioning; using ObjCRuntime; using Foundation; -#if NET using CFNetwork; -#endif namespace CoreFoundation { // Utility enum for string constants in ObjC @@ -52,12 +50,10 @@ public enum CFProxyType { SOCKS } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CFProxy { NSDictionary settings; @@ -339,12 +335,10 @@ public string? Username { } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CFProxySettings { NSDictionary settings; @@ -490,12 +484,10 @@ public string? ProxyAutoConfigURLString { } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public static partial class CFNetwork { [DllImport (Constants.CFNetworkLibrary)] unsafe extern static /* CFArrayRef __nullable */ IntPtr CFNetworkCopyProxiesForAutoConfigurationScript ( @@ -617,15 +609,7 @@ public static partial class CFNetwork { return new CFProxySettings (dict); } -#if !NET - delegate void CFProxyAutoConfigurationResultCallbackInternal (IntPtr client, IntPtr proxyList, IntPtr error); - // helper delegate to reuse code -#endif -#if NET unsafe delegate IntPtr CreatePACCFRunLoopSource (delegate* unmanaged cb, ref CFStreamClientContext context); -#else - delegate IntPtr CreatePACCFRunLoopSource (CFProxyAutoConfigurationResultCallbackInternal cb, ref CFStreamClientContext context); -#endif static CFProxy []? ParseProxies (IntPtr proxyList) { @@ -667,11 +651,7 @@ public NSError? Error { } // callback that will sent the client info -#if NET [UnmanagedCallersOnly] -#else - [MonoPInvokeCallback (typeof (CFProxyAutoConfigurationResultCallbackInternal))] -#endif static void ExecutePacCallback (IntPtr client, IntPtr proxyList, IntPtr error) { // grab the required structure and set the data, according apple docs: @@ -717,32 +697,26 @@ await Task.Run (() => { var clientContext = new CFStreamClientContext (); clientContext.Info = pacDataPtr; -#if NET unsafe { - using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) -#else - using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) -#endif - using (var mode = new NSString ("Xamarin.iOS.Proxy")) { - - if (cancellationToken.IsCancellationRequested) - throw new OperationCanceledException ("Operation was cancelled."); - - cancellationToken.Register (() => { - //if user cancels, we invalidte the source, stop the runloop and remove the source - loopSource.Invalidate (); + using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) + using (var mode = new NSString ("Xamarin.iOS.Proxy")) { + + if (cancellationToken.IsCancellationRequested) + throw new OperationCanceledException ("Operation was cancelled."); + + cancellationToken.Register (() => { + //if user cancels, we invalidte the source, stop the runloop and remove the source + loopSource.Invalidate (); + runLoop.RemoveSource (loopSource, mode); + runLoop.Stop (); + }); + runLoop.AddSource (loopSource, mode); + // blocks until stop is called, will be done in the cb set previously + runLoop.RunInMode (mode, double.MaxValue, false); + // does not raise an error if source is not longer present, so no need to worry runLoop.RemoveSource (loopSource, mode); - runLoop.Stop (); - }); - runLoop.AddSource (loopSource, mode); - // blocks until stop is called, will be done in the cb set previously - runLoop.RunInMode (mode, double.MaxValue, false); - // does not raise an error if source is not longer present, so no need to worry - runLoop.RemoveSource (loopSource, mode); - } -#if NET + } } // matches the unsafe block -#endif if (cancellationToken.IsCancellationRequested) throw new OperationCanceledException ("Operation was cancelled."); @@ -781,23 +755,17 @@ await Task.Run (() => { var clientContext = new CFStreamClientContext (); clientContext.Info = pacDataPtr; -#if NET unsafe { - using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) -#else - using (var loopSource = new CFRunLoopSource (factory (ExecutePacCallback, ref clientContext), true)) -#endif - using (var mode = new NSString ("Xamarin.iOS.Proxy")) { - runLoop.AddSource (loopSource, mode); - runLoop.RunInMode (mode, double.MaxValue, false); - runLoop.RemoveSource (loopSource, mode); - } - pacCbData = Marshal.PtrToStructure (pacDataPtr)!; - // get data from the struct - outError = pacCbData.Error; -#if NET + using (var loopSource = new CFRunLoopSource (factory (&ExecutePacCallback, ref clientContext), true)) + using (var mode = new NSString ("Xamarin.iOS.Proxy")) { + runLoop.AddSource (loopSource, mode); + runLoop.RunInMode (mode, double.MaxValue, false); + runLoop.RemoveSource (loopSource, mode); + } + pacCbData = Marshal.PtrToStructure (pacDataPtr)!; + // get data from the struct + outError = pacCbData.Error; } // unsafe -#endif return pacCbData.ProxyList; } finally { if (pacCbData.ProxyListPtr != IntPtr.Zero) @@ -812,11 +780,7 @@ await Task.Run (() => { extern unsafe static /* CFRunLoopSourceRef __nonnull */ IntPtr CFNetworkExecuteProxyAutoConfigurationScript ( /* CFStringRef __nonnull */ IntPtr proxyAutoConfigurationScript, /* CFURLRef __nonnull */ IntPtr targetURL, -#if NET /* CFProxyAutoConfigurationResultCallback __nonnull */ delegate* unmanaged cb, -#else - /* CFProxyAutoConfigurationResultCallback __nonnull */ CFProxyAutoConfigurationResultCallbackInternal cb, -#endif /* CFStreamClientContext * __nonnull */ CFStreamClientContext* clientContext); public static CFProxy []? ExecuteProxyAutoConfigurationScript (string proxyAutoConfigurationScript, Uri targetUrl, out NSError? outError) @@ -832,11 +796,7 @@ await Task.Run (() => { using (var url = new NSUrl (targetUrl.AbsoluteUri)) { CreatePACCFRunLoopSource factory; unsafe { -#if NET factory = delegate (delegate* unmanaged cb, ref CFStreamClientContext context) -#else - factory = delegate (CFProxyAutoConfigurationResultCallbackInternal cb, ref CFStreamClientContext context) -#endif { return CFNetworkExecuteProxyAutoConfigurationScript (pacScript.Handle, url.Handle, cb, (CFStreamClientContext*) Unsafe.AsPointer (ref context)); }; @@ -857,11 +817,7 @@ await Task.Run (() => { using (var url = new NSUrl (targetUrl.AbsoluteUri)) { CreatePACCFRunLoopSource factory; unsafe { -#if NET factory = delegate (delegate* unmanaged cb, ref CFStreamClientContext context) -#else - factory = delegate (CFProxyAutoConfigurationResultCallbackInternal cb, ref CFStreamClientContext context) -#endif { return CFNetworkExecuteProxyAutoConfigurationScript (pacScript.Handle, url.Handle, cb, (CFStreamClientContext*) Unsafe.AsPointer (ref context)); }; @@ -871,21 +827,12 @@ await Task.Run (() => { } } -#if NET [DllImport (Constants.CFNetworkLibrary)] extern unsafe static /* CFRunLoopSourceRef __nonnull */ IntPtr CFNetworkExecuteProxyAutoConfigurationURL ( /* CFURLRef __nonnull */ IntPtr proxyAutoConfigurationURL, /* CFURLRef __nonnull */ IntPtr targetURL, /* CFProxyAutoConfigurationResultCallback __nonnull */ delegate* unmanaged cb, /* CFStreamClientContext * __nonnull */ CFStreamClientContext* clientContext); -#else - [DllImport (Constants.CFNetworkLibrary)] - extern unsafe static /* CFRunLoopSourceRef __nonnull */ IntPtr CFNetworkExecuteProxyAutoConfigurationURL ( - /* CFURLRef __nonnull */ IntPtr proxyAutoConfigurationURL, - /* CFURLRef __nonnull */ IntPtr targetURL, - /* CFProxyAutoConfigurationResultCallback __nonnull */ CFProxyAutoConfigurationResultCallbackInternal cb, - /* CFStreamClientContext * __nonnull */ CFStreamClientContext* clientContext); -#endif public static CFProxy []? ExecuteProxyAutoConfigurationUrl (Uri proxyAutoConfigurationUrl, Uri targetUrl, out NSError? outError) { @@ -900,11 +847,7 @@ await Task.Run (() => { using (var url = new NSUrl (targetUrl.AbsoluteUri)) { CreatePACCFRunLoopSource factory; unsafe { -#if NET factory = delegate (delegate* unmanaged cb, ref CFStreamClientContext context) -#else - factory = delegate (CFProxyAutoConfigurationResultCallbackInternal cb, ref CFStreamClientContext context) -#endif { return CFNetworkExecuteProxyAutoConfigurationURL (pacUrl.Handle, url.Handle, cb, (CFStreamClientContext*) Unsafe.AsPointer (ref context)); }; @@ -926,11 +869,7 @@ await Task.Run (() => { using (var url = new NSUrl (targetUrl.AbsoluteUri)) { CreatePACCFRunLoopSource factory; unsafe { -#if NET factory = delegate (delegate* unmanaged cb, ref CFStreamClientContext context) -#else - factory = delegate (CFProxyAutoConfigurationResultCallbackInternal cb, ref CFStreamClientContext context) -#endif { return CFNetworkExecuteProxyAutoConfigurationURL (pacUrl.Handle, url.Handle, cb, (CFStreamClientContext*) Unsafe.AsPointer (ref context)); }; diff --git a/src/CoreGraphics/CGAffineTransform.cs b/src/CoreGraphics/CGAffineTransform.cs index 620b85fdd7d7..962babf65da9 100644 --- a/src/CoreGraphics/CGAffineTransform.cs +++ b/src/CoreGraphics/CGAffineTransform.cs @@ -468,6 +468,10 @@ public CGAffineTransform Invert () [DllImport (Constants.CoreGraphicsLibrary)] static extern CGAffineTransformComponents CGAffineTransformDecompose (CGAffineTransform transform); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGAffineTransformComponents Decompose () { return CGAffineTransformDecompose (this); @@ -484,6 +488,10 @@ public CGAffineTransformComponents Decompose () [DllImport (Constants.CoreGraphicsLibrary)] static extern CGAffineTransform CGAffineTransformMakeWithComponents (CGAffineTransformComponents components); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public static CGAffineTransform MakeWithComponents (CGAffineTransformComponents components) { return CGAffineTransformMakeWithComponents (components); diff --git a/src/CoreGraphics/CGColor.cs b/src/CoreGraphics/CGColor.cs index 68d896b124cc..4a821790728a 100644 --- a/src/CoreGraphics/CGColor.cs +++ b/src/CoreGraphics/CGColor.cs @@ -142,6 +142,10 @@ public CGColor (string name) { } + [SupportedOSPlatform ("ios14.0")] + [SupportedOSPlatform ("tvos14.0")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] static IntPtr Create (CGConstantColor color) { var constant = color.GetConstant (); diff --git a/src/CoreGraphics/CGColorConversionInfo.cs b/src/CoreGraphics/CGColorConversionInfo.cs index 5251ef727a0d..6778f5686b72 100644 --- a/src/CoreGraphics/CGColorConversionInfo.cs +++ b/src/CoreGraphics/CGColorConversionInfo.cs @@ -142,6 +142,10 @@ public CGColorConversionInfo (CGColorSpace source, CGColorSpace destination) [DllImport (Constants.CoreGraphicsLibrary)] static extern /* CGColorConversionInfoRef* */ IntPtr CGColorConversionInfoCreateWithOptions (/* CGColorSpaceRef* */ IntPtr src, /* CGColorSpaceRef* */ IntPtr dst, /* CFDictionaryRef _Nullable */ IntPtr options); + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] static IntPtr Create (CGColorSpace source, CGColorSpace destination, NSDictionary? options) { if (source is null) diff --git a/src/CoreGraphics/CGContext.cs b/src/CoreGraphics/CGContext.cs index af5248c560ee..586ca7736924 100644 --- a/src/CoreGraphics/CGContext.cs +++ b/src/CoreGraphics/CGContext.cs @@ -988,8 +988,10 @@ public void ShowText (byte []? bytes) [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] - [ObsoletedOSPlatform ("macos10.9")] - [ObsoletedOSPlatform ("ios7.0")] + [ObsoletedOSPlatform ("macos10.9", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("tvos9.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("ios7.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the 'CoreText' API instead.")] #else [Deprecated (PlatformName.iOS, 7, 0)] [Deprecated (PlatformName.MacOSX, 10, 9)] @@ -1005,6 +1007,8 @@ extern static void CGContextShowTextAtPoint (/* CGContextRef __nullable */ IntPt [SupportedOSPlatform ("tvos")] [ObsoletedOSPlatform ("macos10.9", "Use the 'CoreText' API instead.")] [ObsoletedOSPlatform ("ios7.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("tvos9.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the 'CoreText' API instead.")] #else [Deprecated (PlatformName.iOS, 7, 0, message: "Use the 'CoreText' API instead.")] [Deprecated (PlatformName.MacOSX, 10, 9, message: "Use the 'CoreText' API instead.")] @@ -1021,7 +1025,9 @@ public void ShowTextAtPoint (nfloat x, nfloat y, string? str, int length) [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [ObsoletedOSPlatform ("macos10.9", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("tvos9.0", "Use the 'CoreText' API instead.")] [ObsoletedOSPlatform ("ios7.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the 'CoreText' API instead.")] #else [Deprecated (PlatformName.iOS, 7, 0, message: "Use the 'CoreText' API instead.")] [Deprecated (PlatformName.MacOSX, 10, 9, message: "Use the 'CoreText' API instead.")] @@ -1037,8 +1043,10 @@ public void ShowTextAtPoint (nfloat x, nfloat y, string? str) [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] - [ObsoletedOSPlatform ("macos10.9")] - [ObsoletedOSPlatform ("ios7.0")] + [ObsoletedOSPlatform ("macos10.9", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("tvos9.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("ios7.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the 'CoreText' API instead.")] #else [Deprecated (PlatformName.iOS, 7, 0)] [Deprecated (PlatformName.MacOSX, 10, 9)] @@ -1046,11 +1054,27 @@ public void ShowTextAtPoint (nfloat x, nfloat y, string? str) [DllImport (Constants.CoreGraphicsLibrary)] extern static void CGContextShowTextAtPoint (/* CGContextRef */ IntPtr c, /* CGFloat */ nfloat x, /* CGFloat */ nfloat y, /* const char* */ byte []? bytes, /* size_t */ nint length); + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] + [ObsoletedOSPlatform ("macos10.9", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("tvos9.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("ios7.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the 'CoreText' API instead.")] public void ShowTextAtPoint (nfloat x, nfloat y, byte []? bytes, int length) { CGContextShowTextAtPoint (Handle, x, y, bytes, length); } + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] + [ObsoletedOSPlatform ("macos10.9", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("tvos9.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("ios7.0", "Use the 'CoreText' API instead.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the 'CoreText' API instead.")] public void ShowTextAtPoint (nfloat x, nfloat y, byte []? bytes) { CGContextShowTextAtPoint (Handle, x, y, bytes, bytes is null ? 0 : bytes.Length); @@ -1430,6 +1454,10 @@ public CGBitmapContext AsBitmapContext () [DllImport (Constants.CoreGraphicsLibrary)] static extern void CGContextDrawConicGradient (/* CGContext */ IntPtr context, /*[NullAllowed] CGGradient*/ IntPtr gradient, CGPoint center, nfloat angle); + [SupportedOSPlatform ("ios17.0")] + [SupportedOSPlatform ("maccatalyst17.0")] + [SupportedOSPlatform ("macos14.0")] + [SupportedOSPlatform ("tvos17.0")] public void DrawConicGradient (CGGradient? gradient, CGPoint point, nfloat angle) => CGContextDrawConicGradient (Handle, gradient.GetHandle (), point, angle); diff --git a/src/CoreGraphics/CGDisplay.cs b/src/CoreGraphics/CGDisplay.cs index e526968846e1..2c1630bed4c1 100644 --- a/src/CoreGraphics/CGDisplay.cs +++ b/src/CoreGraphics/CGDisplay.cs @@ -96,6 +96,10 @@ public static int GetGammaTableCapacity (int display) [DllImport (Constants.CoreGraphicsLibrary)] static extern byte CGDisplayIsCaptured (uint display); + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [ObsoletedOSPlatform ("macos10.9")] + [ObsoletedOSPlatform ("maccatalyst13.1")] public static bool IsCaptured (int display) { return CGDisplayIsCaptured ((uint)display) != 0; diff --git a/src/CoreGraphics/CGImage.cs b/src/CoreGraphics/CGImage.cs index bb0ce4fde487..bb995d9cf6b3 100644 --- a/src/CoreGraphics/CGImage.cs +++ b/src/CoreGraphics/CGImage.cs @@ -301,6 +301,10 @@ public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, i return FromHandle (imageRef, true); } #else + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("tvos")] + [UnsupportedOSPlatform ("maccatalyst")] + [UnsupportedOSPlatform ("macos")] public static CGImage? ScreenImage { get { return UIKit.UIScreen.MainScreen.Capture ().CGImage; diff --git a/src/CoreGraphics/CGPath.cs b/src/CoreGraphics/CGPath.cs index c82619db8395..1d0ce2813bb1 100644 --- a/src/CoreGraphics/CGPath.cs +++ b/src/CoreGraphics/CGPath.cs @@ -556,6 +556,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyByNormalizing (IntPtr path, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateByNormalizing (bool evenOddFillRule) { return Runtime.GetINativeObject (CGPathCreateCopyByNormalizing (Handle, evenOddFillRule.AsByte ()), owns: true); @@ -572,6 +576,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyByUnioningPath (IntPtr path, IntPtr maskPath, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateByUnioningPath (CGPath? maskPath, bool evenOddFillRule) { return Runtime.GetINativeObject (CGPathCreateCopyByUnioningPath (Handle, maskPath.GetHandle (), evenOddFillRule.AsByte ()), owns: true); @@ -588,6 +596,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyByIntersectingPath (IntPtr path, IntPtr maskPath, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateByIntersectingPath (CGPath? maskPath, bool evenOddFillRule) { return Runtime.GetINativeObject (CGPathCreateCopyByIntersectingPath (Handle, maskPath.GetHandle (), evenOddFillRule.AsByte ()), owns: true); @@ -604,6 +616,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyBySubtractingPath (IntPtr path, IntPtr maskPath, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateBySubtractingPath (CGPath? maskPath, bool evenOddFillRule) { return Runtime.GetINativeObject (CGPathCreateCopyBySubtractingPath (Handle, maskPath.GetHandle (), evenOddFillRule.AsByte ()), owns: true); @@ -620,6 +636,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyBySymmetricDifferenceOfPath (IntPtr path, IntPtr maskPath, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateBySymmetricDifferenceOfPath (CGPath? maskPath, bool evenOddFillRule) { return Runtime.GetINativeObject (CGPathCreateCopyBySymmetricDifferenceOfPath (Handle, maskPath.GetHandle (), evenOddFillRule.AsByte ()), owns: true); @@ -636,6 +656,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyOfLineBySubtractingPath (IntPtr path, IntPtr maskPath, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateLineBySubtractingPath (CGPath? maskPath, bool evenOddFillRule) { return Runtime.GetINativeObject (CGPathCreateCopyOfLineBySubtractingPath (Handle, maskPath.GetHandle (), evenOddFillRule.AsByte ()), owns: true); @@ -652,6 +676,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyOfLineByIntersectingPath (IntPtr path, IntPtr maskPath, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateLineByIntersectingPath (CGPath? maskPath, bool evenOddFillRule) { return Runtime.GetINativeObject (CGPathCreateCopyOfLineByIntersectingPath (Handle, maskPath.GetHandle (), evenOddFillRule.AsByte ()), owns: true); @@ -668,6 +696,10 @@ public void Apply (ApplierFunction func) [DllImport (Constants.CoreGraphicsLibrary)] static extern unsafe /* CFArrayRef __nullable */ IntPtr CGPathCreateSeparateComponents (IntPtr path, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath [] GetSeparateComponents (bool evenOddFillRule) { var cfArrayRef = CGPathCreateSeparateComponents (Handle, evenOddFillRule.AsByte ()); @@ -687,6 +719,10 @@ public CGPath [] GetSeparateComponents (bool evenOddFillRule) [DllImport (Constants.CoreGraphicsLibrary)] static extern IntPtr CGPathCreateCopyByFlattening (IntPtr path, nfloat flatteningThreshold); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public CGPath? CreateByFlattening (nfloat flatteningThreshold) { return Runtime.GetINativeObject (CGPathCreateCopyByFlattening (Handle, flatteningThreshold), owns: true); @@ -703,6 +739,10 @@ public CGPath [] GetSeparateComponents (bool evenOddFillRule) [DllImport (Constants.CoreGraphicsLibrary)] static extern byte CGPathIntersectsPath (IntPtr path1, IntPtr path2, byte evenOddFillRule); + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("tvos16.0")] public bool DoesIntersect (CGPath? maskPath, bool evenOddFillRule) { return CGPathIntersectsPath (Handle, maskPath.GetHandle (), evenOddFillRule.AsByte ()) != 0; diff --git a/src/CoreMedia/CMAttachmentBearer.cs b/src/CoreMedia/CMAttachmentBearer.cs index e601ed93c090..0a3cfb6faa9b 100644 --- a/src/CoreMedia/CMAttachmentBearer.cs +++ b/src/CoreMedia/CMAttachmentBearer.cs @@ -10,12 +10,10 @@ namespace CoreMedia { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public static class CMAttachmentBearer { [DllImport (Constants.CoreMediaLibrary)] diff --git a/src/CoreMedia/CMBlockBuffer.cs b/src/CoreMedia/CMBlockBuffer.cs index 4b51e2dcd5bd..5a5595ea0cd0 100644 --- a/src/CoreMedia/CMBlockBuffer.cs +++ b/src/CoreMedia/CMBlockBuffer.cs @@ -19,18 +19,12 @@ using CoreFoundation; using ObjCRuntime; -#if !NET -using NativeHandle = System.IntPtr; -#endif - namespace CoreMedia { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMBlockBuffer : NativeObject, ICMAttachmentBearer { CMCustomBlockAllocator? customAllocator; diff --git a/src/CoreMedia/CMBufferQueue.cs b/src/CoreMedia/CMBufferQueue.cs index 6ad5cae24bdd..1388b662744f 100644 --- a/src/CoreMedia/CMBufferQueue.cs +++ b/src/CoreMedia/CMBufferQueue.cs @@ -24,17 +24,13 @@ namespace CoreMedia { public delegate bool CMBufferGetBool (INativeObject buffer); public delegate int CMBufferCompare (INativeObject first, INativeObject second); -#if NET // [SupportedOSPlatform ("ios")] - SupportedOSPlatform is not valid on this declaration type "delegate" -#endif public delegate nint CMBufferGetSize (INativeObject buffer); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMBufferQueue : NativeObject { #if !COREBUILD GCHandle gch; @@ -46,37 +42,17 @@ public class CMBufferQueue : NativeObject { CMBufferCompare? compare; CMBufferGetSize? getTotalSize; -#if !NET - delegate CMTime BufferGetTimeCallback (/* CMBufferRef */ IntPtr buf, /* void* */ IntPtr refcon); - [return: MarshalAs (UnmanagedType.I1)] - delegate bool BufferGetBooleanCallback (/* CMBufferRef */ IntPtr buf, /* void* */ IntPtr refcon); - delegate int BufferCompareCallback (/* CMBufferRef */ IntPtr buf1, /* CMBufferRef */ IntPtr buf2, /* void* */ IntPtr refcon); - delegate nint BufferGetSizeCallback (/* CMBufferRef */ IntPtr buffer, /* void* */ IntPtr refcon); -#endif - [StructLayout (LayoutKind.Sequential)] struct CMBufferCallbacks { internal uint version; internal IntPtr refcon; -#if NET internal unsafe delegate* unmanaged XgetDecodeTimeStamp; internal unsafe delegate* unmanaged XgetPresentationTimeStamp; internal unsafe delegate* unmanaged XgetDuration; internal unsafe delegate* unmanaged XisDataReady; internal unsafe delegate* unmanaged Xcompare; -#else - internal IntPtr XgetDecodeTimeStamp; - internal IntPtr XgetPresentationTimeStamp; - internal IntPtr XgetDuration; - internal IntPtr XisDataReady; - internal IntPtr Xcompare; -#endif internal IntPtr cfStringPtr_dataBecameReadyNotification; -#if NET internal unsafe delegate* unmanaged XgetSize; -#else - internal IntPtr XgetSize; -#endif } // A version with no delegates, just native pointers @@ -130,7 +106,6 @@ protected override void Dispose (bool disposing) CMBufferGetBool? isDataReady, CMBufferCompare? compare, NSString dataBecameReadyNotification, CMBufferGetSize? getTotalSize) { var bq = new CMBufferQueue (count); -#if NET CMBufferCallbacks cbacks; unsafe { cbacks = new CMBufferCallbacks () { @@ -145,19 +120,6 @@ protected override void Dispose (bool disposing) XgetSize = getTotalSize is not null ? &GetTotalSize : null }; } -#else - var cbacks = new CMBufferCallbacks () { - version = (uint) (getTotalSize is null ? 0 : 1), - refcon = GCHandle.ToIntPtr (bq.gch), - XgetDecodeTimeStamp = getDecodeTimeStamp is not null ? Marshal.GetFunctionPointerForDelegate (GetDecodeTimeStampCallback) : IntPtr.Zero, - XgetPresentationTimeStamp = getPresentationTimeStamp is not null ? Marshal.GetFunctionPointerForDelegate (GetPresentationTimeStampCallback) : IntPtr.Zero, - XgetDuration = getDuration is not null ? Marshal.GetFunctionPointerForDelegate (GetDurationCallback) : IntPtr.Zero, - XisDataReady = isDataReady is not null ? Marshal.GetFunctionPointerForDelegate (GetDataReadyCallback) : IntPtr.Zero, - Xcompare = compare is not null ? Marshal.GetFunctionPointerForDelegate (CompareCallback) : IntPtr.Zero, - cfStringPtr_dataBecameReadyNotification = dataBecameReadyNotification is null ? IntPtr.Zero : dataBecameReadyNotification.Handle, - XgetSize = getTotalSize is not null ? Marshal.GetFunctionPointerForDelegate (GetTotalSizeCallback) : IntPtr.Zero - }; -#endif bq.getDecodeTimeStamp = getDecodeTimeStamp; bq.getPresentationTimeStamp = getPresentationTimeStamp; @@ -320,21 +282,17 @@ public CMTime Duration { } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static /* size_t */ nint CMBufferQueueGetTotalSize (/* CMBufferQueueRef */ IntPtr queue); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public nint GetTotalSize () { return CMBufferQueueGetTotalSize (Handle); @@ -347,14 +305,7 @@ INativeObject Surface (IntPtr v) return queueObjects [v]; } -#if NET [UnmanagedCallersOnly] -#else - static BufferGetTimeCallback GetDecodeTimeStampCallback = GetDecodeTimeStamp; -#if !MONOMAC - [MonoPInvokeCallback (typeof (BufferGetTimeCallback))] -#endif -#endif static CMTime GetDecodeTimeStamp (IntPtr buffer, IntPtr refcon) { var queue = (CMBufferQueue?) GCHandle.FromIntPtr (refcon).Target; @@ -363,14 +314,7 @@ static CMTime GetDecodeTimeStamp (IntPtr buffer, IntPtr refcon) return queue.getDecodeTimeStamp (queue.Surface (buffer)); } -#if NET [UnmanagedCallersOnly] -#else - static BufferGetTimeCallback GetPresentationTimeStampCallback = GetPresentationTimeStamp; -#if !MONOMAC - [MonoPInvokeCallback (typeof (BufferGetTimeCallback))] -#endif -#endif static CMTime GetPresentationTimeStamp (IntPtr buffer, IntPtr refcon) { var queue = (CMBufferQueue?) GCHandle.FromIntPtr (refcon).Target; @@ -379,14 +323,7 @@ static CMTime GetPresentationTimeStamp (IntPtr buffer, IntPtr refcon) return queue.getPresentationTimeStamp (queue.Surface (buffer)); } -#if NET [UnmanagedCallersOnly] -#else - static BufferGetTimeCallback GetDurationCallback = GetDuration; -#if !MONOMAC - [MonoPInvokeCallback (typeof (BufferGetTimeCallback))] -#endif -#endif static CMTime GetDuration (IntPtr buffer, IntPtr refcon) { var queue = (CMBufferQueue?) GCHandle.FromIntPtr (refcon).Target; @@ -395,36 +332,16 @@ static CMTime GetDuration (IntPtr buffer, IntPtr refcon) return queue.getDuration (queue.Surface (buffer)); } -#if NET [UnmanagedCallersOnly] static byte GetDataReady (IntPtr buffer, IntPtr refcon) -#else - static BufferGetBooleanCallback GetDataReadyCallback = GetDataReady; -#if !MONOMAC - [MonoPInvokeCallback (typeof (BufferGetBooleanCallback))] -#endif - static bool GetDataReady (IntPtr buffer, IntPtr refcon) -#endif { var queue = (CMBufferQueue?) GCHandle.FromIntPtr (refcon).Target; if (queue?.isDataReady is null) -#if NET return 0; return (byte) (queue.isDataReady (queue.Surface (buffer)) ? 1 : 0); -#else - return false; - return queue.isDataReady (queue.Surface (buffer)); -#endif } -#if NET [UnmanagedCallersOnly] -#else - static BufferCompareCallback CompareCallback = Compare; -#if !MONOMAC - [MonoPInvokeCallback (typeof (BufferCompareCallback))] -#endif -#endif static int Compare (IntPtr buffer1, IntPtr buffer2, IntPtr refcon) { var queue = (CMBufferQueue?) GCHandle.FromIntPtr (refcon).Target; @@ -433,14 +350,7 @@ static int Compare (IntPtr buffer1, IntPtr buffer2, IntPtr refcon) return queue.compare (queue.Surface (buffer1), queue.Surface (buffer2)); } -#if NET [UnmanagedCallersOnly] -#else - static BufferGetSizeCallback GetTotalSizeCallback = GetTotalSize; -#if !MONOMAC - [MonoPInvokeCallback (typeof (BufferGetSizeCallback))] -#endif -#endif static nint GetTotalSize (IntPtr buffer, IntPtr refcon) { var queue = (CMBufferQueue?) GCHandle.FromIntPtr (refcon).Target; diff --git a/src/CoreMedia/CMCustomBlockAllocator.cs b/src/CoreMedia/CMCustomBlockAllocator.cs index aca2023cf094..56d85db28dbe 100644 --- a/src/CoreMedia/CMCustomBlockAllocator.cs +++ b/src/CoreMedia/CMCustomBlockAllocator.cs @@ -18,12 +18,10 @@ namespace CoreMedia { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMCustomBlockAllocator : IDisposable { GCHandle gch; @@ -33,7 +31,6 @@ public CMCustomBlockAllocator () gch = GCHandle.Alloc (this); // kCMBlockBufferCustomBlockSourceVersion = 0 <- this is the only and current value Cblock.Version = 0; -#if NET unsafe { // Assign function pointers to temporary variable due to https://github.com/dotnet/runtime/issues/107396. delegate* unmanaged allocate = &AllocateCallback; @@ -42,10 +39,6 @@ public CMCustomBlockAllocator () Cblock.Allocate = allocate; Cblock.Free = free; } -#else - Cblock.Allocate = Marshal.GetFunctionPointerForDelegate (static_AllocateCallback); - Cblock.Free = Marshal.GetFunctionPointerForDelegate (static_FreeCallback); -#endif Cblock.RefCon = GCHandle.ToIntPtr (gch); } @@ -53,32 +46,13 @@ public CMCustomBlockAllocator () [StructLayout (LayoutKind.Sequential, Pack = 4)] // it's 28 bytes (not 32) on 64 bits iOS internal struct CMBlockBufferCustomBlockSource { public uint Version; -#if NET public unsafe delegate* unmanaged Allocate; public unsafe delegate* unmanaged Free; -#else - public IntPtr Allocate; - public IntPtr Free; -#endif public IntPtr RefCon; } internal CMBlockBufferCustomBlockSource Cblock; -#if !NET - internal delegate IntPtr CMAllocateCallback (/* void* */ IntPtr refCon, /* size_t */ nuint sizeInBytes); - internal delegate void CMFreeCallback (/* void* */ IntPtr refCon, /* void* */ IntPtr doomedMemoryBlock, /* size_t */ nuint sizeInBytes); - - static CMAllocateCallback static_AllocateCallback = AllocateCallback; - static CMFreeCallback static_FreeCallback = FreeCallback; -#endif - -#if NET [UnmanagedCallersOnly] -#else -#if !MONOMAC - [MonoPInvokeCallback (typeof (CMAllocateCallback))] -#endif -#endif static IntPtr AllocateCallback (IntPtr refCon, nuint sizeInBytes) { var gch = GCHandle.FromIntPtr (refCon); @@ -92,13 +66,7 @@ public virtual IntPtr Allocate (nuint sizeInBytes) return Marshal.AllocHGlobal ((int) sizeInBytes); } -#if NET [UnmanagedCallersOnly] -#else -#if !MONOMAC - [MonoPInvokeCallback (typeof (CMFreeCallback))] -#endif -#endif static void FreeCallback (IntPtr refCon, IntPtr doomedMemoryBlock, nuint sizeInBytes) { var gch = GCHandle.FromIntPtr (refCon); diff --git a/src/CoreMedia/CMFormatDescription.cs b/src/CoreMedia/CMFormatDescription.cs index 8ca3cd9819d6..c6f253e8edfe 100644 --- a/src/CoreMedia/CMFormatDescription.cs +++ b/src/CoreMedia/CMFormatDescription.cs @@ -25,18 +25,12 @@ using CoreVideo; using AudioToolbox; -#if !NET -using NativeHandle = System.IntPtr; -#endif - namespace CoreMedia { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMFormatDescription : NativeObject { [Preserve (Conditional = true)] internal CMFormatDescription (NativeHandle handle, bool owns) @@ -307,12 +301,10 @@ public AudioFormat AudioRichestDecodableFormat { #endif } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMAudioFormatDescription : CMFormatDescription { [Preserve (Conditional = true)] internal CMAudioFormatDescription (NativeHandle handle, bool owns) @@ -323,12 +315,10 @@ internal CMAudioFormatDescription (NativeHandle handle, bool owns) // TODO: Move more audio specific methods here } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public partial class CMVideoFormatDescription : CMFormatDescription { [Preserve (Conditional = true)] internal CMVideoFormatDescription (NativeHandle handle, bool owns) @@ -390,12 +380,10 @@ public CMVideoDimensions Dimensions { return new CMVideoFormatDescription (desc, true); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe static extern /* OSStatus */ CMFormatDescriptionError CMVideoFormatDescriptionCreateFromH264ParameterSets ( /* CFAllocatorRef */ IntPtr allocator, @@ -405,12 +393,10 @@ public CMVideoDimensions Dimensions { /* int */ int NALUnitHeaderLength, /* CMFormatDescriptionRef* */ IntPtr* formatDescriptionOut); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMVideoFormatDescription? FromH264ParameterSets (List parameterSets, int nalUnitHeaderLength, out CMFormatDescriptionError error) { if (parameterSets is null) @@ -453,12 +439,10 @@ public CMVideoDimensions Dimensions { } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe static extern /* OSStatus */ CMFormatDescriptionError CMVideoFormatDescriptionGetH264ParameterSetAtIndex ( /* CMFormatDescriptionRef */ IntPtr videoDesc, @@ -468,12 +452,10 @@ public CMVideoDimensions Dimensions { /* size_t* */ nuint* parameterSetCountOut, /* int* */ int* nalUnitHeaderLengthOut); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public byte []? GetH264ParameterSet (nuint index, out nuint parameterSetCount, out int nalUnitHeaderLength, out CMFormatDescriptionError error) { IntPtr ret; @@ -521,12 +503,10 @@ public bool VideoMatchesImageBuffer (CVImageBuffer imageBuffer) return CMVideoFormatDescriptionMatchesImageBuffer (Handle, imageBuffer.Handle) != 0; } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe static extern /* OSStatus */ CMFormatDescriptionError CMVideoFormatDescriptionCreateFromHEVCParameterSets ( /* CFAllocatorRef */ IntPtr allocator, @@ -537,12 +517,10 @@ public bool VideoMatchesImageBuffer (CVImageBuffer imageBuffer) /* CFDictionaryRef */ IntPtr extensions, /* CMFormatDescriptionRef* */ IntPtr* formatDescriptionOut); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static CMVideoFormatDescription? FromHevcParameterSets (List parameterSets, int nalUnitHeaderLength, NSDictionary extensions, out CMFormatDescriptionError error) { if (parameterSets is null) @@ -585,12 +563,10 @@ public bool VideoMatchesImageBuffer (CVImageBuffer imageBuffer) } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe static extern /* OSStatus */ CMFormatDescriptionError CMVideoFormatDescriptionGetHEVCParameterSetAtIndex ( /* CMFormatDescriptionRef */ IntPtr videoDesc, @@ -600,12 +576,10 @@ public bool VideoMatchesImageBuffer (CVImageBuffer imageBuffer) /* size_t* */ nuint* parameterSetCountOut, /* int* */ int* nalUnitHeaderLengthOut); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public byte []? GetHevcParameterSet (nuint index, out nuint parameterSetCount, out int nalUnitHeaderLength, out CMFormatDescriptionError error) { IntPtr ret; diff --git a/src/CoreMedia/CMSampleBuffer.cs b/src/CoreMedia/CMSampleBuffer.cs index dd2cd47b4d63..91440dd93402 100644 --- a/src/CoreMedia/CMSampleBuffer.cs +++ b/src/CoreMedia/CMSampleBuffer.cs @@ -28,18 +28,12 @@ #endif #endif -#if !NET -using NativeHandle = System.IntPtr; -#endif - namespace CoreMedia { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMSampleBuffer : NativeObject, ICMAttachmentBearer { #if !COREBUILD GCHandle invalidate; @@ -167,24 +161,10 @@ unsafe static extern OSStatus CMSampleBufferCreateCopyWithNewTiming ( [DllImport (Constants.CoreMediaLibrary)] unsafe static extern CMSampleBufferError CMSampleBufferCallForEachSample ( /* CMSampleBufferRef */ IntPtr sbuf, -#if NET - delegate* unmanaged callback, -#else - CMSampleBufferCallForEachSampleCallback callback, -#endif + delegate* unmanaged callback, /* void* */ IntPtr refcon); -#if !NET - delegate CMSampleBufferError CMSampleBufferCallForEachSampleCallback (/* CMSampleBufferRef */ IntPtr - sampleBuffer, int index, /* void* */ IntPtr refcon); -#endif -#if NET [UnmanagedCallersOnly] -#else -#if !MONOMAC - [MonoPInvokeCallback (typeof (CMSampleBufferCallForEachSampleCallback))] -#endif -#endif static CMSampleBufferError ForEachSampleHandler (IntPtr sbuf, int index, IntPtr refCon) { GCHandle gch = GCHandle.FromIntPtr (refCon); @@ -202,13 +182,9 @@ public CMSampleBufferError CallForEachSample (Func invalidateCallback, -#else - /* CMSampleBufferInvalidateCallback */ CMSampleBufferInvalidateCallback? invalidateCallback, -#endif - /* uint64_t */ ulong invalidateRefCon); - -#if !NET - delegate void CMSampleBufferInvalidateCallback (/* CMSampleBufferRef */ IntPtr sbuf, /* uint64_t */ ulong invalidateRefCon); - static CMSampleBufferInvalidateCallback invalidate_handler = InvalidateHandler; -#endif - -#if NET [UnmanagedCallersOnly] -#else -#if !MONOMAC - [MonoPInvokeCallback (typeof (CMSampleBufferInvalidateCallback))] -#endif -#endif static void InvalidateHandler (IntPtr sbuf, ulong invalidateRefCon) { GCHandle gch = GCHandle.FromIntPtr ((IntPtr) invalidateRefCon); @@ -660,13 +615,9 @@ public CMSampleBufferError SetInvalidateCallback (Action invalid if (invalidateHandler is null) { if (invalidate.IsAllocated) invalidate.Free (); -#if NET unsafe { -#endif - return CMSampleBufferSetInvalidateCallback (Handle, null, 0); -#if NET + return CMSampleBufferSetInvalidateCallback (Handle, null, 0); } -#endif } // only one callback can be assigned - and ObjC does not let you re-assign a different one, @@ -676,13 +627,9 @@ public CMSampleBufferError SetInvalidateCallback (Action invalid return CMSampleBufferError.RequiredParameterMissing; invalidate = GCHandle.Alloc (Tuple.Create (invalidateHandler, this)); -#if NET unsafe { - return CMSampleBufferSetInvalidateCallback (Handle, &InvalidateHandler, (ulong)(IntPtr)invalidate); + return CMSampleBufferSetInvalidateCallback (Handle, &InvalidateHandler, (ulong) (IntPtr) invalidate); } -#else - return CMSampleBufferSetInvalidateCallback (Handle, invalidate_handler, (ulong) (IntPtr) invalidate); -#endif } [DllImport (Constants.CoreMediaLibrary)] @@ -693,21 +640,17 @@ public CMSampleBufferError TrackDataReadiness (CMSampleBuffer bufferToTrack) return CMSampleBufferTrackDataReadiness (Handle, bufferToTrack.GetHandle ()); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static /* OSStatus */ CMSampleBufferError CMSampleBufferCopyPCMDataIntoAudioBufferList (/* CMSampleBufferRef */ IntPtr sbuf, /* int32_t */ int frameOffset, /* int32_t */ int numFrames, /* AudioBufferList* */ IntPtr bufferList); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public CMSampleBufferError CopyPCMDataIntoAudioBufferList (int frameOffset, int numFrames, AudioBuffers bufferList) { if (bufferList is null) @@ -716,12 +659,10 @@ public CMSampleBufferError CopyPCMDataIntoAudioBufferList (int frameOffset, int return CMSampleBufferCopyPCMDataIntoAudioBufferList (Handle, frameOffset, numFrames, (IntPtr) bufferList); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe extern static /* OSStatus */ CMSampleBufferError CMAudioSampleBufferCreateReadyWithPacketDescriptions ( /* CFAllocatorRef */ IntPtr allocator, @@ -732,12 +673,10 @@ public CMSampleBufferError CopyPCMDataIntoAudioBufferList (int frameOffset, int /* AudioStreamPacketDescription* */ AudioStreamPacketDescription* packetDescriptions, /* CMSampleBufferRef* */ IntPtr* sBufOut); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMSampleBuffer? CreateReadyWithPacketDescriptions (CMBlockBuffer dataBuffer, CMFormatDescription formatDescription, int samplesCount, CMTime sampleTimestamp, AudioStreamPacketDescription []? packetDescriptions, out CMSampleBufferError error) { @@ -768,12 +707,10 @@ public CMSampleBufferError CopyPCMDataIntoAudioBufferList (int frameOffset, int return new CMSampleBuffer (buffer, true); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe extern static /* OSStatus */ CMSampleBufferError CMSampleBufferCreateReady ( /* CFAllocatorRef */ IntPtr allocator, @@ -786,12 +723,10 @@ public CMSampleBufferError CopyPCMDataIntoAudioBufferList (int frameOffset, int /* size_t* */ nuint* sampleSizeArray, // can be null /* CMSampleBufferRef* */ IntPtr* sBufOut); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMSampleBuffer? CreateReady (CMBlockBuffer dataBuffer, CMFormatDescription? formatDescription, int samplesCount, CMSampleTimingInfo []? sampleTimingArray, nuint []? sampleSizeArray, out CMSampleBufferError error) @@ -828,12 +763,10 @@ public CMSampleBufferError CopyPCMDataIntoAudioBufferList (int frameOffset, int return new CMSampleBuffer (buffer, true); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe extern static /* OSStatus */ CMSampleBufferError CMSampleBufferCreateReadyWithImageBuffer ( /* CFAllocatorRef */ IntPtr allocator, @@ -842,24 +775,10 @@ public CMSampleBufferError CopyPCMDataIntoAudioBufferList (int frameOffset, int /* const CMSampleTimingInfo * CM_NONNULL */ CMSampleTimingInfo* sampleTiming, /* CMSampleBufferRef* */ IntPtr* sBufOut); -#if !NET - [Obsolete ("Use the 'CreateReadyWithImageBuffer' overload with a single ref, not array, 'CMSampleTimingInfo' parameter.")] - public static CMSampleBuffer CreateReadyWithImageBuffer (CVImageBuffer imageBuffer, - CMFormatDescription formatDescription, CMSampleTimingInfo [] sampleTiming, out CMSampleBufferError error) - { - if (sampleTiming is null) - ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (sampleTiming)); - if (sampleTiming.Length != 1) - ObjCRuntime.ThrowHelper.ThrowArgumentException (nameof (sampleTiming), "Only a single sample is allowed."); - return CreateReadyWithImageBuffer (imageBuffer, formatDescription, sampleTiming, out error); - } -#endif // !NET -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMSampleBuffer? CreateReadyWithImageBuffer (CVImageBuffer imageBuffer, CMFormatDescription formatDescription, ref CMSampleTimingInfo sampleTiming, out CMSampleBufferError error) { @@ -1045,12 +964,10 @@ public string? DroppedFrameReason { } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("macos")] -#endif public LensStabilizationStatus StillImageLensStabilizationStatus { get { var reason = GetStringValue (CMSampleAttachmentKey.StillImageLensStabilizationInfo); diff --git a/src/CoreMedia/CMSync.cs b/src/CoreMedia/CMSync.cs index 15197044350f..a54da0bb7687 100644 --- a/src/CoreMedia/CMSync.cs +++ b/src/CoreMedia/CMSync.cs @@ -14,28 +14,16 @@ using CoreFoundation; using ObjCRuntime; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreMedia { // CMSync.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMClock : CMClockOrTimebase { -#if !NET - public CMClock (NativeHandle handle) : base (handle) - { - } -#endif - [Preserve (Conditional = true)] internal CMClock (NativeHandle handle, bool owns) : base (handle, owns) @@ -63,12 +51,10 @@ public CMTime CurrentTime { #if !MONOMAC // CMAudioClock.h -#if NET [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe extern static /* OSStatus */ CMClockError CMAudioClockCreate (/* CFAllocatorRef */ IntPtr allocator, /* CMClockRef* */ IntPtr* clockOut); @@ -121,20 +107,11 @@ public void Invalidate () #endif // !COREBUILD } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMTimebase : CMClockOrTimebase { -#if !NET - public CMTimebase (NativeHandle handle) - : base (handle) - { - } -#endif - [Preserve (Conditional = true)] private CMTimebase (NativeHandle handle, bool owns) : base (handle, owns) @@ -142,7 +119,6 @@ private CMTimebase (NativeHandle handle, bool owns) } #if !COREBUILD -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -151,11 +127,6 @@ private CMTimebase (NativeHandle handle, bool owns) [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios9.0")] -#else - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe extern static /* OSStatus */ CMTimebaseError CMTimebaseCreateWithMasterClock (/* CFAllocatorRef */ IntPtr allocator, /* CMClockRef */ IntPtr masterClock, /* CMTimebaseRef* */ IntPtr* timebaseOut); @@ -179,7 +150,6 @@ public CMTimebase (CMClock masterClock) { } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -188,11 +158,6 @@ public CMTimebase (CMClock masterClock) [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios8.0")] [ObsoletedOSPlatform ("maccatalyst13.0")] -#else - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe extern static /* OSStatus */ CMTimebaseError CMTimebaseCreateWithMasterTimebase (/* CFAllocatorRef */ IntPtr allocator, /* CMTimebaseRef */ IntPtr masterTimebase, /* CMTimebaseRef* */ IntPtr* timebaseOut); @@ -216,16 +181,10 @@ public CMTimebase (CMTimebase masterTimebase) { } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe static extern CMTimebaseError CMTimebaseCreateWithSourceClock (/* [NullAllowed] CFAllocatorRef */ IntPtr allocator, /* CMClock */ IntPtr sourceClock, /* CMTimebase */ IntPtr* timebaseOut); @@ -244,31 +203,19 @@ static IntPtr Create (CFAllocator? allocator, CMClock sourceClock) return handle; } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif public CMTimebase (CFAllocator? allocator, CMClock sourceClock) : base (Create (allocator, sourceClock), true) { } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] unsafe static extern CMTimebaseError CMTimebaseCreateWithSourceTimebase (/* [NullAllowed] CFAllocatorRef */ IntPtr allocator, /* CMTimebase */ IntPtr sourceTimebase, /* CMTimebase */ IntPtr* timebaseOut); @@ -287,16 +234,10 @@ static IntPtr Create (CFAllocator? allocator, CMTimebase sourceTimebase) return handle; } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif public CMTimebase (CFAllocator? allocator, CMTimebase sourceTimebase) : base (Create (allocator, sourceTimebase), true) { @@ -345,7 +286,6 @@ public double Rate { } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -354,15 +294,9 @@ public double Rate { [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios9.0")] -#else - [Deprecated (PlatformName.iOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 11)] - [Deprecated (PlatformName.TvOS, 9, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static /* CMTimebaseRef */ IntPtr CMTimebaseGetMasterTimebase (/* CMTimebaseRef */ IntPtr timebase); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -371,10 +305,6 @@ public double Rate { [ObsoletedOSPlatform ("ios9.0", "Use 'CopyMasterTimebase' instead.")] [ObsoletedOSPlatform ("tvos9.0", "Use 'CopyMasterTimebase' instead.")] [ObsoletedOSPlatform ("maccatalyst13.0", "Use 'CopyMasterTimebase' instead.")] -#else - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CopyMasterTimebase' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CopyMasterTimebase' instead.")] -#endif public CMTimebase? GetMasterTimebase () { var ptr = CMTimebaseGetMasterTimebase (Handle); @@ -384,7 +314,6 @@ public double Rate { return new CMTimebase (ptr, false); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -393,15 +322,9 @@ public double Rate { [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios9.0")] -#else - [Deprecated (PlatformName.iOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 11)] - [Deprecated (PlatformName.TvOS, 9, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static /* CMClockRef */ IntPtr CMTimebaseGetMasterClock (/* CMTimebaseRef */ IntPtr timebase); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -410,10 +333,6 @@ public double Rate { [ObsoletedOSPlatform ("ios9.0", "Use 'CopyMasterClock' instead.")] [ObsoletedOSPlatform ("tvos9.0", "Use 'CopyMasterClock' instead.")] [ObsoletedOSPlatform ("maccatalyst13.0", "Use 'CopyMasterClock' instead.")] -#else - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CopyMasterClock' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CopyMasterClock' instead.")] -#endif public CMClock? GetMasterClock () { var ptr = CMTimebaseGetMasterClock (Handle); @@ -423,7 +342,6 @@ public double Rate { return new CMClock (ptr, false); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -432,15 +350,9 @@ public double Rate { [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.11")] [ObsoletedOSPlatform ("ios9.0")] -#else - [Deprecated (PlatformName.iOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 11)] - [Deprecated (PlatformName.TvOS, 9, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static /* CMClockOrTimebaseRef */ IntPtr CMTimebaseGetMaster (/* CMTimebaseRef */ IntPtr timebase); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -449,10 +361,6 @@ public double Rate { [ObsoletedOSPlatform ("ios9.0", "Use 'CopyMaster' instead.")] [ObsoletedOSPlatform ("tvos9.0", "Use 'CopyMaster' instead.")] [ObsoletedOSPlatform ("maccatalyst13.0", "Use 'CopyMaster' instead.")] -#else - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CopyMaster' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CopyMaster' instead.")] -#endif public CMClockOrTimebase? GetMaster () { var ptr = CMTimebaseGetMaster (Handle); @@ -462,7 +370,6 @@ public double Rate { return new CMClockOrTimebase (ptr, false); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -471,15 +378,9 @@ public double Rate { [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.11")] [ObsoletedOSPlatform ("ios9.0")] -#else - [Deprecated (PlatformName.iOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 11)] - [Deprecated (PlatformName.TvOS, 9, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static /* CMClockRef */ IntPtr CMTimebaseGetUltimateMasterClock (/* CMTimebaseRef */ IntPtr timebase); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -488,10 +389,6 @@ public double Rate { [ObsoletedOSPlatform ("ios9.0", "Use 'CopyUltimateMasterClock' instead.")] [ObsoletedOSPlatform ("tvos9.0", "Use 'CopyUltimateMasterClock' instead.")] [ObsoletedOSPlatform ("maccatalyst13.0", "Use 'CopyUltimateMasterClock' instead.")] -#else - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CopyUltimateMasterClock' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CopyUltimateMasterClock' instead.")] -#endif public CMClock? GetUltimateMasterClock () { var ptr = CMTimebaseGetUltimateMasterClock (Handle); @@ -596,7 +493,6 @@ public CMTimebaseError SetTimerToFireImmediately (NSTimer timer) return CMTimebaseSetTimerToFireImmediately (Handle, timer.Handle); } -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -604,15 +500,9 @@ public CMTimebaseError SetTimerToFireImmediately (NSTimer timer) [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios8.0")] -#else - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static CMTimebaseError CMTimebaseSetMasterTimebase (/* CMTimebaseRef* */ IntPtr timebase, /* CMTimebaseRef* */ IntPtr newMasterTimebase); -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -621,11 +511,6 @@ public CMTimebaseError SetTimerToFireImmediately (NSTimer timer) [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios8.0")] -#else - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] -#endif public CMTimebaseError SetMasterTimebase (CMTimebase newMasterTimebase) { if (newMasterTimebase is null) @@ -634,7 +519,6 @@ public CMTimebaseError SetMasterTimebase (CMTimebase newMasterTimebase) return CMTimebaseSetMasterTimebase (Handle, newMasterTimebase.Handle); } -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -643,15 +527,9 @@ public CMTimebaseError SetMasterTimebase (CMTimebase newMasterTimebase) [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios8.0")] -#else - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static CMTimebaseError CMTimebaseSetMasterClock (/* CMTimebaseRef* */ IntPtr timebase, /* CMClockRef* */ IntPtr newMasterClock); -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -660,11 +538,6 @@ public CMTimebaseError SetMasterTimebase (CMTimebase newMasterTimebase) [ObsoletedOSPlatform ("tvos9.0")] [ObsoletedOSPlatform ("macos10.10")] [ObsoletedOSPlatform ("ios8.0")] -#else - [Deprecated (PlatformName.iOS, 8, 0)] - [Deprecated (PlatformName.TvOS, 9, 0)] - [Deprecated (PlatformName.MacOSX, 10, 10)] -#endif public CMTimebaseError SetMasterClock (CMClock newMasterClock) { if (newMasterClock is null) @@ -748,7 +621,6 @@ bool IsDeprecated () return new CMClock (ptr, deprecated); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] @@ -756,16 +628,9 @@ bool IsDeprecated () [ObsoletedOSPlatform ("macos10.11", "Use 'CMTimebaseGetMasterTimebase' instead.")] [ObsoletedOSPlatform ("ios9.0", "Use 'CMTimebaseGetMasterTimebase' instead.")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [NoMacCatalyst] - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CMTimebaseGetMasterTimebase' instead.")] - [Deprecated (PlatformName.TvOS, 9, 0, message: "Use 'CMTimebaseGetMasterTimebase' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CMTimebaseGetMasterTimebase' instead.")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern unsafe /* CMTimebaseRef */ IntPtr CMTimebaseCopyMasterTimebase (/* CMTimebaseRef */ IntPtr timebase); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] @@ -774,15 +639,9 @@ bool IsDeprecated () [ObsoletedOSPlatform ("tvos9.0", "Use 'CMTimebaseGetMasterClock' instead.")] [ObsoletedOSPlatform ("macos10.11", "Use 'CMTimebaseGetMasterClock' instead.")] [ObsoletedOSPlatform ("ios9.0", "Use 'CMTimebaseGetMasterClock' instead.")] -#else - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CMTimebaseGetMasterClock' instead.")] - [Deprecated (PlatformName.TvOS, 9, 0, message: "Use 'CMTimebaseGetMasterClock' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CMTimebaseGetMasterClock' instead.")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern unsafe /* CMClockRef */ IntPtr CMTimebaseCopyMasterClock (/* CMTimebaseRef */ IntPtr timebase); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] @@ -790,16 +649,9 @@ bool IsDeprecated () [ObsoletedOSPlatform ("macos10.11", "Use 'CMTimebaseGetMaster' instead.")] [ObsoletedOSPlatform ("ios9.0", "Use 'CMTimebaseGetMaster' instead.")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [NoMacCatalyst] - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CMTimebaseGetMaster' instead.")] - [Deprecated (PlatformName.TvOS, 9, 0, message: "Use 'CMTimebaseGetMaster' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CMTimebaseGetMaster' instead.")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern unsafe IntPtr /* void* */ CMTimebaseCopyMaster (/* CMTimebaseRef */ IntPtr timebase); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] @@ -807,12 +659,6 @@ bool IsDeprecated () [ObsoletedOSPlatform ("macos10.11", "Use 'CMTimebaseGetUltimateMasterClock' instead.")] [ObsoletedOSPlatform ("ios9.0", "Use 'CMTimebaseGetUltimateMasterClock' instead.")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [NoMacCatalyst] - [Deprecated (PlatformName.iOS, 9, 0, message: "Use 'CMTimebaseGetUltimateMasterClock' instead.")] - [Deprecated (PlatformName.TvOS, 9, 0, message: "Use 'CMTimebaseGetUltimateMasterClock' instead.")] - [Deprecated (PlatformName.MacOSX, 10, 11, message: "Use 'CMTimebaseGetUltimateMasterClock' instead.")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern unsafe /* CMClockRef */ IntPtr CMTimebaseCopyUltimateMasterClock (/* CMTimebaseRef */ IntPtr timebase); #endif @@ -826,20 +672,11 @@ bool IsDeprecated () #endif // !COREBUILD } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMClockOrTimebase : NativeObject { -#if !NET - public CMClockOrTimebase (NativeHandle handle) - : base (handle, false) - { - } -#endif - [Preserve (Conditional = true)] internal CMClockOrTimebase (NativeHandle handle, bool owns) : base (handle, owns) @@ -926,42 +763,24 @@ public static bool MightDrift (CMClockOrTimebase clockOrTimebaseA, CMClockOrTime return CMSyncMightDrift (clockOrTimebaseA.Handle, clockOrTimebaseB.Handle) != 0; } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern /* CMTimebase */ IntPtr CMTimebaseCopySourceTimebase (/* CMTimebase */ IntPtr timebase); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern int CMTimebaseSetSourceTimebase (/* CMTimebase */ IntPtr timebase, /* CMTimebase */ IntPtr newSourceTimebase); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif public CMTimebase? SourceTimebase { get { var source = CMTimebaseCopySourceTimebase (Handle); @@ -972,42 +791,24 @@ public CMTimebase? SourceTimebase { } } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern /* CMClock */ IntPtr CMTimebaseCopySourceClock (/* CMTimebase */ IntPtr timebase); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern int CMTimebaseSetSourceClock (/* CMTimebase */ IntPtr timebase, /* CMClock */ IntPtr newSourceClock); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif public CMClock? SourceClock { get { var clock = CMTimebaseCopySourceClock (Handle); @@ -1018,29 +819,17 @@ public CMClock? SourceClock { } } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern /* CMClock */ IntPtr CMTimebaseCopyUltimateSourceClock (/* CMTimebase */ IntPtr timebase); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif public CMClock? UltimateSourceClock { get { var clock = CMTimebaseCopyUltimateSourceClock (Handle); diff --git a/src/CoreMedia/CMTextMarkupAttributes.cs b/src/CoreMedia/CMTextMarkupAttributes.cs index 4f6618c210df..736a551fd391 100644 --- a/src/CoreMedia/CMTextMarkupAttributes.cs +++ b/src/CoreMedia/CMTextMarkupAttributes.cs @@ -38,12 +38,10 @@ namespace CoreMedia { // Convenience structure -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct TextMarkupColor { public TextMarkupColor (float red, float green, float blue, float alpha) : this () @@ -69,12 +67,10 @@ public TextMarkupColor (float red, float green, float blue, float alpha) public float Alpha { get; private set; } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CMTextMarkupAttributes : DictionaryContainer { public CMTextMarkupAttributes () { diff --git a/src/CoreMedia/CMTime.cs b/src/CoreMedia/CMTime.cs index ab1e9ddfb55f..2c50d81c3db3 100644 --- a/src/CoreMedia/CMTime.cs +++ b/src/CoreMedia/CMTime.cs @@ -17,12 +17,10 @@ namespace CoreMedia { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif [StructLayout (LayoutKind.Sequential)] public partial struct CMTime { // CMTimeFlags -> uint32_t -> CMTime.h @@ -194,11 +192,7 @@ public override bool Equals (object? obj) public override int GetHashCode () { -#if NET return HashCode.Combine (Value, TimeScale, TimeFlags, TimeEpoch); -#else - return Value.GetHashCode () ^ TimeScale.GetHashCode () ^ TimeFlags.GetHashCode () ^ TimeEpoch.GetHashCode (); -#endif } [DllImport (Constants.CoreMediaLibrary)] @@ -233,21 +227,17 @@ public static CMTime Multiply (CMTime time, double multiplier) return CMTimeMultiplyByFloat64 (time, multiplier); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static CMTime CMTimeMultiplyByRatio (CMTime time, /* int32_t */ int multiplier, /* int32_t */ int divisor); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMTime Multiply (CMTime time, int multiplier, int divisor) { return CMTimeMultiplyByRatio (time, multiplier, divisor); @@ -314,21 +304,17 @@ public static CMTime GetMinimum (CMTime time1, CMTime time2) return CMTimeMinimum (time1, time2); } -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreMediaLibrary)] extern static CMTime CMTimeFoldIntoRange (CMTime time, CMTimeRange foldRange); -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] -#endif public static CMTime Fold (CMTime time, CMTimeRange foldRange) { return CMTimeFoldIntoRange (time, foldRange); diff --git a/src/CoreMedia/CoreMedia.cs b/src/CoreMedia/CoreMedia.cs index 727efb51e79d..a9643860d389 100644 --- a/src/CoreMedia/CoreMedia.cs +++ b/src/CoreMedia/CoreMedia.cs @@ -19,12 +19,10 @@ namespace CoreMedia { // CMSampleBuffer.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif [StructLayout (LayoutKind.Sequential)] public struct CMSampleTimingInfo { public CMTime Duration; @@ -33,12 +31,10 @@ public struct CMSampleTimingInfo { } // CMTimeRange.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif [StructLayout (LayoutKind.Sequential)] public struct CMTimeRange { public CMTime Start; @@ -47,28 +43,22 @@ public struct CMTimeRange { public static readonly CMTimeRange Zero; public static readonly CMTimeRange InvalidRange; -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static readonly CMTimeRange InvalidMapping; -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static NSString? TimeMappingSourceKey { get; private set; } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static NSString? TimeMappingTargetKey { get; private set; } static CMTimeRange () @@ -91,127 +81,103 @@ static CMTimeRange () } // CMTimeRange.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif [StructLayout (LayoutKind.Sequential)] public struct CMTimeMapping { public CMTimeRange Source; public CMTimeRange Target; #if !COREBUILD -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMTimeMapping Create (CMTimeRange source, CMTimeRange target) { return CMTimeMappingMake (source, target); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMTimeMapping CreateEmpty (CMTimeRange target) { return CMTimeMappingMakeEmpty (target); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public static CMTimeMapping CreateFromDictionary (NSDictionary dict) { return CMTimeMappingMakeFromDictionary (dict.Handle); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public NSDictionary AsDictionary () { return new NSDictionary (CMTimeMappingCopyAsDictionary (this, IntPtr.Zero), true); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public string? Description { get { return CFString.FromHandle (CMTimeMappingCopyDescription (IntPtr.Zero, this), true); } } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern CMTimeMapping CMTimeMappingMake (CMTimeRange source, CMTimeRange target); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern CMTimeMapping CMTimeMappingMakeEmpty (CMTimeRange target); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern IntPtr /* CFDictionaryRef* */ CMTimeMappingCopyAsDictionary (CMTimeMapping mapping, IntPtr allocator); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern CMTimeMapping CMTimeMappingMakeFromDictionary (/* CFDictionaryRef* */ IntPtr dict); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreMediaLibrary)] static extern IntPtr /* CFStringRef* */ CMTimeMappingCopyDescription (IntPtr allocator, CMTimeMapping mapping); #endif // !COREBUILD } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif [StructLayout (LayoutKind.Sequential)] public struct CMTimeScale { // CMTime.h @@ -230,12 +196,10 @@ public CMTimeScale (int value) } // CMVideoDimensions => int32_t width + int32_t height -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CMVideoDimensions { public int Width; public int Height; diff --git a/src/CoreVideo/CVBuffer.cs b/src/CoreVideo/CVBuffer.cs index 8eebf4912d78..a2ff572b7b52 100644 --- a/src/CoreVideo/CVBuffer.cs +++ b/src/CoreVideo/CVBuffer.cs @@ -35,21 +35,15 @@ using ObjCRuntime; using Foundation; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { // CVBuffer.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public partial class CVBuffer : NativeObject { #if !COREBUILD [Preserve (Conditional = true)] @@ -93,7 +87,6 @@ public void RemoveAttachment (NSString key) CVBufferRemoveAttachment (Handle, key.Handle); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -102,12 +95,6 @@ public void RemoveAttachment (NSString key) [ObsoletedOSPlatform ("tvos15.0")] [ObsoletedOSPlatform ("maccatalyst15.0")] [ObsoletedOSPlatform ("ios15.0")] -#else - [Deprecated (PlatformName.MacOSX, 12, 0)] - [Deprecated (PlatformName.iOS, 15, 0)] - [Deprecated (PlatformName.TvOS, 15, 0)] - [Deprecated (PlatformName.MacCatalyst, 15, 0)] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe extern static /* CFTypeRef */ IntPtr CVBufferGetAttachment (/* CVBufferRef */ IntPtr buffer, /* CFStringRef */ IntPtr key, CVAttachmentMode* attachmentMode); @@ -119,16 +106,10 @@ public void RemoveAttachment (NSString key) // The new method is the same as the old one but changing the ownership from Get to Copy, so we will use the new version if possible since the // older method has been deprecatd. -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe extern static /* CFTypeRef */ IntPtr CVBufferCopyAttachment (/* CVBufferRef */ IntPtr buffer, /* CFStringRef */ IntPtr key, CVAttachmentMode* attachmentMode); @@ -163,7 +144,6 @@ unsafe static IntPtr CVBufferCopyAttachment (IntPtr buffer, IntPtr key, out CVAt } #endif -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -172,25 +152,13 @@ unsafe static IntPtr CVBufferCopyAttachment (IntPtr buffer, IntPtr key, out CVAt [ObsoletedOSPlatform ("tvos15.0")] [ObsoletedOSPlatform ("maccatalyst15.0")] [ObsoletedOSPlatform ("ios15.0")] -#else - [Deprecated (PlatformName.MacOSX, 12, 0)] - [Deprecated (PlatformName.iOS, 15, 0)] - [Deprecated (PlatformName.TvOS, 15, 0)] - [Deprecated (PlatformName.MacCatalyst, 15, 0)] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static /* CFDictionaryRef */ IntPtr CVBufferGetAttachments (/* CVBufferRef */ IntPtr buffer, CVAttachmentMode attachmentMode); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static /* CFDictionaryRef */ IntPtr CVBufferCopyAttachments (/* CVBufferRef */ IntPtr buffer, CVAttachmentMode attachmentMode); @@ -247,29 +215,17 @@ public void SetAttachments (NSDictionary theAttachments, CVAttachmentMode attach CVBufferSetAttachments (Handle, theAttachments.Handle, attachmentMode); } -#if NET [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] -#else - [iOS (15, 0)] - [TV (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreVideoLibrary)] static extern byte CVBufferHasAttachment (/* CVBufferRef */ IntPtr buffer, /* CFStringRef */ IntPtr key); -#if NET [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] -#else - [iOS (15, 0)] - [TV (15, 0)] - [MacCatalyst (15, 0)] -#endif public bool HasAttachment (NSString key) { if (key is null) diff --git a/src/CoreVideo/CVDisplayLink.cs b/src/CoreVideo/CVDisplayLink.cs index b8059e928234..587461ba75eb 100644 --- a/src/CoreVideo/CVDisplayLink.cs +++ b/src/CoreVideo/CVDisplayLink.cs @@ -35,25 +35,12 @@ using Foundation; using OpenGL; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { -#if NET [SupportedOSPlatform ("macos")] -#endif public class CVDisplayLink : NativeObject { GCHandle callbackHandle; - -#if !NET - public CVDisplayLink (NativeHandle handle) - : base (handle, false, true) - { - } -#endif [Preserve (Conditional=true)] internal CVDisplayLink (NativeHandle handle, bool owns) @@ -61,33 +48,19 @@ internal CVDisplayLink (NativeHandle handle, bool owns) { } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe static extern CVReturn CVDisplayLinkCreateWithCGDisplay (uint displayId, IntPtr* displayLink); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public static CVDisplayLink? CreateFromDisplayId (uint displayId, out CVReturn error) { IntPtr handle; @@ -100,46 +73,26 @@ internal CVDisplayLink (NativeHandle handle, bool owns) return new CVDisplayLink (handle, true); } -#if NET [SupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public static CVDisplayLink? CreateFromDisplayId (uint displayId) => CreateFromDisplayId (displayId, out var _); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe static extern CVReturn CVDisplayLinkCreateWithCGDisplays (uint* displayArray, nint count, IntPtr* displayLink); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds, out CVReturn error) { if (displayIds is null) @@ -158,46 +111,26 @@ internal CVDisplayLink (NativeHandle handle, bool owns) return new CVDisplayLink (handle, true); } -#if NET [SupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds) => CreateFromDisplayIds (displayIds, out var _); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe static extern CVReturn CVDisplayLinkCreateWithOpenGLDisplayMask (uint mask, IntPtr* displayLinkOut); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public static CVDisplayLink? CreateFromOpenGLMask (uint mask, out CVReturn error) { IntPtr handle; @@ -209,54 +142,32 @@ internal CVDisplayLink (NativeHandle handle, bool owns) return new CVDisplayLink (handle, true); } -#if NET [SupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public static CVDisplayLink? CreateFromOpenGLMask (uint mask) => CreateFromOpenGLMask (mask, out var _); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRetain (IntPtr handle); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRelease (IntPtr handle); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif protected internal override void Retain () { CVDisplayLinkRetain (GetCheckedHandle ()); } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif protected internal override void Release () { CVDisplayLinkRelease (GetCheckedHandle ()); @@ -272,20 +183,12 @@ protected override void Dispose (bool disposing) } [DllImport (Constants.CoreVideoLibrary)] -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif unsafe extern static CVReturn CVDisplayLinkCreateWithActiveCGDisplays (IntPtr* displayLinkOut); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif static IntPtr Create () { CVReturn ret; @@ -301,216 +204,132 @@ static IntPtr Create () } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVDisplayLink () : base (Create (), true) { } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static CVReturn CVDisplayLinkSetCurrentCGDisplay (IntPtr displayLink, int /* CGDirectDisplayID = uint32_t */ displayId); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVReturn SetCurrentDisplay (int displayId) { return CVDisplayLinkSetCurrentCGDisplay (Handle, displayId); } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static CVReturn CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext (IntPtr displayLink, IntPtr cglContext, IntPtr cglPixelFormat); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVReturn SetCurrentDisplay (CGLContext cglContext, CGLPixelFormat cglPixelFormat) { return CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext (Handle, cglContext.Handle, cglPixelFormat.Handle); } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static int /* CGDirectDisplayID = uint32_t */ CVDisplayLinkGetCurrentCGDisplay (IntPtr displayLink); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public int GetCurrentDisplay () { return CVDisplayLinkGetCurrentCGDisplay (Handle); } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static CVReturn CVDisplayLinkStart (IntPtr displayLink); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVReturn Start () { return CVDisplayLinkStart (Handle); } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static CVReturn CVDisplayLinkStop (IntPtr displayLink); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVReturn Stop () { return CVDisplayLinkStop (Handle); } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static CVTime CVDisplayLinkGetNominalOutputVideoRefreshPeriod (IntPtr displayLink); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVTime NominalOutputVideoRefreshPeriod { get { return CVDisplayLinkGetNominalOutputVideoRefreshPeriod (Handle); } } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static CVTime CVDisplayLinkGetOutputVideoLatency (IntPtr displayLink); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVTime OutputVideoLatency { get { return CVDisplayLinkGetOutputVideoLatency (Handle); } } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static double CVDisplayLinkGetActualOutputVideoRefreshPeriod (IntPtr displayLink); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public double ActualOutputVideoRefreshPeriod { get { return CVDisplayLinkGetActualOutputVideoRefreshPeriod (Handle); } } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static byte CVDisplayLinkIsRunning (IntPtr displayLink); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public bool IsRunning { get { return CVDisplayLinkIsRunning (Handle) != 0; } } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe extern static CVReturn CVDisplayLinkGetCurrentTime (IntPtr displayLink, CVTimeStamp* outTime); -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVReturn GetCurrentTime (out CVTimeStamp outTime) { CVReturn ret; @@ -525,119 +344,63 @@ public CVReturn GetCurrentTime (out CVTimeStamp outTime) public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut); delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext); -#if NET [UnmanagedCallersOnly] static unsafe CVReturn OutputCallback (IntPtr displayLink, CVTimeStamp* inNow, CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, IntPtr displayLinkContext) -#else - static CVDisplayLinkOutputCallback static_OutputCallback = new CVDisplayLinkOutputCallback (OutputCallback); -#if !MONOMAC - [MonoPInvokeCallback (typeof (CVDisplayLinkOutputCallback))] -#endif - static CVReturn OutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext) -#endif { GCHandle callbackHandle = GCHandle.FromIntPtr (displayLinkContext); DisplayLinkOutputCallback func = (DisplayLinkOutputCallback) callbackHandle.Target!; CVDisplayLink delegateDisplayLink = new CVDisplayLink(displayLink, false); -#if NET return func (delegateDisplayLink, ref System.Runtime.CompilerServices.Unsafe.AsRef (inNow), ref System.Runtime.CompilerServices.Unsafe.AsRef (inOutputTime), flagsIn, ref System.Runtime.CompilerServices.Unsafe.AsRef (flagsOut)); -#else - return func (delegateDisplayLink, ref inNow, ref inOutputTime, flagsIn, ref flagsOut); -#endif } -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] extern static unsafe CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, delegate* unmanaged function, IntPtr userInfo); -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [DllImport (Constants.CoreVideoLibrary)] - extern static CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, CVDisplayLinkOutputCallback function, IntPtr userInfo); -#endif -#if NET [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] -#endif public CVReturn SetOutputCallback (DisplayLinkOutputCallback callback) { callbackHandle = GCHandle.Alloc (callback); -#if NET unsafe { CVReturn ret = CVDisplayLinkSetOutputCallback (this.Handle, &OutputCallback, GCHandle.ToIntPtr (callbackHandle)); return ret; } -#else - CVReturn ret = CVDisplayLinkSetOutputCallback (this.Handle, static_OutputCallback, GCHandle.ToIntPtr (callbackHandle)); - return ret; -#endif - } -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif [DllImport (Constants.CoreVideoLibrary)] static extern nuint CVDisplayLinkGetTypeID (); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public static nuint GetTypeId () => CVDisplayLinkGetTypeID (); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe static extern int CVDisplayLinkTranslateTime (IntPtr displayLink, CVTimeStamp inTime, CVTimeStamp* outTime); -#if NET [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] -#else - [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] - [NoiOS] - [NoTV] - [NoMacCatalyst] -#endif public bool TryTranslateTime (CVTimeStamp inTime, ref CVTimeStamp outTime) { unsafe { diff --git a/src/CoreVideo/CVImageBuffer.cs b/src/CoreVideo/CVImageBuffer.cs index 063924e77237..bf4ed0fa31f2 100644 --- a/src/CoreVideo/CVImageBuffer.cs +++ b/src/CoreVideo/CVImageBuffer.cs @@ -32,21 +32,15 @@ using Foundation; using CoreGraphics; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { // CVImageBuffer.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public partial class CVImageBuffer : CVBuffer { #if !COREBUILD [Preserve (Conditional = true)] @@ -96,16 +90,11 @@ public bool IsFlipped { [DllImport (Constants.CoreVideoLibrary)] extern static /* CGColorSpaceRef */ IntPtr CVImageBufferGetColorSpace (/* CVImageBufferRef */ IntPtr imageBuffer); -#if NET [UnsupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [ObsoletedOSPlatform ("macos10.4")] -#else - [Deprecated (PlatformName.MacOSX, 10, 4)] - [Unavailable (PlatformName.iOS)] -#endif public CGColorSpace? ColorSpace { get { var h = CVImageBufferGetColorSpace (Handle); @@ -127,123 +116,99 @@ public CGColorSpace? ColorSpace { } #endif -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static int CVYCbCrMatrixGetIntegerCodePointForString (IntPtr yCbCrMatrixString); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static int GetCodePoint (CVImageBufferYCbCrMatrix yCbCrMatrix) { return CVYCbCrMatrixGetIntegerCodePointForString (yCbCrMatrix.GetConstant ()!.Handle); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static int CVColorPrimariesGetIntegerCodePointForString (IntPtr colorPrimariesString); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static int GetCodePoint (CVImageBufferColorPrimaries color) { return CVColorPrimariesGetIntegerCodePointForString (color.GetConstant ()!.Handle); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static int CVTransferFunctionGetIntegerCodePointForString (IntPtr colorPrimariesString); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static int GetCodePoint (CVImageBufferTransferFunction function) { return CVTransferFunctionGetIntegerCodePointForString (function.GetConstant ()!.Handle); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static IntPtr CVYCbCrMatrixGetStringForIntegerCodePoint (int yCbCrMatrixCodePoint); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static CVImageBufferYCbCrMatrix GetYCbCrMatrixOption (int yCbCrMatrixCodePoint) { var ret = Runtime.GetNSObject (CVYCbCrMatrixGetStringForIntegerCodePoint (yCbCrMatrixCodePoint)); return CVImageBufferYCbCrMatrixExtensions.GetValue (ret); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static IntPtr CVColorPrimariesGetStringForIntegerCodePoint (int colorPrimariesCodePoint); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static CVImageBufferColorPrimaries GetColorPrimariesOption (int colorPrimariesCodePoint) { var ret = Runtime.GetNSObject (CVColorPrimariesGetStringForIntegerCodePoint (colorPrimariesCodePoint)); return CVImageBufferColorPrimariesExtensions.GetValue (ret); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static IntPtr CVTransferFunctionGetStringForIntegerCodePoint (int transferFunctionCodePoint); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static CVImageBufferTransferFunction GetTransferFunctionOption (int transferFunctionCodePoint) { var ret = Runtime.GetNSObject (CVTransferFunctionGetStringForIntegerCodePoint (transferFunctionCodePoint)); diff --git a/src/CoreVideo/CVMetalBuffer.cs b/src/CoreVideo/CVMetalBuffer.cs index 8c5651e52bb4..c27698ebff33 100644 --- a/src/CoreVideo/CVMetalBuffer.cs +++ b/src/CoreVideo/CVMetalBuffer.cs @@ -7,24 +7,16 @@ using Metal; using ObjCRuntime; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { /// A CVPixelBuffer wrapped in a Metal based buffer. /// This type is used to provide buffers to Metal. -#if NET [SupportedOSPlatform ("ios18.0")] [SupportedOSPlatform ("maccatalyst18.0")] [SupportedOSPlatform ("macos15.0")] [SupportedOSPlatform ("tvos18.0")] -#else - [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] -#endif public class CVMetalBuffer : CVBuffer { #if !COREBUILD [Preserve (Conditional = true)] diff --git a/src/CoreVideo/CVMetalBufferCache.cs b/src/CoreVideo/CVMetalBufferCache.cs index 8c2d8c0547e7..5efe17f7d3a9 100644 --- a/src/CoreVideo/CVMetalBufferCache.cs +++ b/src/CoreVideo/CVMetalBufferCache.cs @@ -10,23 +10,15 @@ using Metal; using ObjCRuntime; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { /// A cache used to manage instances. -#if NET [SupportedOSPlatform ("ios18.0")] [SupportedOSPlatform ("maccatalyst18.0")] [SupportedOSPlatform ("macos15.0")] [SupportedOSPlatform ("tvos18.0")] -#else - [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] -#endif public class CVMetalBufferCache : NativeObject { #if !COREBUILD [Preserve (Conditional = true)] diff --git a/src/CoreVideo/CVMetalTexture.cs b/src/CoreVideo/CVMetalTexture.cs index 42e8162a15cb..112d089c79be 100644 --- a/src/CoreVideo/CVMetalTexture.cs +++ b/src/CoreVideo/CVMetalTexture.cs @@ -16,22 +16,14 @@ using Foundation; using Metal; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#else - [MacCatalyst (15, 0)] -#endif public class CVMetalTexture : NativeObject { [Preserve (Conditional = true)] internal CVMetalTexture (NativeHandle handle, bool owns) diff --git a/src/CoreVideo/CVMetalTextureCache.cs b/src/CoreVideo/CVMetalTextureCache.cs index 1e7579b34b8f..2725c5b64b00 100644 --- a/src/CoreVideo/CVMetalTextureCache.cs +++ b/src/CoreVideo/CVMetalTextureCache.cs @@ -15,10 +15,6 @@ using Foundation; using Metal; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { diff --git a/src/CoreVideo/CVOpenGLESTexture.cs b/src/CoreVideo/CVOpenGLESTexture.cs index c8c08a9ba53e..edffa74d5d38 100644 --- a/src/CoreVideo/CVOpenGLESTexture.cs +++ b/src/CoreVideo/CVOpenGLESTexture.cs @@ -27,15 +27,10 @@ namespace CoreVideo { // CVOpenGLESTexture.h -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("ios")] [ObsoletedOSPlatform ("tvos12.0", "Use 'CVMetalTexture' instead.")] [ObsoletedOSPlatform ("ios12.0", "Use 'CVMetalTexture' instead.")] -#else - [Deprecated (PlatformName.iOS, 12,0, message: "Use 'CVMetalTexture' instead.")] - [Deprecated (PlatformName.TvOS, 12,0, message: "Use 'CVMetalTexture' instead.")] -#endif public class CVOpenGLESTexture : INativeObject, IDisposable { internal IntPtr handle; diff --git a/src/CoreVideo/CVOpenGLESTextureCache.cs b/src/CoreVideo/CVOpenGLESTextureCache.cs index 853efb1d7d09..5d0f7d9aa779 100644 --- a/src/CoreVideo/CVOpenGLESTextureCache.cs +++ b/src/CoreVideo/CVOpenGLESTextureCache.cs @@ -26,15 +26,10 @@ namespace CoreVideo { // CVOpenGLESTextureCache.h -#if NET [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("ios")] [ObsoletedOSPlatform ("tvos12.0", "Use 'CVMetalTextureCache' instead.")] [ObsoletedOSPlatform ("ios12.0", "Use 'CVMetalTextureCache' instead.")] -#else - [Deprecated (PlatformName.iOS, 12,0, message: "Use 'CVMetalTextureCache' instead.")] - [Deprecated (PlatformName.TvOS, 12,0, message: "Use 'CVMetalTextureCache' instead.")] -#endif public class CVOpenGLESTextureCache : INativeObject, IDisposable { internal IntPtr handle; diff --git a/src/CoreVideo/CVPixelBuffer.cs b/src/CoreVideo/CVPixelBuffer.cs index aeae3ddc1fae..446e346c953f 100644 --- a/src/CoreVideo/CVPixelBuffer.cs +++ b/src/CoreVideo/CVPixelBuffer.cs @@ -16,20 +16,14 @@ using CFDictionaryRef = System.IntPtr; using CVPixelBufferRef = System.IntPtr; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public partial class CVPixelBuffer : CVImageBuffer { #if !COREBUILD [DllImport (Constants.CoreVideoLibrary, EntryPoint = "CVPixelBufferGetTypeID")] @@ -111,29 +105,17 @@ unsafe extern static CVReturn CVPixelBufferCreateResolvedAttributesDictionary ( return Runtime.GetNSObject (resolvedDictionaryOut); } -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [NoMacCatalyst] -#endif [DllImport (Constants.CoreVideoLibrary)] static extern CFDictionaryRef CVPixelBufferCopyCreationAttributes (CVPixelBufferRef pixelBuffer); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [NoMacCatalyst] -#endif public CVPixelBufferAttributes? GetPixelBufferCreationAttributes () { var attrs = Runtime.GetNSObject (CVPixelBufferCopyCreationAttributes (Handle), true); @@ -149,15 +131,7 @@ delegate void CVPixelBufferReleaseBytesCallback ( /* void * CV_NULLABLE */ IntPtr releaseRefCon, /* const void * CV_NULLABLE */ IntPtr baseAddress); -#if !NET - static CVPixelBufferReleaseBytesCallback releaseBytesCallback = new CVPixelBufferReleaseBytesCallback (ReleaseBytesCallback); -#endif - -#if NET [UnmanagedCallersOnly] -#else - [MonoPInvokeCallbackAttribute (typeof (CVPixelBufferReleaseBytesCallback))] -#endif static void ReleaseBytesCallback (IntPtr releaseRefCon, IntPtr baseAddress) { GCHandle handle = GCHandle.FromIntPtr (releaseRefCon); @@ -172,11 +146,7 @@ static unsafe extern CVReturn CVPixelBufferCreateWithBytes ( /* OSType */ CVPixelFormatType pixelFormatType, /* void * CV_NONNULL */ IntPtr baseAddress, /* size_t */ nint bytesPerRow, -#if NET delegate* unmanaged releaseCallback, -#else - CVPixelBufferReleaseBytesCallback /* CV_NULLABLE */ releaseCallback, -#endif /* void * CV_NULLABLE */ IntPtr releaseRefCon, /* CFDictionaryRef CV_NULLABLE */ IntPtr pixelBufferAttributes, /* CV_RETURNS_RETAINED_PARAMETER CVPixelBufferRef CV_NULLABLE * CV_NONNULL */ IntPtr* pixelBufferOut);// __OSX_AVAILABLE_STARTING(__MAC_10_4,__IPHONE_4_0); @@ -207,11 +177,7 @@ static unsafe extern CVReturn CVPixelBufferCreateWithBytes ( pixelFormatType, gchandle.AddrOfPinnedObject (), bytesPerRow, -#if NET &ReleaseBytesCallback, -#else - releaseBytesCallback, -#endif GCHandle.ToIntPtr (gchandle), DictionaryContainerHelper.GetHandle (pixelBufferAttributes), &handle); @@ -237,9 +203,6 @@ delegate void CVPixelBufferReleasePlanarBytesCallback ( /* size_t */ nint dataSize, /* size_t */ nint numberOfPlanes, /* const void* */IntPtr planeAddresses); -#if !NET - static CVPixelBufferReleasePlanarBytesCallback releasePlanarBytesCallback = new CVPixelBufferReleasePlanarBytesCallback (ReleasePlanarBytesCallback); -#endif static void ReleasePlanarBytesCallbackImpl (IntPtr releaseRefCon, IntPtr dataPtr, nint dataSize, nint numberOfPlanes, IntPtr planeAddresses) { @@ -249,11 +212,8 @@ static void ReleasePlanarBytesCallbackImpl (IntPtr releaseRefCon, IntPtr dataPtr data.dataHandles [i].Free (); handle.Free (); } -#if NET + [UnmanagedCallersOnly] -#else - [MonoPInvokeCallbackAttribute (typeof (CVPixelBufferReleasePlanarBytesCallback))] -#endif static void ReleasePlanarBytesCallback (IntPtr releaseRefCon, IntPtr dataPtr, nint dataSize, nint numberOfPlanes, IntPtr planeAddresses) { ReleasePlanarBytesCallbackImpl (releaseRefCon, dataPtr, dataSize, numberOfPlanes, planeAddresses); @@ -272,11 +232,7 @@ static unsafe extern CVReturn CVPixelBufferCreateWithPlanarBytes ( /* size_t[] */ nint* planeWidth, /* size_t[] */ nint* planeHeight, /* size_t[] */ nint* planeBytesPerRow, -#if NET delegate* unmanaged/* CV_NULLABLE */ releaseCallback, -#else - CVPixelBufferReleasePlanarBytesCallback /* CV_NULLABLE */ releaseCallback, -#endif /* void * CV_NULLABLE */ IntPtr releaseRefCon, /* CFDictionaryRef CV_NULLABLE */ IntPtr pixelBufferAttributes, /* CV_RETURNS_RETAINED_PARAMETER CVPixelBufferRef CV_NULLABLE * CV_NONNULL */ IntPtr* pixelBufferOut); // __OSX_AVAILABLE_STARTING(__MAC_10_4,__IPHONE_4_0); @@ -340,11 +296,7 @@ static unsafe extern CVReturn CVPixelBufferCreateWithPlanarBytes ( planeWidthsPtr, planeHeightsPtr, planeBytesPerRowPtr, -#if NET &ReleasePlanarBytesCallback, -#else - releasePlanarBytesCallback, -#endif data_handle_ptr, DictionaryContainerHelper.GetHandle (pixelBufferAttributes), &handle); diff --git a/src/CoreVideo/CVPixelBufferAttributes.cs b/src/CoreVideo/CVPixelBufferAttributes.cs index 3abb8e67b1ad..fb8cdc78c290 100644 --- a/src/CoreVideo/CVPixelBufferAttributes.cs +++ b/src/CoreVideo/CVPixelBufferAttributes.cs @@ -34,12 +34,10 @@ namespace CoreVideo { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CVPixelBufferAttributes : DictionaryContainer { #if !COREBUILD public CVPixelBufferAttributes () @@ -203,12 +201,10 @@ public bool? OpenGLESCompatibility { } #endif -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("macos")] -#endif public bool? MetalCompatibility { set { SetBooleanValue (CVPixelBuffer.MetalCompatibilityKey, value); diff --git a/src/CoreVideo/CVPixelBufferIOSurface.cs b/src/CoreVideo/CVPixelBufferIOSurface.cs index 18232190537c..67a77d8d1306 100644 --- a/src/CoreVideo/CVPixelBufferIOSurface.cs +++ b/src/CoreVideo/CVPixelBufferIOSurface.cs @@ -17,23 +17,19 @@ namespace CoreVideo { public partial class CVPixelBuffer : CVImageBuffer { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static IntPtr /* IOSurfaceRef */ CVPixelBufferGetIOSurface ( /* CVPixelBufferRef CV_NULLABLE */ IntPtr pixelBuffer ); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public IOSurface.IOSurface? GetIOSurface () { if (Handle == IntPtr.Zero) @@ -46,12 +42,10 @@ public partial class CVPixelBuffer : CVImageBuffer { return Runtime.GetINativeObject (ret, false); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif [DllImport (Constants.CoreVideoLibrary)] unsafe extern static CVReturn /* IOSurfaceRef */ CVPixelBufferCreateWithIOSurface ( /* CFAllocatorRef CV_NULLABLE */ IntPtr allocator, @@ -60,12 +54,10 @@ public partial class CVPixelBuffer : CVImageBuffer { /* CVPixelBufferRef CV_NULLABLE * CV_NONNULL */ IntPtr* pixelBufferOut ); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static CVPixelBuffer? Create (IOSurface.IOSurface surface, out CVReturn result, CVPixelBufferAttributes? pixelBufferAttributes = null) { if (surface is null) @@ -87,12 +79,10 @@ public partial class CVPixelBuffer : CVImageBuffer { return new CVPixelBuffer (pixelBufferPtr, true); } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static CVPixelBuffer? Create (IOSurface.IOSurface surface, CVPixelBufferAttributes? pixelBufferAttributes = null) { CVReturn result; diff --git a/src/CoreVideo/CVPixelBufferPool.cs b/src/CoreVideo/CVPixelBufferPool.cs index b571556fa5b7..e60c464d292d 100644 --- a/src/CoreVideo/CVPixelBufferPool.cs +++ b/src/CoreVideo/CVPixelBufferPool.cs @@ -16,21 +16,15 @@ using ObjCRuntime; using Foundation; -#if !NET -using NativeHandle = System.IntPtr; -#endif - #nullable enable namespace CoreVideo { // CVPixelBufferPool.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public partial class CVPixelBufferPool : NativeObject { #if !COREBUILD [Preserve (Conditional = true)] @@ -162,23 +156,18 @@ public CVPixelBufferPool (CVPixelBufferPoolSettings? settings, CVPixelBufferAttr { } - -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif [DllImport (Constants.CoreVideoLibrary)] static extern void CVPixelBufferPoolFlush (/* CVPixelBufferPoolRef __nonnull */ IntPtr pool, CVPixelBufferPoolFlushFlags options); -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("tvos")] -#endif public void Flush (CVPixelBufferPoolFlushFlags options) { CVPixelBufferPoolFlush (Handle, options); diff --git a/src/CoreVideo/CVPixelBufferPoolSettings.cs b/src/CoreVideo/CVPixelBufferPoolSettings.cs index f11120e03e7c..adf793e21c18 100644 --- a/src/CoreVideo/CVPixelBufferPoolSettings.cs +++ b/src/CoreVideo/CVPixelBufferPoolSettings.cs @@ -35,12 +35,10 @@ namespace CoreVideo { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public class CVPixelBufferPoolSettings : DictionaryContainer { #if !COREBUILD public CVPixelBufferPoolSettings () @@ -73,12 +71,10 @@ public double? MaximumBufferAgeInSeconds { #endif } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public partial class CVPixelBufferPoolAllocationSettings : DictionaryContainer { #if !COREBUILD public CVPixelBufferPoolAllocationSettings () diff --git a/src/CoreVideo/CVPixelFormatDescription.cs b/src/CoreVideo/CVPixelFormatDescription.cs index 2011de0dd91c..4a3d82afa736 100644 --- a/src/CoreVideo/CVPixelFormatDescription.cs +++ b/src/CoreVideo/CVPixelFormatDescription.cs @@ -156,24 +156,18 @@ public partial class CVPixelFormatDescription { [Obsolete ("Use 'CVPixelFormatKeys.ContainsGrayscale' instead.")] [EditorBrowsable (EditorBrowsableState.Never)] -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("tvos")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] -#endif public static readonly NSString ContainsGrayscaleKey; [Obsolete ("Use 'CVPixelFormatKeys.ContainsSenselArray' instead.")] [EditorBrowsable (EditorBrowsableState.Never)] -#if NET [SupportedOSPlatform ("ios16.0")] [SupportedOSPlatform ("maccatalyst16.0")] [SupportedOSPlatform ("macos13.0")] [SupportedOSPlatform ("tvos16.0")] -#else - [Mac (13, 0), iOS (16, 0), TV (16, 0), MacCatalyst (16, 0)] -#endif public static readonly NSString ContainsSenselArray; #endif // !XAMCORE_5_0 @@ -288,34 +282,25 @@ public static void Register (CVPixelFormatDescription description, CVPixelFormat Register (description?.Dictionary!, pixelFormat); } -#if NET [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [iOS (15, 0), MacCatalyst (15, 0), TV (15, 0), Mac (12, 0)] -#endif [DllImport (Constants.CoreVideoLibrary)] extern static byte CVIsCompressedPixelFormatAvailable (int /* OSType = int32_t */ pixelFormat); /// Check if the specified pixel format is supported on this platform. /// The pixel format to check. /// Whether the specified pixel format is supported or not. -#if NET [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [iOS (15, 0), MacCatalyst (15, 0), TV (15, 0), Mac (12, 0)] -#endif public static bool IsPixelFormatAvailable (CVPixelFormatType pixelFormat) { return CVIsCompressedPixelFormatAvailable ((int) pixelFormat) != 0; } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -329,7 +314,7 @@ public CVFillExtendedPixelsCallBackDataStruct? FillExtendedPixelsCallbackStruct unsafe { if (bytes.Length < sizeof (CVFillExtendedPixelsCallBackDataStruct)) throw new InvalidOperationException ($"The size of the callback data structure is smaller than expected (got {bytes.Length} bytes, expected at least {sizeof (CVFillExtendedPixelsCallBackDataStruct)} bytes)"); - fixed (byte *ptr = bytes) + fixed (byte* ptr = bytes) return Marshal.PtrToStructure ((IntPtr) ptr); } } @@ -346,8 +331,6 @@ public CVFillExtendedPixelsCallBackDataStruct? FillExtendedPixelsCallbackStruct FillExtendedPixelsCallback = data; } } -#endif - #endif // !COREBUILD } } diff --git a/src/CoreVideo/CVPixelFormatType.cs b/src/CoreVideo/CVPixelFormatType.cs index 286a7776bd54..a28a7f71af74 100644 --- a/src/CoreVideo/CVPixelFormatType.cs +++ b/src/CoreVideo/CVPixelFormatType.cs @@ -178,37 +178,23 @@ public enum CVPixelFormatType : uint { } #if !COREBUILD -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public static class CVPixelFormatTypeExtensions { -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif [DllImport (Constants.CoreVideoLibrary)] static extern byte CVIsCompressedPixelFormatAvailable (uint pixelFormatType); -#if NET [SupportedOSPlatform ("tvos15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (15, 0)] - [iOS (15, 0)] - [MacCatalyst (15, 0)] -#endif public static bool IsCompressedPixelFormatAvailable (this CVPixelFormatType type) => CVIsCompressedPixelFormatAvailable ((uint) type) != 0; } diff --git a/src/CoreVideo/CVTime.cs b/src/CoreVideo/CVTime.cs index eb57463e0cee..233ad41829c8 100644 --- a/src/CoreVideo/CVTime.cs +++ b/src/CoreVideo/CVTime.cs @@ -35,12 +35,10 @@ namespace CoreVideo { // CVBase.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVTime { public /* int64_t */ long TimeValue; diff --git a/src/CoreVideo/CoreVideo.cs b/src/CoreVideo/CoreVideo.cs index d3e34b6d80e1..f5fe71e6a49d 100644 --- a/src/CoreVideo/CoreVideo.cs +++ b/src/CoreVideo/CoreVideo.cs @@ -36,58 +36,48 @@ namespace CoreVideo { // CVPixelBuffer.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVPlanarComponentInfo { public /* int32_t */ int Offset; public /* uint32_t */ uint RowBytes; } // CVPixelBuffer.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVPlanarPixelBufferInfo { public CVPlanarComponentInfo [] ComponentInfo; } // CVPixelBuffer.h -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVPlanarPixelBufferInfo_YCbCrPlanar { public CVPlanarComponentInfo ComponentInfoY; public CVPlanarComponentInfo ComponentInfoCb; public CVPlanarComponentInfo ComponentInfoCr; } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVPlanarPixelBufferInfo_YCbCrBiPlanar { public CVPlanarComponentInfo ComponentInfoY; public CVPlanarComponentInfo ComponentInfoCbCr; } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVTimeStamp { public UInt32 Version; public Int32 VideoTimeScale; @@ -100,12 +90,10 @@ public struct CVTimeStamp { public UInt64 Reserved; } -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVSMPTETime { public Int16 Subframes; public Int16 SubframeDivisor; @@ -119,12 +107,10 @@ public struct CVSMPTETime { } #if !XAMCORE_5_0 -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos")] -#endif public struct CVFillExtendedPixelsCallBackData { public nint /* CFIndex */ Version; public CVFillExtendedPixelsCallBack FillCallBack; @@ -134,7 +120,6 @@ public struct CVFillExtendedPixelsCallBackData { public delegate bool CVFillExtendedPixelsCallBack (IntPtr pixelBuffer, IntPtr refCon); #endif // !XAMCORE_5_0 -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("macos")] @@ -158,6 +143,5 @@ public unsafe bool CallFillCallback (CVPixelBuffer buffer) } #endif } -#endif } diff --git a/src/Intents/INBillTypeResolutionResult.cs b/src/Intents/INBillTypeResolutionResult.cs deleted file mode 100644 index ea6e7a3a7e48..000000000000 --- a/src/Intents/INBillTypeResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INBillTypeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INBillTypeResolutionResult { - - public static INBillTypeResolutionResult GetSuccess (INBillType resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return SuccessWithResolvedBillType (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INBillTypeResolutionResult GetConfirmationRequired (INBillType valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return ConfirmationRequiredWithBillTypeToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -} -#endif diff --git a/src/Intents/INCallRecord.cs b/src/Intents/INCallRecord.cs index fdfac385485f..9e65e8fbe9e0 100644 --- a/src/Intents/INCallRecord.cs +++ b/src/Intents/INCallRecord.cs @@ -12,6 +12,8 @@ using Foundation; using ObjCRuntime; +#nullable enable + namespace Intents { public partial class INCallRecord { diff --git a/src/Intents/INCallRecordTypeResolutionResult.cs b/src/Intents/INCallRecordTypeResolutionResult.cs deleted file mode 100644 index 9246df1f7567..000000000000 --- a/src/Intents/INCallRecordTypeResolutionResult.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// INCallRecordTypeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INCallRecordTypeResolutionResult { - - public static INCallRecordTypeResolutionResult GetSuccess (INCallRecordType resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#elif MONOMAC - if (SystemVersion.CheckmacOS (10, 13)) -#endif - return SuccessWithResolvedCallRecordType (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INCallRecordTypeResolutionResult GetConfirmationRequired (INCallRecordType valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#elif MONOMAC - if (SystemVersion.CheckmacOS (10, 13)) -#endif - return ConfirmationRequiredWithCallRecordTypeToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -} -#endif diff --git a/src/Intents/INCarAirCirculationModeResolutionResult.cs b/src/Intents/INCarAirCirculationModeResolutionResult.cs deleted file mode 100644 index 8aa11697ff70..000000000000 --- a/src/Intents/INCarAirCirculationModeResolutionResult.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// INCarAirCirculationModeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INCarAirCirculationModeResolutionResult { - - public static INCarAirCirculationModeResolutionResult GetSuccess (INCarAirCirculationMode resolvedValue) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return SuccessWithResolvedCarAirCirculationMode (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); -#endif - } - - public static INCarAirCirculationModeResolutionResult GetConfirmationRequired (INCarAirCirculationMode valueToConfirm) - { - -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return ConfirmationRequiredWithCarAirCirculationModeToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); -#endif - } - } -} -#endif diff --git a/src/Intents/INCarAirCirculationModeResolutionResult.watchOS.cs b/src/Intents/INCarAirCirculationModeResolutionResult.watchOS.cs deleted file mode 100644 index 758ad7939291..000000000000 --- a/src/Intents/INCarAirCirculationModeResolutionResult.watchOS.cs +++ /dev/null @@ -1,60 +0,0 @@ -#if !NET -using System; -using System.Drawing; -using System.Diagnostics; -using System.ComponentModel; -using System.Threading.Tasks; -using System.Runtime.InteropServices; -using UIKit; -using SceneKit; -using Contacts; -using CoreVideo; -using SpriteKit; -using Foundation; -using ObjCRuntime; -using CoreGraphics; -using CoreLocation; -using AVFoundation; -using CoreFoundation; - -namespace Intents { - [Register ("INCarAirCirculationModeResolutionResult", true)] - [Obsolete (Constants.UnavailableOnWatchOS)] - public unsafe partial class INCarAirCirculationModeResolutionResult : INIntentResolutionResult { - public override IntPtr ClassHandle { get { throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); } } - - protected INCarAirCirculationModeResolutionResult (NSObjectFlag t) : base (t) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - protected internal INCarAirCirculationModeResolutionResult (IntPtr handle) : base (handle) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public static INCarAirCirculationModeResolutionResult ConfirmationRequiredWithCarAirCirculationModeToConfirm (INCarAirCirculationMode carAirCirculationModeToConfirm) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public new static INCarAirCirculationModeResolutionResult NeedsValue { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarAirCirculationModeResolutionResult NotRequired { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarAirCirculationModeResolutionResult Unsupported { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - } /* class INCarAirCirculationModeResolutionResult */ -} -#endif // !NET diff --git a/src/Intents/INCarAudioSourceResolutionResult.cs b/src/Intents/INCarAudioSourceResolutionResult.cs deleted file mode 100644 index 993740760199..000000000000 --- a/src/Intents/INCarAudioSourceResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INCarAudioSourceResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INCarAudioSourceResolutionResult { - - public static INCarAudioSourceResolutionResult GetSuccess (INCarAudioSource resolvedValue) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return SuccessWithResolvedCarAudioSource (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); -#endif - } - - public static INCarAudioSourceResolutionResult GetConfirmationRequired (INCarAudioSource valueToConfirm) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return ConfirmationRequiredWithCarAudioSourceToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); -#endif - } - } -} -#endif diff --git a/src/Intents/INCarAudioSourceResolutionResult.watchOS.cs b/src/Intents/INCarAudioSourceResolutionResult.watchOS.cs deleted file mode 100644 index 803304ccc37a..000000000000 --- a/src/Intents/INCarAudioSourceResolutionResult.watchOS.cs +++ /dev/null @@ -1,56 +0,0 @@ -#if !NET - -using System; -using System.Drawing; -using System.Diagnostics; -using System.ComponentModel; -using System.Threading.Tasks; -using System.Runtime.InteropServices; -using UIKit; -using SceneKit; -using Contacts; -using CoreVideo; -using SpriteKit; -using Foundation; -using ObjCRuntime; -using CoreGraphics; -using CoreLocation; -using AVFoundation; -using CoreFoundation; - -namespace Intents { - [Register ("INCarAudioSourceResolutionResult", true)] - [Obsolete (Constants.UnavailableOnWatchOS)] - public unsafe partial class INCarAudioSourceResolutionResult : INIntentResolutionResult { - public override IntPtr ClassHandle { get { throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); } } - - protected INCarAudioSourceResolutionResult (NSObjectFlag t) : base (t) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - protected internal INCarAudioSourceResolutionResult (IntPtr handle) : base (handle) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public new static INCarAudioSourceResolutionResult NeedsValue { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarAudioSourceResolutionResult NotRequired { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarAudioSourceResolutionResult Unsupported { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - } /* class INCarAudioSourceResolutionResult */ -} -#endif // !NET diff --git a/src/Intents/INCarDefrosterResolutionResult.cs b/src/Intents/INCarDefrosterResolutionResult.cs deleted file mode 100644 index 3a38cb8e4e01..000000000000 --- a/src/Intents/INCarDefrosterResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INCarDefrosterResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INCarDefrosterResolutionResult { - - public static INCarDefrosterResolutionResult GetSuccess (INCarDefroster resolvedValue) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return SuccessWithResolvedCarDefroster (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); -#endif - } - - public static INCarDefrosterResolutionResult GetConfirmationRequired (INCarDefroster valueToConfirm) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return ConfirmationRequiredWithCarDefrosterToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); -#endif - } - } -} -#endif diff --git a/src/Intents/INCarDefrosterResolutionResult.watchOS.cs b/src/Intents/INCarDefrosterResolutionResult.watchOS.cs deleted file mode 100644 index 8e73226d3770..000000000000 --- a/src/Intents/INCarDefrosterResolutionResult.watchOS.cs +++ /dev/null @@ -1,55 +0,0 @@ -#if !NET -using System; -using System.Drawing; -using System.Diagnostics; -using System.ComponentModel; -using System.Threading.Tasks; -using System.Runtime.InteropServices; -using UIKit; -using SceneKit; -using Contacts; -using CoreVideo; -using SpriteKit; -using Foundation; -using ObjCRuntime; -using CoreGraphics; -using CoreLocation; -using AVFoundation; -using CoreFoundation; - -namespace Intents { - [Register ("INCarDefrosterResolutionResult", true)] - [Obsolete (Constants.UnavailableOnWatchOS)] - public unsafe partial class INCarDefrosterResolutionResult : INIntentResolutionResult { - public override IntPtr ClassHandle { get { throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); } } - - protected INCarDefrosterResolutionResult (NSObjectFlag t) : base (t) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - protected internal INCarDefrosterResolutionResult (IntPtr handle) : base (handle) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public new static INCarDefrosterResolutionResult NeedsValue { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarDefrosterResolutionResult NotRequired { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarDefrosterResolutionResult Unsupported { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - } /* class INCarDefrosterResolutionResult */ -} -#endif // !NET diff --git a/src/Intents/INCarSeatResolutionResult.cs b/src/Intents/INCarSeatResolutionResult.cs deleted file mode 100644 index c6f1d8931445..000000000000 --- a/src/Intents/INCarSeatResolutionResult.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -// INCarSeatResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INCarSeatResolutionResult { - public static INCarSeatResolutionResult GetSuccess (INCarSeat resolvedValue) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return SuccessWithResolvedCarSeat (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); -#endif - } - - public static INCarSeatResolutionResult GetConfirmationRequired (INCarSeat valueToConfirm) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return ConfirmationRequiredWithCarSeatToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); -#endif - } - } -} -#endif diff --git a/src/Intents/INCarSeatResolutionResult.watchOS.cs b/src/Intents/INCarSeatResolutionResult.watchOS.cs deleted file mode 100644 index 0fe90458f0f4..000000000000 --- a/src/Intents/INCarSeatResolutionResult.watchOS.cs +++ /dev/null @@ -1,55 +0,0 @@ -#if !NET -using System; -using System.Drawing; -using System.Diagnostics; -using System.ComponentModel; -using System.Threading.Tasks; -using System.Runtime.InteropServices; -using UIKit; -using SceneKit; -using Contacts; -using CoreVideo; -using SpriteKit; -using Foundation; -using ObjCRuntime; -using CoreGraphics; -using CoreLocation; -using AVFoundation; -using CoreFoundation; - -namespace Intents { - [Register ("INCarSeatResolutionResult", true)] - [Obsolete (Constants.UnavailableOnWatchOS)] - public unsafe partial class INCarSeatResolutionResult : INIntentResolutionResult { - public override IntPtr ClassHandle { get { throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); } } - - protected INCarSeatResolutionResult (NSObjectFlag t) : base (t) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - protected internal INCarSeatResolutionResult (IntPtr handle) : base (handle) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public new static INCarSeatResolutionResult NeedsValue { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarSeatResolutionResult NotRequired { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INCarSeatResolutionResult Unsupported { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - } /* class INCarSeatResolutionResult */ -} -#endif // !NET diff --git a/src/Intents/INCarSignalOptionsResolutionResult.cs b/src/Intents/INCarSignalOptionsResolutionResult.cs deleted file mode 100644 index bcdc2196ffc8..000000000000 --- a/src/Intents/INCarSignalOptionsResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INCarAirCirculationModeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INCarSignalOptionsResolutionResult { - - public static INCarSignalOptionsResolutionResult GetSuccess (INCarSignalOptions resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return SuccessWithResolvedCarSignalOptions (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INCarSignalOptionsResolutionResult GetConfirmationRequired (INCarSignalOptions valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return ConfirmationRequiredWithCarSignalOptionsToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -} -#endif diff --git a/src/Intents/INCompat.cs b/src/Intents/INCompat.cs deleted file mode 100644 index c60ee73c1214..000000000000 --- a/src/Intents/INCompat.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Compatibility stubs - -#if IOS - -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - -#if !NET - public partial class INRideDriver { - - [Obsolete ("This constructor does not create a valid instance of the type")] - public INRideDriver () : base (NSObjectFlag.Empty) - { - } - } - - public partial class INRideStatus { - - [Obsolete ("This constructor does not create a valid instance of the type")] - public INRideStatus () - { - } - } - - public partial class INRestaurantGuest { - [Obsolete ("This constructor does not create a valid instance of the type")] - public INRestaurantGuest () - : base (IntPtr.Zero) // base class doesn't have a default ctor. - { - } - } -#endif -} -#endif diff --git a/src/Intents/INGetCarLockStatusIntentResponse.cs b/src/Intents/INGetCarLockStatusIntentResponse.cs deleted file mode 100644 index 4cd345ca5258..000000000000 --- a/src/Intents/INGetCarLockStatusIntentResponse.cs +++ /dev/null @@ -1,28 +0,0 @@ -// INGetCarLockStatusIntentResponse.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if IOS - -using Foundation; -using Intents; -using ObjCRuntime; - -namespace Intents { - - public partial class INGetCarLockStatusIntentResponse { - - // if/when we update the generator to allow this pattern we can move this back - // into bindings and making them virtual (not a breaking change) - - public bool? Locked { - get { return _Locked is null ? null : (bool?) _Locked.BoolValue; } - } - } -} - -#endif diff --git a/src/Intents/INGetCarPowerLevelStatusIntentResponse.cs b/src/Intents/INGetCarPowerLevelStatusIntentResponse.cs deleted file mode 100644 index 5daf8a1dd1b7..000000000000 --- a/src/Intents/INGetCarPowerLevelStatusIntentResponse.cs +++ /dev/null @@ -1,34 +0,0 @@ -// INGetCarPowerLevelStatusIntentResponse.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if IOS && !TVOS -#if !(NET && __MACOS__) - -using Foundation; -using Intents; -using ObjCRuntime; - -namespace Intents { - - public partial class INGetCarPowerLevelStatusIntentResponse { - - // if/when we update the generator to allow this pattern we can move this back - // into bindings and making them virtual (not a breaking change) - - public float? FuelPercentRemaining { - get { return _FuelPercentRemaining is null ? null : (float?) _FuelPercentRemaining.FloatValue; } - } - - public float? ChargePercentRemaining { - get { return _ChargePercentRemaining is null ? null : (float?) _ChargePercentRemaining.FloatValue; } - } - } -} - -#endif // !(NET && __MACOS__) -#endif diff --git a/src/Intents/INIntentResolutionResult.cs b/src/Intents/INIntentResolutionResult.cs index bc1efb975987..70a8232bfc98 100644 --- a/src/Intents/INIntentResolutionResult.cs +++ b/src/Intents/INIntentResolutionResult.cs @@ -11,20 +11,14 @@ using Foundation; using ObjCRuntime; -#if !NET -using NativeHandle = System.IntPtr; -#endif +#nullable enable namespace Intents { -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos14.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [TV (14, 0)] -#endif [Register ("INIntentResolutionResult", SkipRegistration = true)] public sealed partial class INIntentResolutionResult : INIntentResolutionResult where ObjectType : class, INativeObject { @@ -53,24 +47,16 @@ public static INIntentResolutionResult Unsupported { } } -#if NET [SupportedOSPlatform ("ios13.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos14.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [iOS (13, 0)] -#endif public static INIntentResolutionResult GetUnsupported (nint reason) => throw new NotImplementedException ("All subclasses of INIntentResolutionResult must re-implement this method"); -#if NET [SupportedOSPlatform ("ios13.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("tvos14.0")] [SupportedOSPlatform ("maccatalyst")] -#else - [iOS (13, 0)] -#endif public static INIntentResolutionResult GetConfirmationRequired (NSObject itemToConfirm, nint reason) => throw new NotImplementedException ("All subclasses of INIntentResolutionResult must re-implement this method"); } diff --git a/src/Intents/INInteraction.cs b/src/Intents/INInteraction.cs index 98cee40d7593..34bdb83764bf 100644 --- a/src/Intents/INInteraction.cs +++ b/src/Intents/INInteraction.cs @@ -12,15 +12,14 @@ using Foundation; using ObjCRuntime; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Intents { public partial class INInteraction { public T GetParameterValue (INParameter parameter) where T : NSObject { - return Runtime.GetNSObject (_GetParameterValue (parameter)); + return Runtime.GetNSObject (_GetParameterValue (parameter))!; } } } diff --git a/src/Intents/INMessageAttributeOptionsResolutionResult.cs b/src/Intents/INMessageAttributeOptionsResolutionResult.cs deleted file mode 100644 index ff6439b10fbc..000000000000 --- a/src/Intents/INMessageAttributeOptionsResolutionResult.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// INMessageAttributeOptionsResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !(NET && __MACOS__) -#if !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INMessageAttributeOptionsResolutionResult { - - public static INMessageAttributeOptionsResolutionResult GetSuccess (INMessageAttributeOptions resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#elif MONOMAC - if (SystemVersion.CheckmacOS (10, 13)) -#endif - return SuccessWithResolvedMessageAttributeOptions (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INMessageAttributeOptionsResolutionResult GetConfirmationRequired (INMessageAttributeOptions valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#elif MONOMAC - if (SystemVersion.CheckmacOS (10, 13)) -#endif - return ConfirmationRequiredWithMessageAttributeOptionsToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -} -#endif -#endif // !(NET && __MACOS__) diff --git a/src/Intents/INMessageAttributeResolutionResult.cs b/src/Intents/INMessageAttributeResolutionResult.cs deleted file mode 100644 index 5e8a2b8d8658..000000000000 --- a/src/Intents/INMessageAttributeResolutionResult.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// INMessageAttributeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { -#if !(NET && __MACOS__) - public partial class INMessageAttributeResolutionResult { - - public static INMessageAttributeResolutionResult GetSuccess (INMessageAttribute resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#elif MONOMAC - if (SystemVersion.CheckmacOS (10, 13)) -#endif - return SuccessWithResolvedMessageAttribute (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INMessageAttributeResolutionResult GetConfirmationRequired (INMessageAttribute valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#elif MONOMAC - if (SystemVersion.CheckmacOS (10, 13)) -#endif - return ConfirmationRequiredWithMessageAttributeToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -#endif // !(NET && __MACOS__) -} -#endif diff --git a/src/Intents/INPaymentStatusResolutionResult.cs b/src/Intents/INPaymentStatusResolutionResult.cs deleted file mode 100644 index 05098efd515c..000000000000 --- a/src/Intents/INPaymentStatusResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INPaymentStatusResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INPaymentStatusResolutionResult { - - public static INPaymentStatusResolutionResult GetSuccess (INPaymentStatus resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return SuccessWithResolvedPaymentStatus (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INPaymentStatusResolutionResult GetConfirmationRequired (INPaymentStatus valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return ConfirmationRequiredWithPaymentStatusToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -} -#endif diff --git a/src/Intents/INPerson.cs b/src/Intents/INPerson.cs index 106eb0abcc71..2b5ad41554be 100644 --- a/src/Intents/INPerson.cs +++ b/src/Intents/INPerson.cs @@ -9,44 +9,28 @@ namespace Intents { #if !TVOS public partial class INPerson { - -#if NET [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] -#else - [Introduced (PlatformName.iOS, 15, 0)] - [Introduced (PlatformName.WatchOS, 8, 0)] -#endif public enum INPersonType { Me = 0, ContactSuggestion = 1, } -#if NET [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] -#else - [Introduced (PlatformName.iOS, 15, 0)] - [Introduced (PlatformName.WatchOS, 8, 0)] -#endif public INPerson (INPersonHandle personHandle, NSPersonNameComponents? nameComponents, string? displayName, INImage? image, string? contactIdentifier, string? customIdentifier, bool isMe, INPersonSuggestionType suggestionType) : this (personHandle, nameComponents, displayName, image, contactIdentifier, customIdentifier, isMe, suggestionType, INPersonType.Me) { } -#if NET [SupportedOSPlatform ("ios15.0")] [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] -#else - [Introduced (PlatformName.iOS, 15, 0)] - [Introduced (PlatformName.WatchOS, 8, 0)] -#endif public INPerson (INPersonHandle personHandle, NSPersonNameComponents? nameComponents, string? displayName, INImage? image, string? contactIdentifier, string? customIdentifier, bool isMe, INPersonSuggestionType suggestionType, INPersonType personType) : base (NSObjectFlag.Empty) { switch (personType) { diff --git a/src/Intents/INPlayMediaIntentResponse.cs b/src/Intents/INPlayMediaIntentResponse.cs index 8a6c3c72432a..9a69ce1ec378 100644 --- a/src/Intents/INPlayMediaIntentResponse.cs +++ b/src/Intents/INPlayMediaIntentResponse.cs @@ -13,6 +13,8 @@ using ObjCRuntime; using MediaPlayer; +#nullable enable + namespace Intents { public partial class INPlayMediaIntentResponse { diff --git a/src/Intents/INPriceRange.cs b/src/Intents/INPriceRange.cs index d1191bd48c11..aa91290eb0fa 100644 --- a/src/Intents/INPriceRange.cs +++ b/src/Intents/INPriceRange.cs @@ -11,20 +11,29 @@ using System; using Foundation; +#nullable enable + namespace Intents { public enum INPriceRangeOption { Maximum, - Minimum + Minimum, } public partial class INPriceRange { public INPriceRange (INPriceRangeOption option, NSDecimalNumber price, string currencyCode) + : base (NSObjectFlag.Empty) { - if (option == INPriceRangeOption.Maximum) - Handle = InitWithMaximumPrice (price, currencyCode); - else - Handle = InitWithMinimumPrice (price, currencyCode); + switch (option) { + case INPriceRangeOption.Maximum: + InitializeHandle (InitWithMaximumPrice (price, currencyCode)); + break; + case INPriceRangeOption.Minimum: + InitializeHandle (InitWithMinimumPrice (price, currencyCode)); + break; + default: + throw new ArgumentOutOfRangeException (nameof (option), option, "Invalid enum value."); + } } } } diff --git a/src/Intents/INRadioTypeResolutionResult.cs b/src/Intents/INRadioTypeResolutionResult.cs deleted file mode 100644 index 5d5f5c49a9ca..000000000000 --- a/src/Intents/INRadioTypeResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INRadioTypeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INRadioTypeResolutionResult { - - public static INRadioTypeResolutionResult GetSuccess (INRadioType resolvedValue) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return SuccessWithResolvedRadioType (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); -#endif - } - - public static INRadioTypeResolutionResult GetConfirmationRequired (INRadioType valueToConfirm) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return ConfirmationRequiredWithRadioTypeToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); -#endif - } - } -} -#endif diff --git a/src/Intents/INRadioTypeResolutionResult.watchOS.cs b/src/Intents/INRadioTypeResolutionResult.watchOS.cs deleted file mode 100644 index eae5b88989b8..000000000000 --- a/src/Intents/INRadioTypeResolutionResult.watchOS.cs +++ /dev/null @@ -1,55 +0,0 @@ -#if !NET -using System; -using System.Drawing; -using System.Diagnostics; -using System.ComponentModel; -using System.Threading.Tasks; -using System.Runtime.InteropServices; -using UIKit; -using SceneKit; -using Contacts; -using CoreVideo; -using SpriteKit; -using Foundation; -using ObjCRuntime; -using CoreGraphics; -using CoreLocation; -using AVFoundation; -using CoreFoundation; - -namespace Intents { - [Register ("INRadioTypeResolutionResult", true)] - [Obsolete (Constants.UnavailableOnWatchOS)] - public unsafe partial class INRadioTypeResolutionResult : INIntentResolutionResult { - public override IntPtr ClassHandle { get { throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); } } - - protected INRadioTypeResolutionResult (NSObjectFlag t) : base (t) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - protected internal INRadioTypeResolutionResult (IntPtr handle) : base (handle) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public new static INRadioTypeResolutionResult NeedsValue { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INRadioTypeResolutionResult NotRequired { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INRadioTypeResolutionResult Unsupported { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - } /* class INRadioTypeResolutionResult */ -} -#endif // !NET diff --git a/src/Intents/INRelativeReferenceResolutionResult.cs b/src/Intents/INRelativeReferenceResolutionResult.cs deleted file mode 100644 index c0d7cc768343..000000000000 --- a/src/Intents/INRelativeReferenceResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INRelativeReferenceResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INRelativeReferenceResolutionResult { - - public static INRelativeReferenceResolutionResult GetSuccess (INRelativeReference resolvedValue) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return SuccessWithResolvedRelativeReference (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); -#endif - } - - public static INRelativeReferenceResolutionResult GetConfirmationRequired (INRelativeReference valueToConfirm) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return ConfirmationRequiredWithRelativeReferenceToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); -#endif - } - } -} -#endif diff --git a/src/Intents/INRelativeReferenceResolutionResult.watchOS.cs b/src/Intents/INRelativeReferenceResolutionResult.watchOS.cs deleted file mode 100644 index e4e2de95af0b..000000000000 --- a/src/Intents/INRelativeReferenceResolutionResult.watchOS.cs +++ /dev/null @@ -1,55 +0,0 @@ -#if !NET -using System; -using System.Drawing; -using System.Diagnostics; -using System.ComponentModel; -using System.Threading.Tasks; -using System.Runtime.InteropServices; -using UIKit; -using SceneKit; -using Contacts; -using CoreVideo; -using SpriteKit; -using Foundation; -using ObjCRuntime; -using CoreGraphics; -using CoreLocation; -using AVFoundation; -using CoreFoundation; - -namespace Intents { - [Register ("INRelativeReferenceResolutionResult", true)] - [Obsolete (Constants.UnavailableOnWatchOS)] - public unsafe partial class INRelativeReferenceResolutionResult : INIntentResolutionResult { - public override IntPtr ClassHandle { get { throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); } } - - protected INRelativeReferenceResolutionResult (NSObjectFlag t) : base (t) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - protected internal INRelativeReferenceResolutionResult (IntPtr handle) : base (handle) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public new static INRelativeReferenceResolutionResult NeedsValue { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INRelativeReferenceResolutionResult NotRequired { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INRelativeReferenceResolutionResult Unsupported { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - } /* class INRelativeReferenceResolutionResult */ -} -#endif // !NET diff --git a/src/Intents/INRelativeSettingResolutionResult.cs b/src/Intents/INRelativeSettingResolutionResult.cs deleted file mode 100644 index e82507ec806f..000000000000 --- a/src/Intents/INRelativeSettingResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INRelativeSettingResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INRelativeSettingResolutionResult { - - public static INRelativeSettingResolutionResult GetSuccess (INRelativeSetting resolvedValue) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return SuccessWithResolvedRelativeSetting (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); -#endif - } - - public static INRelativeSettingResolutionResult GetConfirmationRequired (INRelativeSetting valueToConfirm) - { -#if __IOS__ - if (SystemVersion.CheckiOS (11, 0)) - return ConfirmationRequiredWithRelativeSettingToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); -#endif - } - } -} -#endif diff --git a/src/Intents/INRelativeSettingResolutionResult.watchOS.cs b/src/Intents/INRelativeSettingResolutionResult.watchOS.cs deleted file mode 100644 index 8e5b6410eecb..000000000000 --- a/src/Intents/INRelativeSettingResolutionResult.watchOS.cs +++ /dev/null @@ -1,55 +0,0 @@ -#if !NET -using System; -using System.Drawing; -using System.Diagnostics; -using System.ComponentModel; -using System.Threading.Tasks; -using System.Runtime.InteropServices; -using UIKit; -using SceneKit; -using Contacts; -using CoreVideo; -using SpriteKit; -using Foundation; -using ObjCRuntime; -using CoreGraphics; -using CoreLocation; -using AVFoundation; -using CoreFoundation; - -namespace Intents { - [Register ("INRelativeSettingResolutionResult", true)] - [Obsolete (Constants.UnavailableOnWatchOS)] - public unsafe partial class INRelativeSettingResolutionResult : INIntentResolutionResult { - public override IntPtr ClassHandle { get { throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); } } - - protected INRelativeSettingResolutionResult (NSObjectFlag t) : base (t) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - protected internal INRelativeSettingResolutionResult (IntPtr handle) : base (handle) - { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - - public new static INRelativeSettingResolutionResult NeedsValue { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INRelativeSettingResolutionResult NotRequired { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - - public new static INRelativeSettingResolutionResult Unsupported { - get { - throw new PlatformNotSupportedException (Constants.UnavailableOnWatchOS); - } - } - } /* class INRelativeSettingResolutionResult */ -} -#endif // !NET diff --git a/src/Intents/INRideOption.cs b/src/Intents/INRideOption.cs deleted file mode 100644 index 0c5ee67bc5ca..000000000000 --- a/src/Intents/INRideOption.cs +++ /dev/null @@ -1,20 +0,0 @@ -#if IOS - -using Foundation; -using Intents; -using ObjCRuntime; - -namespace Intents { - - public partial class INRideOption { - - // if/when we update the generator to allow this pattern we can move this back - // into bindings and making them virtual (not a breaking change) - - public bool? UsesMeteredFare { - get { return _UsesMeteredFare is null ? null : (bool?) _UsesMeteredFare.BoolValue; } - } - } -} - -#endif diff --git a/src/Intents/INSaveProfileInCarIntent.cs b/src/Intents/INSaveProfileInCarIntent.cs deleted file mode 100644 index 2e0ed3f6f0e2..000000000000 --- a/src/Intents/INSaveProfileInCarIntent.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// INSaveProfileInCarIntent Extensions -// -// Authors: -// Alex Soto -// -// Copyright 2016 Xamarin Inc. All rights reserved. -// - -#if IOS - -using Foundation; -using Intents; -using ObjCRuntime; -using UIKit; - -namespace Intents { - public partial class INSaveProfileInCarIntent { - - public INSaveProfileInCarIntent (NSNumber profileNumber, string profileLabel) - { - // Apple created this change in 10,2 - if (SystemVersion.CheckiOS (10, 2)) - InitializeHandle (InitWithProfileNumberName (profileNumber, profileLabel)); - else - InitializeHandle (InitWithProfileNumberLabel (profileNumber, profileLabel)); - } - } -} -#endif diff --git a/src/Intents/INSearchCallHistoryIntent.cs b/src/Intents/INSearchCallHistoryIntent.cs index cdf600ee622a..677e556eb716 100644 --- a/src/Intents/INSearchCallHistoryIntent.cs +++ b/src/Intents/INSearchCallHistoryIntent.cs @@ -7,12 +7,14 @@ // Copyright 2017 Xamarin Inc. All rights reserved. // -#if !(NET && __MACOS__) +#if !__MACOS__ #if !TVOS using System; using Foundation; using ObjCRuntime; +#nullable enable + namespace Intents { public partial class INSearchCallHistoryIntent { @@ -22,4 +24,4 @@ public bool? Unseen { } } #endif -#endif // !(NET && __MACOS__) +#endif // __MACOS__ diff --git a/src/Intents/INSetCarLockStatusIntent.cs b/src/Intents/INSetCarLockStatusIntent.cs index 547ec242d06e..4357f767d453 100644 --- a/src/Intents/INSetCarLockStatusIntent.cs +++ b/src/Intents/INSetCarLockStatusIntent.cs @@ -21,13 +21,6 @@ public INSetCarLockStatusIntent (bool? locked, INSpeakableString carName) : this (locked.HasValue ? new NSNumber (locked.Value) : null, carName) { } - - // if/when we update the generator to allow this pattern we can move this back - // into bindings and making them virtual (not a breaking change) - - public bool? Locked { - get { return _Locked is null ? null : (bool?) _Locked.BoolValue; } - } } } diff --git a/src/Intents/INSetClimateSettingsInCarIntent.cs b/src/Intents/INSetClimateSettingsInCarIntent.cs index dc2f218e2f01..859a84e79da3 100644 --- a/src/Intents/INSetClimateSettingsInCarIntent.cs +++ b/src/Intents/INSetClimateSettingsInCarIntent.cs @@ -4,19 +4,17 @@ using Intents; using ObjCRuntime; +#nullable enable + namespace Intents { public partial class INSetClimateSettingsInCarIntent { - -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [ObsoletedOSPlatform ("ios12.0", "Use the overload that takes 'INSpeakableString carName'.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the overload that takes 'INSpeakableString carName'.")] [UnsupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("tvos")] -#else - [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] -#endif public INSetClimateSettingsInCarIntent (bool? enableFan, bool? enableAirConditioner, bool? enableClimateControl, bool? enableAutoMode, INCarAirCirculationMode airCirculationMode, NSNumber fanSpeedIndex, NSNumber fanSpeedPercentage, INRelativeSetting relativeFanSpeedSetting, NSMeasurement temperature, INRelativeSetting relativeTemperatureSetting, INCarSeat climateZone) : this (enableFan.HasValue ? new NSNumber (enableFan.Value) : null, enableAirConditioner.HasValue ? new NSNumber (enableAirConditioner.Value) : null, enableClimateControl.HasValue ? new NSNumber (enableClimateControl.Value) : null, enableAutoMode.HasValue ? new NSNumber (enableAutoMode.Value) : null, diff --git a/src/Intents/INSetDefrosterSettingsInCarIntent.cs b/src/Intents/INSetDefrosterSettingsInCarIntent.cs index c7fc8ed61c9c..bd3d045dc1d1 100644 --- a/src/Intents/INSetDefrosterSettingsInCarIntent.cs +++ b/src/Intents/INSetDefrosterSettingsInCarIntent.cs @@ -4,19 +4,17 @@ using Intents; using ObjCRuntime; +#nullable enable + namespace Intents { public partial class INSetDefrosterSettingsInCarIntent { - -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [ObsoletedOSPlatform ("ios12.0", "Use the overload that takes 'INSpeakableString carName'.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the overload that takes 'INSpeakableString carName'.")] [UnsupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("tvos")] -#else - [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] -#endif public INSetDefrosterSettingsInCarIntent (bool? enable, INCarDefroster defroster) : this (enable.HasValue ? new NSNumber (enable.Value) : null, defroster) { diff --git a/src/Intents/INSetProfileInCarIntent.cs b/src/Intents/INSetProfileInCarIntent.cs index b03001963b35..cfc7938087cf 100644 --- a/src/Intents/INSetProfileInCarIntent.cs +++ b/src/Intents/INSetProfileInCarIntent.cs @@ -5,44 +5,21 @@ using ObjCRuntime; using UIKit; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Intents { public partial class INSetProfileInCarIntent { - -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [ObsoletedOSPlatform ("ios12.0", "Use the overload that takes 'INSpeakableString carName'.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the overload that takes 'INSpeakableString carName'.")] [UnsupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("tvos")] -#else - [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] -#endif public INSetProfileInCarIntent (NSNumber profileNumber, string profileLabel, bool? defaultProfile) : this (profileNumber, profileLabel, defaultProfile.HasValue ? new NSNumber (defaultProfile.Value) : null) { } - -#if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [ObsoletedOSPlatform ("ios12.0", "Use the overload that takes 'INSpeakableString carName'.")] - [UnsupportedOSPlatform ("macos")] - [UnsupportedOSPlatform ("tvos")] -#else - [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] -#endif - protected INSetProfileInCarIntent (NSNumber profileNumber, string profileLabel, NSNumber defaultProfile) - { - // Apple created this change in 10,2 - if (SystemVersion.CheckiOS (10, 2)) - InitializeHandle (InitWithProfileNumberName (profileNumber, profileLabel, defaultProfile)); - else - InitializeHandle (InitWithProfileNumberLabel (profileNumber, profileLabel, defaultProfile)); - } } } diff --git a/src/Intents/INSetSeatSettingsInCarIntent.cs b/src/Intents/INSetSeatSettingsInCarIntent.cs index dacf738389c1..e72cbdf83332 100644 --- a/src/Intents/INSetSeatSettingsInCarIntent.cs +++ b/src/Intents/INSetSeatSettingsInCarIntent.cs @@ -4,19 +4,17 @@ using Intents; using ObjCRuntime; +#nullable enable + namespace Intents { public partial class INSetSeatSettingsInCarIntent { - -#if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] [ObsoletedOSPlatform ("ios12.0", "Use the overload that takes 'INSpeakableString carName'.")] + [ObsoletedOSPlatform ("maccatalyst13.1", "Use the overload that takes 'INSpeakableString carName'.")] [UnsupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("tvos")] -#else - [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] -#endif public INSetSeatSettingsInCarIntent (bool? enableHeating, bool? enableCooling, bool? enableMassage, INCarSeat seat, NSNumber level, INRelativeSetting relativeLevelSetting) : this (enableHeating.HasValue ? new NSNumber (enableHeating.Value) : null, enableCooling.HasValue ? new NSNumber (enableCooling.Value) : null, enableMassage.HasValue ? new NSNumber (enableMassage.Value) : null, seat, level, relativeLevelSetting) { diff --git a/src/Intents/INSpeakableString.cs b/src/Intents/INSpeakableString.cs deleted file mode 100644 index 7b6ed0e23a73..000000000000 --- a/src/Intents/INSpeakableString.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// INSpeakableString.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INSpeakableString { - public INSpeakableString (string identifier, string spokenPhrase, string pronunciationHint) - : base (NSObjectFlag.Empty) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#elif MONOMAC - if (SystemVersion.CheckmacOS (10, 13)) -#endif - InitializeHandle (InitWithVocabularyIdentifier (identifier, spokenPhrase, pronunciationHint)); -#if !TVOS - else - InitializeHandle (InitWithIdentifier (identifier, spokenPhrase, pronunciationHint)); -#endif - } - } -} diff --git a/src/Intents/INStartWorkoutIntent.cs b/src/Intents/INStartWorkoutIntent.cs index dcaedc738c13..f780a57b2df5 100644 --- a/src/Intents/INStartWorkoutIntent.cs +++ b/src/Intents/INStartWorkoutIntent.cs @@ -1,10 +1,12 @@ #if IOS -#if !(NET && __MACOS__) +#if !__MACOS__ using Foundation; using Intents; using ObjCRuntime; +#nullable enable + namespace Intents { public partial class INStartWorkoutIntent { @@ -13,15 +15,8 @@ public INStartWorkoutIntent (INSpeakableString workoutName, NSNumber goalValue, this (workoutName, goalValue, workoutGoalUnitType, workoutLocationType, isOpenEnded.HasValue ? new NSNumber (isOpenEnded.Value) : null) { } - - // if/when we update the generator to allow this pattern we can move this back - // into bindings and making them virtual (not a breaking change) - - public bool? IsOpenEnded { - get { return _IsOpenEnded is null ? null : (bool?) _IsOpenEnded.BoolValue; } - } } } -#endif // !(NET && __MACOS__) +#endif // !__MACOS__ #endif diff --git a/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs b/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs deleted file mode 100644 index 46020fca83a0..000000000000 --- a/src/Intents/INWorkoutGoalUnitTypeResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INWorkoutGoalUnitTypeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INWorkoutGoalUnitTypeResolutionResult { - - public static INWorkoutGoalUnitTypeResolutionResult GetSuccess (INWorkoutGoalUnitType resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return SuccessWithResolvedWorkoutGoalUnitType (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INWorkoutGoalUnitTypeResolutionResult GetConfirmationRequired (INWorkoutGoalUnitType valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return ConfirmationRequiredWithWorkoutGoalUnitTypeToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -} -#endif diff --git a/src/Intents/INWorkoutLocationTypeResolutionResult.cs b/src/Intents/INWorkoutLocationTypeResolutionResult.cs deleted file mode 100644 index 0afa363d03e1..000000000000 --- a/src/Intents/INWorkoutLocationTypeResolutionResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// INWorkoutLocationTypeResolutionResult.cs -// -// Authors: -// Alex Soto -// -// Copyright 2017 Xamarin Inc. All rights reserved. -// - -#if !MONOMAC && !TVOS -using System; -using Foundation; -using ObjCRuntime; - -namespace Intents { - public partial class INWorkoutLocationTypeResolutionResult { - - public static INWorkoutLocationTypeResolutionResult GetSuccess (INWorkoutLocationType resolvedValue) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return SuccessWithResolvedWorkoutLocationType (resolvedValue); - else - return SuccessWithResolvedValue (resolvedValue); - } - - public static INWorkoutLocationTypeResolutionResult GetConfirmationRequired (INWorkoutLocationType valueToConfirm) - { -#if IOS - if (SystemVersion.CheckiOS (11, 0)) -#endif - return ConfirmationRequiredWithWorkoutLocationTypeToConfirm (valueToConfirm); - else - return ConfirmationRequiredWithValueToConfirm (valueToConfirm); - } - } -} -#endif diff --git a/src/ObjCBindings/ExportTag.cs b/src/ObjCBindings/ExportTag.cs index acf65e9633cc..9ee01343ac08 100644 --- a/src/ObjCBindings/ExportTag.cs +++ b/src/ObjCBindings/ExportTag.cs @@ -60,7 +60,6 @@ public enum Method : Int64 { /// MarshalNativeExceptions = 1 << 4, - /// /// Instruct the generator to use a custom marshal directive for the method. When this flag is applied the /// following name parameters must be provided: @@ -85,6 +84,28 @@ public enum Method : Int64 { /// Use this flag on method to wrap the invocation in a NSAutoReleasePool. /// AutoRelease = 1 << 8, + + /// + /// Use this flag on method to retain the return value. + /// + RetainReturnValue = 1 << 9, + + /// + /// Use this flag on method to release the return value. + /// + ReleaseReturnValue = 1 << 10, + + /// + /// Use this flag on a method to mark that the return type of the method is a + /// proxy type. + /// + Proxy = 1 << 11, + + /// + /// Use this flag on a method to mark that the method is a factory method. + /// + Factory = 1 << 12, + } /// @@ -167,6 +188,22 @@ public enum Property : Int64 { /// AutoRelease = 1 << 11, + /// + /// Use this flag on property to retain the return value. + /// + RetainReturnValue = 1 << 12, + + /// + /// Use this flag on property to release the return value. + /// + ReleaseReturnValue = 1 << 13, + + /// + /// Use this flag on a method to mark that the return type of the method is a + /// proxy type. + /// + Proxy = 1 << 14, + } } diff --git a/src/Social/Enums.cs b/src/Social/Enums.cs index 3e80171b08c9..8cb69aff46b0 100644 --- a/src/Social/Enums.cs +++ b/src/Social/Enums.cs @@ -33,18 +33,4 @@ public enum SLComposeViewControllerResult : long { Cancelled, Done, } - - // note: those are NSString in iOS/OSX that we expose as an enum (i.e. it's NOT a native enum) - // when adding a value make sure to update SLRequest.KindToType method - /// Enumeration with the various kinds of social services that can be used. - /// This enumeration is used to map into the underlying set of services offered by the social framework. It is intended to assist code completion while developing and take the gueswork out of using the framework in some entry points that take an NSString as a parameter. - public enum SLServiceKind { - Facebook, - Twitter, - SinaWeibo, - TencentWeibo, -#if MONOMAC - LinkedIn, -#endif - } } diff --git a/src/Social/SLComposeViewController.cs b/src/Social/SLComposeViewController.cs index 320a257ee803..3905af9be3bc 100644 --- a/src/Social/SLComposeViewController.cs +++ b/src/Social/SLComposeViewController.cs @@ -21,12 +21,12 @@ namespace Social { public partial class SLComposeViewController { public static SLComposeViewController FromService (SLServiceKind serviceKind) { - return FromService (SLRequest.KindToType (serviceKind)); + return FromService (serviceKind.GetConstant ()!); } public static bool IsAvailable (SLServiceKind serviceKind) { - return IsAvailable (SLRequest.KindToType (serviceKind)); + return IsAvailable (serviceKind.GetConstant ()!); } } } diff --git a/src/Social/SLRequest.cs b/src/Social/SLRequest.cs index 57c2673a5d2d..e69de29bb2d1 100644 --- a/src/Social/SLRequest.cs +++ b/src/Social/SLRequest.cs @@ -1,45 +0,0 @@ -// -// SLRequest.cs: extensions to the SLRequest class -// -// Authors: -// Miguel de Icaza (miguel@xamarin.com) -// -// Copyright 2012-2013 Xamarin Inc -// - -#nullable enable - -using System; -using ObjCRuntime; -using Foundation; -using Accounts; - -namespace Social { - - public partial class SLRequest { - internal static NSString KindToType (SLServiceKind kind) - { - switch (kind) { - case SLServiceKind.Facebook: - return SLServiceType.Facebook; - case SLServiceKind.Twitter: - return SLServiceType.Twitter; - case SLServiceKind.SinaWeibo: - return SLServiceType.SinaWeibo; - case SLServiceKind.TencentWeibo: - return SLServiceType.TencentWeibo; -#if MONOMAC - case SLServiceKind.LinkedIn: - return SLServiceType.LinkedIn; -#endif - default: - throw new ArgumentOutOfRangeException (nameof (kind)); - } - } - - public static SLRequest Create (SLServiceKind serviceKind, SLRequestMethod method, NSUrl url, NSDictionary parameters) - { - return Create (KindToType (serviceKind), method, url, parameters); - } - } -} diff --git a/src/UIKit/UIEnums.cs b/src/UIKit/UIEnums.cs index e5a727f5acd6..b0d52cff6f3c 100644 --- a/src/UIKit/UIEnums.cs +++ b/src/UIKit/UIEnums.cs @@ -1668,6 +1668,7 @@ public enum UISystemAnimation : ulong { // NSUInteger -> UIGeometry.h [Native] + [Flags] public enum UIRectEdge : ulong { None = 0, Top = 1 << 0, diff --git a/src/WebKit/WKPreferences.cs b/src/WebKit/WKPreferences.cs index d498c8262456..eab9a6e5314e 100644 --- a/src/WebKit/WKPreferences.cs +++ b/src/WebKit/WKPreferences.cs @@ -12,15 +12,10 @@ public partial class WKPreferences { #if !COREBUILD // we use the attrs of the old property -#if NET [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("ios14.5")] [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] -#else - [iOS (14, 5)] - [MacCatalyst (14, 5)] -#endif public bool TextInteractionEnabled { get { #if IOS || __MACCATALYST__ diff --git a/src/foundation.cs b/src/foundation.cs index 258609434527..1779b7dfa1e0 100644 --- a/src/foundation.cs +++ b/src/foundation.cs @@ -972,8 +972,17 @@ interface NSCache { [Export ("objectForKey:")] NSObject ObjectForKey (NSObject key); +#if !XAMCORE_5_0 + [Obsolete ("Use 'SetObjectForKey' instead.")] [Export ("setObject:forKey:")] void SetObjectforKey (NSObject obj, NSObject key); +#endif + +#if !XAMCORE_5_0 + [Sealed] +#endif + [Export ("setObject:forKey:")] + void SetObjectForKey (NSObject obj, NSObject key); [Export ("setObject:forKey:cost:")] void SetCost (NSObject obj, NSObject key, nuint cost); diff --git a/src/frameworks.sources b/src/frameworks.sources index 99c93c5ba037..6d2813b175b4 100644 --- a/src/frameworks.sources +++ b/src/frameworks.sources @@ -1061,47 +1061,19 @@ IMAGEKIT_CORE_SOURCES = \ # Intents INTENTS_SOURCES = \ - Intents/INBillTypeResolutionResult.cs \ Intents/INCallRecord.cs \ - Intents/INCallRecordTypeResolutionResult.cs \ - Intents/INCarAirCirculationModeResolutionResult.cs \ - Intents/INCarAudioSourceResolutionResult.cs \ - Intents/INCarDefrosterResolutionResult.cs \ - Intents/INCarSeatResolutionResult.cs \ - Intents/INCarSignalOptionsResolutionResult.cs \ - Intents/INCompat.cs \ - Intents/INGetCarLockStatusIntentResponse.cs \ - Intents/INGetCarPowerLevelStatusIntentResponse.cs \ Intents/INIntentResolutionResult.cs \ Intents/INInteraction.cs \ - Intents/INMessageAttributeOptionsResolutionResult.cs \ - Intents/INMessageAttributeResolutionResult.cs \ - Intents/INPaymentStatusResolutionResult.cs \ Intents/INPerson.cs \ Intents/INPriceRange.cs \ - Intents/INRadioTypeResolutionResult.cs \ - Intents/INRelativeReferenceResolutionResult.cs \ - Intents/INRelativeSettingResolutionResult.cs \ - Intents/INRideOption.cs \ Intents/INPlayMediaIntentResponse.cs \ - Intents/INSaveProfileInCarIntent.cs \ Intents/INSearchCallHistoryIntent.cs \ Intents/INSetCarLockStatusIntent.cs \ Intents/INSetClimateSettingsInCarIntent.cs \ Intents/INSetDefrosterSettingsInCarIntent.cs \ Intents/INSetProfileInCarIntent.cs \ Intents/INSetSeatSettingsInCarIntent.cs \ - Intents/INSpeakableString.cs \ Intents/INStartWorkoutIntent.cs \ - Intents/INWorkoutGoalUnitTypeResolutionResult.cs \ - Intents/INWorkoutLocationTypeResolutionResult.cs \ - Intents/INCarAirCirculationModeResolutionResult.watchOS.cs \ - Intents/INCarAudioSourceResolutionResult.watchOS.cs \ - Intents/INCarDefrosterResolutionResult.watchOS.cs \ - Intents/INCarSeatResolutionResult.watchOS.cs \ - Intents/INRadioTypeResolutionResult.watchOS.cs \ - Intents/INRelativeReferenceResolutionResult.watchOS.cs \ - Intents/INRelativeSettingResolutionResult.watchOS.cs \ # IOSurface IOSURFACE_CORE_SOURCES = \ @@ -1692,7 +1664,6 @@ SOCIAL_API_SOURCES = \ SOCIAL_SOURCES = \ Social/SLComposeViewController.cs \ - Social/SLRequest.cs \ # Speech diff --git a/src/intents.cs b/src/intents.cs index b3b582d92cbb..d5d07466254f 100644 --- a/src/intents.cs +++ b/src/intents.cs @@ -31,10 +31,6 @@ using NSImage = Foundation.NSObject; #endif -#if !NET -using NativeHandle = System.IntPtr; -#endif - namespace Intents { // HACK only to please the generator - which does not (normally) know the type hierarchy in the @@ -183,12 +179,8 @@ public enum INCarSeat : long { All } -#if NET /// Enumerates operators to be used with search predicates. [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [Native] @@ -361,10 +353,8 @@ public enum INListRideOptionsIntentResponseCode : long { FailurePreviousRideNeedsFeedback, } -#if NET /// Enumerates the attributes of a message. [NoMac] -#endif [NoTV] [MacCatalyst (13, 1)] [Native] @@ -374,19 +364,13 @@ public enum INMessageAttribute : long { Unread, Flagged, Unflagged, -#if NET [NoMac] -#endif [MacCatalyst (13, 1)] Played, } -#if NET /// Enumerates the statuses of a message. [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [Native] @@ -396,9 +380,7 @@ public enum INMessageAttributeOptions : ulong { Unread = (1 << 1), Flagged = (1 << 2), Unflagged = (1 << 3), -#if NET [NoMac] -#endif [MacCatalyst (13, 1)] Played = (1UL << 4), } @@ -665,12 +647,8 @@ public enum INSaveProfileInCarIntentResponseCode : long { FailureRequiringAppLaunch } -#if NET /// Enumerates results codes for the . [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 15, 0)] [NoTV] [MacCatalyst (13, 1)] @@ -690,12 +668,8 @@ public enum INSearchCallHistoryIntentResponseCode : long { Success, } -#if NET /// Enumerates results codes for the . [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [Native] @@ -817,10 +791,8 @@ public enum INSetDefrosterSettingsInCarIntentResponseCode : long { FailureRequiringAppLaunch } -#if NET /// Enumerates results codes for the . [NoMac] -#endif [NoTV] [MacCatalyst (13, 1)] [Native] @@ -894,12 +866,8 @@ public enum INSiriAuthorizationStatus : long { Authorized, } -#if NET /// Enumerates results codes for the . [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntentResponseCode' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -938,12 +906,8 @@ public enum INStartPhotoPlaybackIntentResponseCode : long { FailureAppConfigurationRequired, } -#if NET /// Enumerates results codes for the . [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntentResponseCode' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -1395,12 +1359,8 @@ public enum INLocationSearchType : long { ByLocationTrigger, } -#if NET /// Enumerates message content types. [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [Native] @@ -2425,102 +2385,58 @@ enum INPersonRelationship { [Field (null)] None, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipFather")] Father, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipMother")] Mother, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipParent")] Parent, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipBrother")] Brother, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipSister")] Sister, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipChild")] Child, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipFriend")] Friend, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipSpouse")] Spouse, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipPartner")] Partner, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipAssistant")] Assistant, -#if NET [NoMac] [MacCatalyst (13, 1)] -#else - [Obsoleted (PlatformName.MacOSX, 10, 0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Field ("INPersonRelationshipManager")] Manager, @@ -2633,6 +2549,7 @@ enum INCarChargingConnectorType { Gbtdc, [Deprecated (PlatformName.iOS, 17, 4, message: "Use 'INCarChargingConnectorType.NacsDc' instead.")] + [Deprecated (PlatformName.MacCatalyst, 17, 4, message: "Use 'INCarChargingConnectorType.NacsDc' instead.")] [Field ("INCarChargingConnectorTypeTesla")] Tesla, @@ -2689,12 +2606,8 @@ interface CLPlacemark_INIntentsAdditions { interface INBookRestaurantReservationIntent : NSCopying { [MacCatalyst (13, 1)] [Export ("initWithRestaurant:bookingDateComponents:partySize:bookingIdentifier:guest:selectedOffer:guestProvidedSpecialRequestText:")] -#if NET NativeHandle Constructor (INRestaurant restaurant, NSDateComponents bookingDateComponents, nuint partySize, [NullAllowed] string bookingIdentifier, [NullAllowed] INRestaurantGuest guest, [NullAllowed] INRestaurantOffer selectedOffer, [NullAllowed] string guestProvidedSpecialRequestText); -#else - // This is correctly nuint but a bug in PMCS generated incorrect code which has shipped. - NativeHandle Constructor (INRestaurant restaurant, NSDateComponents bookingDateComponents, ulong partySize, [NullAllowed] string bookingIdentifier, [NullAllowed] INRestaurantGuest guest, [NullAllowed] INRestaurantOffer selectedOffer, [NullAllowed] string guestProvidedSpecialRequestText); -#endif + [Export ("restaurant", ArgumentSemantic.Copy)] INRestaurant Restaurant { get; set; } @@ -2728,13 +2641,7 @@ interface INBookRestaurantReservationIntentHandling { void HandleBookRestaurantReservation (INBookRestaurantReservationIntent intent, Action completion); [Export ("confirmBookRestaurantReservation:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmBookRestaurantReservation -#endif - (INBookRestaurantReservationIntent intent, Action completion); + void Confirm (INBookRestaurantReservationIntent intent, Action completion); [Export ("resolveRestaurantForBookRestaurantReservation:withCompletion:")] void ResolveRestaurant (INBookRestaurantReservationIntent intent, Action completion); @@ -2830,32 +2737,14 @@ interface INBooleanResolutionResult { interface INCallRecordTypeResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedCallRecordType:")] - INCallRecordTypeResolutionResult SuccessWithResolvedCallRecordType (INCallRecordType resolvedCallRecordType); - - [Internal] - [Deprecated (PlatformName.MacOSX, 10, 13)] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INCallRecordTypeResolutionResult SuccessWithResolvedValue (INCallRecordType resolvedValue); + INCallRecordTypeResolutionResult GetSuccess (INCallRecordType resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithCallRecordTypeToConfirm:")] - INCallRecordTypeResolutionResult ConfirmationRequiredWithCallRecordTypeToConfirm (INCallRecordType callRecordTypeToConfirm); - - [Internal] - [Deprecated (PlatformName.MacOSX, 10, 13)] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INCallRecordTypeResolutionResult ConfirmationRequiredWithValueToConfirm (INCallRecordType valueToConfirm); + INCallRecordTypeResolutionResult GetConfirmationRequired (INCallRecordType valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -2918,13 +2807,7 @@ interface INCancelWorkoutIntentHandling { void HandleCancelWorkout (INCancelWorkoutIntent intent, Action completion); [Export ("confirmCancelWorkout:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmCancelWorkout -#endif - (INCancelWorkoutIntent intent, Action completion); + void Confirm (INCancelWorkoutIntent intent, Action completion); [Export ("resolveWorkoutNameForCancelWorkout:withCompletion:")] void ResolveWorkoutName (INCancelWorkoutIntent intent, Action completion); @@ -2963,29 +2846,22 @@ interface INCancelWorkoutIntentResponse { interface INCarAirCirculationModeResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedCarAirCirculationMode:")] - INCarAirCirculationModeResolutionResult SuccessWithResolvedCarAirCirculationMode (INCarAirCirculationMode resolvedCarAirCirculationMode); + INCarAirCirculationModeResolutionResult GetSuccess (INCarAirCirculationMode resolvedValue); - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Internal] + [MacCatalyst (13, 1)] [Static] - [Export ("successWithResolvedValue:")] - INCarAirCirculationModeResolutionResult SuccessWithResolvedValue (INCarAirCirculationMode resolvedValue); + [Export ("confirmationRequiredWithCarAirCirculationModeToConfirm:")] + INCarAirCirculationModeResolutionResult GetConfirmationRequired (INCarAirCirculationMode valueToConfirm); +#if !XAMCORE_5_0 + [Obsolete ("Use 'GetConfirmationRequired' instead.")] [MacCatalyst (13, 1)] [Static] [Export ("confirmationRequiredWithCarAirCirculationModeToConfirm:")] INCarAirCirculationModeResolutionResult ConfirmationRequiredWithCarAirCirculationModeToConfirm (INCarAirCirculationMode carAirCirculationModeToConfirm); - - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Internal] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INCarAirCirculationModeResolutionResult ConfirmationRequiredWithValueToConfirm (INCarAirCirculationMode valueToConfirm); +#endif // XAMCORE_5_0 // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -3034,30 +2910,14 @@ interface INCarAirCirculationModeResolutionResult { interface INCarAudioSourceResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedCarAudioSource:")] - INCarAudioSourceResolutionResult SuccessWithResolvedCarAudioSource (INCarAudioSource resolvedCarAudioSource); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INCarAudioSourceResolutionResult SuccessWithResolvedValue (INCarAudioSource resolvedValue); + INCarAudioSourceResolutionResult GetSuccess (INCarAudioSource resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithCarAudioSourceToConfirm:")] - INCarAudioSourceResolutionResult ConfirmationRequiredWithCarAudioSourceToConfirm (INCarAudioSource carAudioSourceToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INCarAudioSourceResolutionResult ConfirmationRequiredWithValueToConfirm (INCarAudioSource valueToConfirm); + INCarAudioSourceResolutionResult GetConfirmationRequired (INCarAudioSource valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -3106,30 +2966,14 @@ interface INCarAudioSourceResolutionResult { interface INCarDefrosterResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedCarDefroster:")] - INCarDefrosterResolutionResult SuccessWithResolvedCarDefroster (INCarDefroster resolvedCarDefroster); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INCarDefrosterResolutionResult SuccessWithResolvedValue (INCarDefroster resolvedValue); + INCarDefrosterResolutionResult GetSuccess (INCarDefroster resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithCarDefrosterToConfirm:")] - INCarDefrosterResolutionResult ConfirmationRequiredWithCarDefrosterToConfirm (INCarDefroster carDefrosterToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INCarDefrosterResolutionResult ConfirmationRequiredWithValueToConfirm (INCarDefroster valueToConfirm); + INCarDefrosterResolutionResult GetConfirmationRequired (INCarDefroster valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -3178,30 +3022,14 @@ interface INCarDefrosterResolutionResult { interface INCarSeatResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedCarSeat:")] - INCarSeatResolutionResult SuccessWithResolvedCarSeat (INCarSeat resolvedCarSeat); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INCarSeatResolutionResult SuccessWithResolvedValue (INCarSeat resolvedValue); + INCarSeatResolutionResult GetSuccess (INCarSeat resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithCarSeatToConfirm:")] - INCarSeatResolutionResult ConfirmationRequiredWithCarSeatToConfirm (INCarSeat carSeatToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INCarSeatResolutionResult ConfirmationRequiredWithValueToConfirm (INCarSeat valueToConfirm); + INCarSeatResolutionResult GetConfirmationRequired (INCarSeat valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -3327,9 +3155,7 @@ interface INDateComponentsRange : NSCopying, NSSecureCoding { NativeHandle Constructor (EKRecurrenceRule recurrenceRule); // Headers claim the recurrenceRule property is available in macOS, but the parameter type INRecurrenceRule is not, so... -#if NET [NoMac] -#endif [NoTV] [MacCatalyst (13, 1)] [Export ("initWithStartDateComponents:endDateComponents:recurrenceRule:")] @@ -3343,9 +3169,7 @@ interface INDateComponentsRange : NSCopying, NSSecureCoding { NSDateComponents EndDateComponents { get; } // Headers claim the recurrenceRule property is available in macOS, but the property type (INRecurrenceRule) is not, so... -#if NET [NoMac] -#endif [NoTV] [MacCatalyst (13, 1)] [NullAllowed, Export ("recurrenceRule", ArgumentSemantic.Copy)] @@ -3358,15 +3182,11 @@ interface INDateComponentsRange : NSCopying, NSSecureCoding { EKRecurrenceRule EKRecurrenceRule { get; } } -#if NET /// /// for resolving parameters in interactions involving a range of dates. /// /// Apple documentation for INDateComponentsRangeResolutionResult [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (INIntentResolutionResult))] @@ -3418,10 +3238,8 @@ interface INDateComponentsRangeResolutionResult { INDateComponentsRangeResolutionResult GetConfirmationRequired (NSObject itemToConfirm, nint reason); } -#if NET /// Interface combining several interfaces related to various phone-call intents. [NoMac] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Implement 'INStartAudioCallIntentHandling, INStartVideoCallIntentHandling and INSearchCallHistoryIntentHandling' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -3490,10 +3308,7 @@ interface INMessagesDomainHandling : INSendMessageIntentHandling, INSearchForMes [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Implement 'INSendPaymentIntentHandling, INRequestPaymentIntentHandling, INPayBillIntentHandling, INSearchForBillsIntentHandling, INSearchForAccountsIntentHandling and INTransferMoneyIntentHandling' instead.")] [Protocol] interface INPaymentsDomainHandling : INSendPaymentIntentHandling, INRequestPaymentIntentHandling, INPayBillIntentHandling, INSearchForBillsIntentHandling -#if NET // Added in iOS 11 -> #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000 - , INSearchForAccountsIntentHandling, INTransferMoneyIntentHandling -#endif - { + , INSearchForAccountsIntentHandling, INTransferMoneyIntentHandling { } /// Interface combining several interfaces related to various photo-related intents. @@ -3514,10 +3329,7 @@ interface INPhotosDomainHandling : INSearchForPhotosIntentHandling, INStartPhoto [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Implement 'INListRideOptionsIntentHandling, INRequestRideIntentHandling, INGetRideStatusIntentHandling, INCancelRideIntentHandling and INSendRideFeedbackIntentHandling' instead.")] [Protocol] interface INRidesharingDomainHandling : INListRideOptionsIntentHandling, INRequestRideIntentHandling, INGetRideStatusIntentHandling -#if NET // Added in iOS 11 -> #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000 - , INCancelRideIntentHandling, INSendRideFeedbackIntentHandling -#endif - { + , INCancelRideIntentHandling, INSendRideFeedbackIntentHandling { } /// Composite interface for adopting all of lists and notes protocols. @@ -3669,13 +3481,7 @@ interface INEndWorkoutIntentHandling { void HandleEndWorkout (INEndWorkoutIntent intent, Action completion); [Export ("confirmEndWorkout:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmEndWorkout -#endif - (INEndWorkoutIntent intent, Action completion); + void Confirm (INEndWorkoutIntent intent, Action completion); [Export ("resolveWorkoutNameForEndWorkout:withCompletion:")] void ResolveWorkoutName (INEndWorkoutIntent intent, Action completion); @@ -3745,13 +3551,7 @@ interface INGetAvailableRestaurantReservationBookingDefaultsIntentHandling { void HandleAvailableRestaurantReservationBookingDefaults (INGetAvailableRestaurantReservationBookingDefaultsIntent intent, Action completion); [Export ("confirmGetAvailableRestaurantReservationBookingDefaults:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmAvailableRestaurantReservationBookingDefaults -#endif - (INGetAvailableRestaurantReservationBookingDefaultsIntent intent, Action completion); + void Confirm (INGetAvailableRestaurantReservationBookingDefaultsIntent intent, Action completion); [Export ("resolveRestaurantForGetAvailableRestaurantReservationBookingDefaults:withCompletion:")] void ResolveAvailableRestaurantReservationBookingDefaults (INGetAvailableRestaurantReservationBookingDefaultsIntent intent, Action completion); @@ -3833,13 +3633,7 @@ interface INGetAvailableRestaurantReservationBookingsIntentHandling { void HandleAvailableRestaurantReservationBookings (INGetAvailableRestaurantReservationBookingsIntent intent, Action completion); [Export ("confirmGetAvailableRestaurantReservationBookings:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmAvailableRestaurantReservationBookings -#endif - (INGetAvailableRestaurantReservationBookingsIntent intent, Action completion); + void Confirm (INGetAvailableRestaurantReservationBookingsIntent intent, Action completion); [Export ("resolveRestaurantForGetAvailableRestaurantReservationBookings:withCompletion:")] void ResolveAvailableRestaurantReservationBookings (INGetAvailableRestaurantReservationBookingsIntent intent, Action completion); @@ -3902,13 +3696,7 @@ interface INGetRestaurantGuestIntentHandling { void HandleRestaurantGuest (INGetRestaurantGuestIntent intent, Action completion); [Export ("confirmGetRestaurantGuest:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmRestaurantGuest -#endif - (INGetRestaurantGuestIntent guestIntent, Action completion); + void Confirm (INGetRestaurantGuestIntent guestIntent, Action completion); } /// @@ -3969,13 +3757,7 @@ interface INGetRideStatusIntentHandling { void StopSendingUpdates (INGetRideStatusIntent intent); [Export ("confirmGetRideStatus:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmRideStatus -#endif - (INGetRideStatusIntent intent, Action completion); + void Confirm (INGetRideStatusIntent intent, Action completion); } interface IINGetRideStatusIntentResponseObserver { } @@ -4055,13 +3837,7 @@ interface INGetUserCurrentRestaurantReservationBookingsIntentHandling { void HandleUserCurrentRestaurantReservationBookings (INGetUserCurrentRestaurantReservationBookingsIntent intent, Action completion); [Export ("confirmGetUserCurrentRestaurantReservationBookings:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmUserCurrentRestaurantReservationBookings -#endif - (INGetUserCurrentRestaurantReservationBookingsIntent intent, Action completion); + void Confirm (INGetUserCurrentRestaurantReservationBookingsIntent intent, Action completion); [Export ("resolveRestaurantForGetUserCurrentRestaurantReservationBookings:withCompletion:")] void ResolveUserCurrentRestaurantReservationBookings (INGetUserCurrentRestaurantReservationBookingsIntent intent, Action completion); @@ -4394,13 +4170,7 @@ interface INListRideOptionsIntentHandling { void HandleListRideOptions (INListRideOptionsIntent intent, Action completion); [Export ("confirmListRideOptions:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmListRideOptions -#endif - (INListRideOptionsIntent intent, Action completion); + void Confirm (INListRideOptionsIntent intent, Action completion); [Export ("resolvePickupLocationForListRideOptions:withCompletion:")] void ResolvePickupLocation (INListRideOptionsIntent intent, Action completion); @@ -4437,14 +4207,10 @@ interface INListRideOptionsIntentResponse { NSDate ExpirationDate { get; set; } } -#if NET /// Encapsulates Intents / SiriKit information regarding a messaging-service message. /// /// Apple documentation for INMessage [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] @@ -4587,15 +4353,11 @@ [NullAllowed] INMessageReaction reaction } -#if NET /// /// for resolving parameters in interactions involving messages. /// /// Apple documentation for INMessageAttributeOptionsResolutionResult [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (INIntentResolutionResult))] @@ -4603,32 +4365,14 @@ [NullAllowed] INMessageReaction reaction interface INMessageAttributeOptionsResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedMessageAttributeOptions:")] - INMessageAttributeOptionsResolutionResult SuccessWithResolvedMessageAttributeOptions (INMessageAttributeOptions resolvedMessageAttributeOptions); - - [Internal] - [Deprecated (PlatformName.MacOSX, 10, 13)] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INMessageAttributeOptionsResolutionResult SuccessWithResolvedValue (INMessageAttributeOptions resolvedValue); + INMessageAttributeOptionsResolutionResult GetSuccess (INMessageAttributeOptions resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithMessageAttributeOptionsToConfirm:")] - INMessageAttributeOptionsResolutionResult ConfirmationRequiredWithMessageAttributeOptionsToConfirm (INMessageAttributeOptions messageAttributeOptionsToConfirm); - - [Internal] - [Deprecated (PlatformName.MacOSX, 10, 13)] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INMessageAttributeOptionsResolutionResult ConfirmationRequiredWithValueToConfirm (INMessageAttributeOptions valueToConfirm); + INMessageAttributeOptionsResolutionResult GetConfirmationRequired (INMessageAttributeOptions valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -4663,13 +4407,11 @@ interface INMessageAttributeOptionsResolutionResult { INMessageAttributeOptionsResolutionResult GetConfirmationRequired (NSObject itemToConfirm, nint reason); } -#if NET /// /// for resolving parameters in interactions involving messages. /// /// Apple documentation for INMessageAttributeResolutionResult [NoMac] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (INIntentResolutionResult))] @@ -4677,30 +4419,14 @@ interface INMessageAttributeOptionsResolutionResult { interface INMessageAttributeResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedMessageAttribute:")] - INMessageAttributeResolutionResult SuccessWithResolvedMessageAttribute (INMessageAttribute resolvedMessageAttribute); - - [Internal] - [MacCatalyst (13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INMessageAttributeResolutionResult SuccessWithResolvedValue (INMessageAttribute resolvedValue); + INMessageAttributeResolutionResult GetSuccess (INMessageAttribute resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithMessageAttributeToConfirm:")] - INMessageAttributeResolutionResult ConfirmationRequiredWithMessageAttributeToConfirm (INMessageAttribute messageAttributeToConfirm); - - [Internal] - [Deprecated (PlatformName.MacOSX, 10, 13)] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INMessageAttributeResolutionResult ConfirmationRequiredWithValueToConfirm (INMessageAttribute valueToConfirm); + INMessageAttributeResolutionResult GetConfirmationRequired (INMessageAttribute valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -4763,13 +4489,7 @@ interface INPauseWorkoutIntentHandling { void HandlePauseWorkout (INPauseWorkoutIntent intent, Action completion); [Export ("confirmPauseWorkout:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmPauseWorkout -#endif - (INPauseWorkoutIntent intent, Action completion); + void Confirm (INPauseWorkoutIntent intent, Action completion); [Export ("resolveWorkoutNameForPauseWorkout:withCompletion:")] void ResolveWorkoutName (INPauseWorkoutIntent intent, Action completion); @@ -5093,9 +4813,7 @@ interface INPlacemarkResolutionResult { } [Unavailable (PlatformName.MacOSX)] -#if NET || TVOS || __MACCATALYST__ [DisableDefaultCtor] -#endif [TV (14, 0)] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] @@ -5166,30 +4884,14 @@ interface INPriceRange : NSCopying, NSSecureCoding { interface INRadioTypeResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedRadioType:")] - INRadioTypeResolutionResult SuccessWithResolvedRadioType (INRadioType resolvedRadioType); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INRadioTypeResolutionResult SuccessWithResolvedValue (INRadioType resolvedValue); + INRadioTypeResolutionResult GetSuccess (INRadioType resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithRadioTypeToConfirm:")] - INRadioTypeResolutionResult ConfirmationRequiredWithRadioTypeToConfirm (INRadioType radioTypeToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INRadioTypeResolutionResult ConfirmationRequiredWithValueToConfirm (INRadioType valueToConfirm); + INRadioTypeResolutionResult GetConfirmationRequired (INRadioType valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -5238,30 +4940,14 @@ interface INRadioTypeResolutionResult { interface INRelativeReferenceResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedRelativeReference:")] - INRelativeReferenceResolutionResult SuccessWithResolvedRelativeReference (INRelativeReference resolvedRelativeReference); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INRelativeReferenceResolutionResult SuccessWithResolvedValue (INRelativeReference resolvedValue); + INRelativeReferenceResolutionResult GetSuccess (INRelativeReference resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithRelativeReferenceToConfirm:")] - INRelativeReferenceResolutionResult ConfirmationRequiredWithRelativeReferenceToConfirm (INRelativeReference relativeReferenceToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INRelativeReferenceResolutionResult ConfirmationRequiredWithValueToConfirm (INRelativeReference valueToConfirm); + INRelativeReferenceResolutionResult GetConfirmationRequired (INRelativeReference valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -5310,30 +4996,14 @@ interface INRelativeReferenceResolutionResult { interface INRelativeSettingResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedRelativeSetting:")] - INRelativeSettingResolutionResult SuccessWithResolvedRelativeSetting (INRelativeSetting resolvedRelativeSetting); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INRelativeSettingResolutionResult SuccessWithResolvedValue (INRelativeSetting resolvedValue); + INRelativeSettingResolutionResult GetSuccess (INRelativeSetting resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithRelativeSettingToConfirm:")] - INRelativeSettingResolutionResult ConfirmationRequiredWithRelativeSettingToConfirm (INRelativeSetting relativeSettingToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INRelativeSettingResolutionResult ConfirmationRequiredWithValueToConfirm (INRelativeSetting valueToConfirm); + INRelativeSettingResolutionResult GetConfirmationRequired (INRelativeSetting valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -5402,13 +5072,7 @@ interface INRequestPaymentIntentHandling { void HandleRequestPayment (INRequestPaymentIntent intent, Action completion); [Export ("confirmRequestPayment:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmRequestPayment -#endif - (INRequestPaymentIntent intent, Action completion); + void Confirm (INRequestPaymentIntent intent, Action completion); [Deprecated (PlatformName.iOS, 11, 0, message: "Use 'ResolvePayer (INRequestPaymentIntent, Action)' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'ResolvePayer (INRequestPaymentIntent, Action)' instead.")] @@ -5504,13 +5168,7 @@ interface INRequestRideIntentHandling { void HandleRequestRide (INRequestRideIntent intent, Action completion); [Export ("confirmRequestRide:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmRequestRide -#endif - (INRequestRideIntent intent, Action completion); + void Confirm (INRequestRideIntent intent, Action completion); [Export ("resolvePickupLocationForRequestRide:withCompletion:")] void ResolvePickupLocation (INRequestRideIntent intent, Action completion); @@ -5873,13 +5531,7 @@ interface INResumeWorkoutIntentHandling { void HandleResumeWorkout (INResumeWorkoutIntent intent, Action completion); [Export ("confirmResumeWorkout:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmResumeWorkout -#endif - (INResumeWorkoutIntent intent, Action completion); + void Confirm (INResumeWorkoutIntent intent, Action completion); [Export ("resolveWorkoutNameForResumeWorkout:withCompletion:")] void ResolveWorkoutName (INResumeWorkoutIntent intent, Action completion); @@ -6044,9 +5696,9 @@ interface INRideOption : NSCopying, NSSecureCoding { [NullAllowed, Export ("priceRange", ArgumentSemantic.Copy)] INPriceRange PriceRange { get; set; } - [Internal] + [BindAs (typeof (bool?))] [NullAllowed, Export ("usesMeteredFare", ArgumentSemantic.Copy)] - NSNumber _UsesMeteredFare { get; set; } + NSNumber UsesMeteredFare { get; set; } [NullAllowed, Export ("disclaimerMessage")] string DisclaimerMessage { get; set; } @@ -6186,15 +5838,14 @@ interface INRideVehicle : NSCopying, NSSecureCoding { [Deprecated (PlatformName.MacCatalyst, 15, 0)] [BaseType (typeof (INIntent))] interface INSaveProfileInCarIntent { - - [Deprecated (PlatformName.iOS, 10, 2)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithProfileNumber:profileLabel:"), Internal] - IntPtr InitWithProfileNumberLabel ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileLabel); - [MacCatalyst (13, 1)] - [Export ("initWithProfileNumber:profileName:"), Internal] - IntPtr InitWithProfileNumberName ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileName); + [DesignatedInitializer] + [Export ("initWithProfileNumber:profileName:")] +#if XAMCORE_5_0 + NativeHandle Constructor ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileName); +#else + NativeHandle Constructor ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileLabel); +#endif [NullAllowed, Export ("profileNumber", ArgumentSemantic.Copy)] NSNumber ProfileNumber { get; } @@ -6222,13 +5873,7 @@ interface INSaveProfileInCarIntentHandling { void HandleSaveProfileInCar (INSaveProfileInCarIntent intent, Action completion); [Export ("confirmSaveProfileInCar:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSaveProfileInCar -#endif - (INSaveProfileInCarIntent intent, Action completion); + void Confirm (INSaveProfileInCarIntent intent, Action completion); [Export ("resolveProfileNumberForSaveProfileInCar:withCompletion:")] void ResolveProfileNumber (INSaveProfileInCarIntent intent, Action completion); @@ -6259,14 +5904,10 @@ interface INSaveProfileInCarIntentResponse { INSaveProfileInCarIntentResponseCode Code { get; } } -#if NET /// An indicating the user wishes to search the call history. /// /// Apple documentation for INSearchCallHistoryIntent [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 15, 0)] [NoTV] [MacCatalyst (13, 1)] @@ -6312,11 +5953,7 @@ interface INSearchCallHistoryIntent { NSNumber WeakUnseen { get; } } -#if NET [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 15, 0)] [NoTV] [MacCatalyst (13, 1)] @@ -6329,13 +5966,7 @@ interface INSearchCallHistoryIntentHandling { void HandleSearchCallHistory (INSearchCallHistoryIntent intent, Action completion); [Export ("confirmSearchCallHistory:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSearchCallHistory -#endif - (INSearchCallHistoryIntent intent, Action completion); + void Confirm (INSearchCallHistoryIntent intent, Action completion); [Deprecated (PlatformName.MacOSX, 10, 13, message: "Use 'ResolveCallTypes' instead.")] [Deprecated (PlatformName.iOS, 11, 0, message: "Use 'ResolveCallTypes' instead.")] @@ -6359,15 +5990,11 @@ interface INSearchCallHistoryIntentHandling { void ResolveUnseen (INSearchCallHistoryIntent intent, Action completion); } -#if NET /// /// subclass that developers of interface implementations populate with their extension's results. /// /// Apple documentation for INSearchCallHistoryIntentResponse [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 15, 0)] [NoTV] [MacCatalyst (13, 1)] @@ -6388,14 +6015,10 @@ interface INSearchCallHistoryIntentResponse { INCallRecord [] CallRecords { get; set; } } -#if NET /// An indicating the user wishes to search their message history. /// /// Apple documentation for INSearchForMessagesIntent [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (INIntent))] @@ -6484,11 +6107,7 @@ interface INSearchForMessagesIntent { INConditionalOperator ConversationIdentifiersOperator { get; } } -#if NET [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [Protocol] @@ -6499,13 +6118,7 @@ interface INSearchForMessagesIntentHandling { void HandleSearchForMessages (INSearchForMessagesIntent intent, Action completion); [Export ("confirmSearchForMessages:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSearchForMessages -#endif - (INSearchForMessagesIntent intent, Action completion); + void Confirm (INSearchForMessagesIntent intent, Action completion); [Export ("resolveRecipientsForSearchForMessages:withCompletion:")] void ResolveRecipients (INSearchForMessagesIntent intent, Action completion); @@ -6530,15 +6143,11 @@ interface INSearchForMessagesIntentHandling { void ResolveSpeakableGroupNames (INSearchForMessagesIntent intent, Action completion); } -#if NET /// /// subclass that developers of interface implementations populate with their extension's results. /// /// Apple documentation for INSearchForMessagesIntentResponse [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (INIntentResponse))] @@ -6612,13 +6221,7 @@ interface INSearchForPhotosIntentHandling { void HandleSearchForPhotos (INSearchForPhotosIntent intent, Action completion); [Export ("confirmSearchForPhotos:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSearchForPhotos -#endif - (INSearchForPhotosIntent intent, Action completion); + void Confirm (INSearchForPhotosIntent intent, Action completion); [Export ("resolveDateCreatedForSearchForPhotos:withCompletion:")] void ResolveDateCreated (INSearchForPhotosIntent intent, Action completion); @@ -6757,13 +6360,7 @@ interface INSendMessageIntentHandling { void HandleSendMessage (INSendMessageIntent intent, Action completion); [Export ("confirmSendMessage:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSendMessage -#endif - (INSendMessageIntent intent, Action completion); + void Confirm (INSendMessageIntent intent, Action completion); [Deprecated (PlatformName.iOS, 11, 0, message: "Use 'ResolveRecipients (INSendMessageIntent, Action)' instead.")] [Deprecated (PlatformName.MacOSX, 10, 13, message: "Use 'ResolveRecipients (INSendMessageIntent, Action)' instead.")] @@ -6789,9 +6386,7 @@ interface INSendMessageIntentHandling { [Export ("resolveOutgoingMessageTypeForSendMessage:withCompletion:")] void ResolveOutgoingMessageType (INSendMessageIntent intent, Action completion); -#if NET [NoMac] // The INSpeakableStringResolutionResult used as a parameter type is not available in macOS -#endif [MacCatalyst (13, 1)] [Export ("resolveSpeakableGroupNameForSendMessage:withCompletion:")] void ResolveSpeakableGroupName (INSendMessageIntent intent, Action completion); @@ -6814,9 +6409,7 @@ interface INSendMessageIntentResponse { [Export ("code")] INSendMessageIntentResponseCode Code { get; } -#if NET [NoMac] // The INMessage type isn't available in macOS -#endif [Deprecated (PlatformName.iOS, 16, 0, message: "Use the 'SentMessages' property instead.")] [Deprecated (PlatformName.MacCatalyst, 16, 0, message: "Use the 'SentMessages' property instead.")] [MacCatalyst (13, 1)] @@ -6864,13 +6457,7 @@ interface INSendPaymentIntentHandling { void HandleSendPayment (INSendPaymentIntent intent, Action completion); [Export ("confirmSendPayment:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSendPayment -#endif - (INSendPaymentIntent intent, Action completion); + void Confirm (INSendPaymentIntent intent, Action completion); [Deprecated (PlatformName.iOS, 11, 0, message: "Use 'ResolvePayee (INSendPaymentIntent, Action)' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'ResolvePayee (INSendPaymentIntent, Action)' instead.")] @@ -6951,13 +6538,7 @@ interface INSetAudioSourceInCarIntentHandling { void HandleSetAudioSourceInCar (INSetAudioSourceInCarIntent intent, Action completion); [Export ("confirmSetAudioSourceInCar:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetAudioSourceInCar -#endif - (INSetAudioSourceInCarIntent intent, Action completion); + void Confirm (INSetAudioSourceInCarIntent intent, Action completion); [Export ("resolveAudioSourceForSetAudioSourceInCar:withCompletion:")] void ResolveAudioSource (INSetAudioSourceInCarIntent intent, Action completion); @@ -7028,15 +6609,11 @@ interface INSetClimateSettingsInCarIntent { [Export ("airCirculationMode", ArgumentSemantic.Assign)] INCarAirCirculationMode AirCirculationMode { get; } -#if NET [BindAs (typeof (int?))] -#endif [NullAllowed, Export ("fanSpeedIndex", ArgumentSemantic.Copy)] NSNumber FanSpeedIndex { get; } -#if NET [BindAs (typeof (double?))] -#endif [NullAllowed, Export ("fanSpeedPercentage", ArgumentSemantic.Copy)] NSNumber FanSpeedPercentage { get; } @@ -7070,13 +6647,7 @@ interface INSetClimateSettingsInCarIntentHandling { void HandleSetClimateSettingsInCar (INSetClimateSettingsInCarIntent intent, Action completion); [Export ("confirmSetClimateSettingsInCar:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetClimateSettingsInCar -#endif - (INSetClimateSettingsInCarIntent intent, Action completion); + void Confirm (INSetClimateSettingsInCarIntent intent, Action completion); [Export ("resolveEnableFanForSetClimateSettingsInCar:withCompletion:")] void ResolveEnableFan (INSetClimateSettingsInCarIntent intent, Action completion); @@ -7184,13 +6755,7 @@ interface INSetDefrosterSettingsInCarIntentHandling { void HandleSetDefrosterSettingsInCar (INSetDefrosterSettingsInCarIntent intent, Action completion); [Export ("confirmSetDefrosterSettingsInCar:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetDefrosterSettingsInCar -#endif - (INSetDefrosterSettingsInCarIntent intent, Action completion); + void Confirm (INSetDefrosterSettingsInCarIntent intent, Action completion); [Export ("resolveEnableForSetDefrosterSettingsInCar:withCompletion:")] void ResolveEnable (INSetDefrosterSettingsInCarIntent intent, Action completion); @@ -7255,13 +6820,7 @@ interface INSetMessageAttributeIntentHandling { void HandleSetMessageAttribute (INSetMessageAttributeIntent intent, Action completion); [Export ("confirmSetMessageAttribute:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetMessageAttribute -#endif - (INSetMessageAttributeIntent intent, Action completion); + void Confirm (INSetMessageAttributeIntent intent, Action completion); [Export ("resolveAttributeForSetMessageAttribute:withCompletion:")] void ResolveAttribute (INSetMessageAttributeIntent intent, Action completion); @@ -7296,26 +6855,23 @@ interface INSetMessageAttributeIntentResponse { [Deprecated (PlatformName.MacCatalyst, 15, 0)] [BaseType (typeof (INIntent))] interface INSetProfileInCarIntent { - - [Deprecated (PlatformName.iOS, 10, 2)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Export ("initWithProfileNumber:profileLabel:defaultProfile:"), Internal] - IntPtr InitWithProfileNumberLabel ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileLabel, [NullAllowed] NSNumber defaultProfile); - + [Protected] [Deprecated (PlatformName.iOS, 12, 0, message: "Use the overload that takes 'INSpeakableString carName'.")] [MacCatalyst (13, 1)] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use the overload that takes 'INSpeakableString carName'.")] - [Export ("initWithProfileNumber:profileName:defaultProfile:"), Internal] - IntPtr InitWithProfileNumberName ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileName, [NullAllowed] NSNumber defaultProfile); + [Export ("initWithProfileNumber:profileName:defaultProfile:")] +#if XAMCORE_5_0 + NativeHandle Constructor ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileName, [NullAllowed] NSNumber defaultProfile); +#else + NativeHandle Constructor ([NullAllowed] NSNumber profileNumber, [NullAllowed] string profileLabel, [NullAllowed] NSNumber defaultProfile); +#endif [MacCatalyst (13, 1)] [Export ("initWithProfileNumber:profileName:defaultProfile:carName:")] [DesignatedInitializer] NativeHandle Constructor ([NullAllowed][BindAs (typeof (int?))] NSNumber profileNumber, [NullAllowed] string profileName, [NullAllowed][BindAs (typeof (bool?))] NSNumber defaultProfile, [NullAllowed] INSpeakableString carName); -#if NET [BindAs (typeof (int?))] -#endif [NullAllowed, Export ("profileNumber", ArgumentSemantic.Copy)] NSNumber ProfileNumber { get; } @@ -7350,13 +6906,7 @@ interface INSetProfileInCarIntentHandling { void HandleSetProfileInCar (INSetProfileInCarIntent intent, Action completion); [Export ("confirmSetProfileInCar:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetProfileInCar -#endif - (INSetProfileInCarIntent intent, Action completion); + void Confirm (INSetProfileInCarIntent intent, Action completion); [Export ("resolveProfileNumberForSetProfileInCar:withCompletion:")] void ResolveProfileNumber (INSetProfileInCarIntent intent, Action completion); @@ -7440,13 +6990,7 @@ interface INSetRadioStationIntentHandling { void HandleSetRadioStation (INSetRadioStationIntent intent, Action completion); [Export ("confirmSetRadioStation:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetRadioStation -#endif - (INSetRadioStationIntent intent, Action completion); + void Confirm (INSetRadioStationIntent intent, Action completion); [Export ("resolveRadioTypeForSetRadioStation:withCompletion:")] void ResolveRadioType (INSetRadioStationIntent intent, Action completion); @@ -7522,9 +7066,7 @@ interface INSetSeatSettingsInCarIntent { [Export ("seat", ArgumentSemantic.Assign)] INCarSeat Seat { get; } -#if NET [BindAs (typeof (int?))] -#endif [NullAllowed, Export ("level", ArgumentSemantic.Copy)] NSNumber Level { get; } @@ -7549,13 +7091,7 @@ interface INSetSeatSettingsInCarIntentHandling { void HandleSetSeatSettingsInCar (INSetSeatSettingsInCarIntent intent, Action completion); [Export ("confirmSetSeatSettingsInCar:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetSeatSettingsInCar -#endif - (INSetSeatSettingsInCarIntent intent, Action completion); + void Confirm (INSetSeatSettingsInCarIntent intent, Action completion); [Export ("resolveEnableHeatingForSetSeatSettingsInCar:withCompletion:")] void ResolveEnableHeating (INSetSeatSettingsInCarIntent intent, Action completion); @@ -7663,16 +7199,12 @@ interface INSpeakable { string PronunciationHint { get; } [MacCatalyst (13, 1)] -#if NET [Abstract] -#endif [NullAllowed, Export ("vocabularyIdentifier")] string VocabularyIdentifier { get; } [MacCatalyst (13, 1)] -#if NET [Abstract] -#endif [NullAllowed, Export ("alternativeSpeakableMatches")] IINSpeakable [] AlternativeSpeakableMatches { get; } @@ -7680,9 +7212,6 @@ interface INSpeakable { [Deprecated (PlatformName.iOS, 11, 0, message: "Use 'VocabularyIdentifier' instead.")] [Deprecated (PlatformName.TvOS, 11, 0, message: "Use 'VocabularyIdentifier' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'VocabularyIdentifier' instead.")] -#if !NET - [Abstract] -#endif [NullAllowed, Export ("identifier")] string Identifier { get; } } @@ -7694,30 +7223,20 @@ interface INSpeakable { interface INSpeakableString : INSpeakable, NSCopying, NSSecureCoding { [MacCatalyst (13, 1)] - [Internal] [Export ("initWithVocabularyIdentifier:spokenPhrase:pronunciationHint:")] - IntPtr InitWithVocabularyIdentifier (string vocabularyIdentifier, string spokenPhrase, [NullAllowed] string pronunciationHint); - - [NoTV] - [MacCatalyst (13, 1)] - [Internal] - [Export ("initWithIdentifier:spokenPhrase:pronunciationHint:")] - IntPtr InitWithIdentifier (string identifier, string spokenPhrase, [NullAllowed] string pronunciationHint); + [DesignatedInitializer] + NativeHandle Constructor (string identifier, string spokenPhrase, [NullAllowed] string pronunciationHint); [MacCatalyst (13, 1)] [Export ("initWithSpokenPhrase:")] NativeHandle Constructor (string spokenPhrase); } -#if NET /// /// for resolving parameters in interactions involving arbitrary strings. /// /// Apple documentation for INSpeakableStringResolutionResult [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (INIntentResolutionResult))] @@ -7769,14 +7288,10 @@ interface INSpeakableStringResolutionResult { INSpeakableStringResolutionResult GetConfirmationRequired (NSObject itemToConfirm, nint reason); } -#if NET /// An indicating the user wishes to start an audio call. /// /// Apple documentation for INStartAudioCallIntent [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntent' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -7803,11 +7318,7 @@ interface INStartAudioCallIntent { INPerson [] Contacts { get; } } -#if NET [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntentHandling' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -7820,13 +7331,7 @@ interface INStartAudioCallIntentHandling { void HandleStartAudioCall (INStartAudioCallIntent intent, Action completion); [Export ("confirmStartAudioCall:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmStartAudioCall -#endif - (INStartAudioCallIntent intent, Action completion); + void Confirm (INStartAudioCallIntent intent, Action completion); [MacCatalyst (13, 1)] [Export ("resolveDestinationTypeForStartAudioCall:withCompletion:")] @@ -7836,15 +7341,11 @@ interface INStartAudioCallIntentHandling { void ResolveContacts (INStartAudioCallIntent intent, Action completion); } -#if NET /// /// subclass that developers of interface implementations populate with their extension's results. /// /// Apple documentation for INStartAudioCallIntentResponse [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntentResponse' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -7917,13 +7418,7 @@ interface INStartPhotoPlaybackIntentHandling { void HandleStartPhotoPlayback (INStartPhotoPlaybackIntent intent, Action completion); [Export ("confirmStartPhotoPlayback:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmStartPhotoPlayback -#endif - (INStartPhotoPlaybackIntent intent, Action completion); + void Confirm (INStartPhotoPlaybackIntent intent, Action completion); [Export ("resolveDateCreatedForStartPhotoPlayback:withCompletion:")] void ResolveDateCreated (INStartPhotoPlaybackIntent intent, Action completion); @@ -7962,14 +7457,10 @@ interface INStartPhotoPlaybackIntentResponse { NSNumber SearchResultsCount { get; set; } } -#if NET /// An indicating the user wishes to start a video call. /// /// Apple documentation for INStartVideoCallIntent [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntent' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -7985,11 +7476,7 @@ interface INStartVideoCallIntent { INPerson [] Contacts { get; } } -#if NET [NoMac] -#elif MONOMAC - [Deprecated (PlatformName.MacOSX, 10, 15, message: "Use 'INStartCallIntentHandling' instead.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntentHandling' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -8002,27 +7489,17 @@ interface INStartVideoCallIntentHandling { void HandleStartVideoCall (INStartVideoCallIntent intent, Action completion); [Export ("confirmStartVideoCall:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmStartVideoCall -#endif - (INStartVideoCallIntent intent, Action completion); + void Confirm (INStartVideoCallIntent intent, Action completion); [Export ("resolveContactsForStartVideoCall:withCompletion:")] void ResolveContacts (INStartVideoCallIntent intent, Action completion); } -#if NET /// /// subclass that developers of interface implementations populate with their extension's results. /// /// Apple documentation for INStartVideoCallIntentResponse [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [Deprecated (PlatformName.iOS, 13, 0, message: "Use 'INStartCallIntentResponse' instead.")] [NoTV] [MacCatalyst (13, 1)] @@ -8065,9 +7542,9 @@ interface INStartWorkoutIntent { [Export ("workoutLocationType", ArgumentSemantic.Assign)] INWorkoutLocationType WorkoutLocationType { get; } - [Internal] + [BindAs (typeof (bool?))] [NullAllowed, Export ("isOpenEnded", ArgumentSemantic.Copy)] - NSNumber _IsOpenEnded { get; } + NSNumber IsOpenEnded { get; } } [Unavailable (PlatformName.MacOSX)] @@ -8081,13 +7558,7 @@ interface INStartWorkoutIntentHandling { void HandleStartWorkout (INStartWorkoutIntent intent, Action completion); [Export ("confirmStartWorkout:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmStartWorkout -#endif - (INStartWorkoutIntent intent, Action completion); + void Confirm (INStartWorkoutIntent intent, Action completion); [Export ("resolveWorkoutNameForStartWorkout:withCompletion:")] void ResolveWorkoutName (INStartWorkoutIntent intent, Action completion); @@ -8294,30 +7765,14 @@ interface INVocabulary { interface INWorkoutGoalUnitTypeResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedWorkoutGoalUnitType:")] - INWorkoutGoalUnitTypeResolutionResult SuccessWithResolvedWorkoutGoalUnitType (INWorkoutGoalUnitType resolvedWorkoutGoalUnitType); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INWorkoutGoalUnitTypeResolutionResult SuccessWithResolvedValue (INWorkoutGoalUnitType resolvedValue); + INWorkoutGoalUnitTypeResolutionResult GetSuccess (INWorkoutGoalUnitType resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithWorkoutGoalUnitTypeToConfirm:")] - INWorkoutGoalUnitTypeResolutionResult ConfirmationRequiredWithWorkoutGoalUnitTypeToConfirm (INWorkoutGoalUnitType workoutGoalUnitTypeToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INWorkoutGoalUnitTypeResolutionResult ConfirmationRequiredWithValueToConfirm (INWorkoutGoalUnitType valueToConfirm); + INWorkoutGoalUnitTypeResolutionResult GetConfirmationRequired (INWorkoutGoalUnitType valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -8364,30 +7819,14 @@ interface INWorkoutGoalUnitTypeResolutionResult { interface INWorkoutLocationTypeResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedWorkoutLocationType:")] - INWorkoutLocationTypeResolutionResult SuccessWithResolvedWorkoutLocationType (INWorkoutLocationType resolvedWorkoutLocationType); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INWorkoutLocationTypeResolutionResult SuccessWithResolvedValue (INWorkoutLocationType resolvedValue); + INWorkoutLocationTypeResolutionResult GetSuccess (INWorkoutLocationType resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithWorkoutLocationTypeToConfirm:")] - INWorkoutLocationTypeResolutionResult ConfirmationRequiredWithWorkoutLocationTypeToConfirm (INWorkoutLocationType workoutLocationTypeToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INWorkoutLocationTypeResolutionResult ConfirmationRequiredWithValueToConfirm (INWorkoutLocationType valueToConfirm); + INWorkoutLocationTypeResolutionResult GetConfirmationRequired (INWorkoutLocationType valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -8485,13 +7924,7 @@ interface INActivateCarSignalIntentHandling { void HandleActivateCarSignal (INActivateCarSignalIntent intent, Action completion); [Export ("confirmActivateCarSignal:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmActivateCarSignal -#endif - (INActivateCarSignalIntent intent, Action completion); + void Confirm (INActivateCarSignalIntent intent, Action completion); [Export ("resolveCarNameForActivateCarSignal:withCompletion:")] void ResolveCarName (INActivateCarSignalIntent intent, Action completion); @@ -8629,32 +8062,15 @@ interface INBillPayeeResolutionResult { [BaseType (typeof (INIntentResolutionResult))] [DisableDefaultCtor] interface INBillTypeResolutionResult { - - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Internal] - [Static] - [Export ("successWithResolvedValue:")] - INBillTypeResolutionResult SuccessWithResolvedValue (INBillType resolvedValue); - [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedBillType:")] - INBillTypeResolutionResult SuccessWithResolvedBillType (INBillType resolvedBillType); - - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Internal] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INBillTypeResolutionResult ConfirmationRequiredWithValueToConfirm (INBillType valueToConfirm); + INBillTypeResolutionResult GetSuccess (INBillType resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithBillTypeToConfirm:")] - INBillTypeResolutionResult ConfirmationRequiredWithBillTypeToConfirm (INBillType billTypeToConfirm); + INBillTypeResolutionResult GetConfirmationRequired (INBillType valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -8699,30 +8115,14 @@ interface INBillTypeResolutionResult { interface INCarSignalOptionsResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedCarSignalOptions:")] - INCarSignalOptionsResolutionResult SuccessWithResolvedCarSignalOptions (INCarSignalOptions resolvedCarSignalOptions); - - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Internal] - [Static] - [Export ("successWithResolvedValue:")] - INCarSignalOptionsResolutionResult SuccessWithResolvedValue (INCarSignalOptions resolvedValue); + INCarSignalOptionsResolutionResult GetSuccess (INCarSignalOptions resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithCarSignalOptionsToConfirm:")] - INCarSignalOptionsResolutionResult ConfirmationRequiredWithCarSignalOptionsToConfirm (INCarSignalOptions carSignalOptionsToConfirm); - - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Internal] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INCarSignalOptionsResolutionResult ConfirmationRequiredWithValueToConfirm (INCarSignalOptions valueToConfirm); + INCarSignalOptionsResolutionResult GetConfirmationRequired (INCarSignalOptions valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -8784,13 +8184,7 @@ interface INGetCarLockStatusIntentHandling { void HandleGetCarLockStatus (INGetCarLockStatusIntent intent, Action completion); [Export ("confirmGetCarLockStatus:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmGetCarLockStatus -#endif - (INGetCarLockStatusIntent intent, Action completion); + void Confirm (INGetCarLockStatusIntent intent, Action completion); [Export ("resolveCarNameForGetCarLockStatus:withCompletion:")] void ResolveCarName (INGetCarLockStatusIntent intent, Action completion); @@ -8812,12 +8206,9 @@ interface INGetCarLockStatusIntentResponse { [Export ("code")] INGetCarLockStatusIntentResponseCode Code { get; } -#if false // I wish BindAs was a thing right now [BindAs (typeof (bool?))] -#endif - [Internal] [NullAllowed, Export ("locked", ArgumentSemantic.Copy)] - NSNumber _Locked { get; set; } + NSNumber Locked { get; set; } } /// An for retrieving the current power level of a car. @@ -8857,13 +8248,7 @@ interface INGetCarPowerLevelStatusIntentHandling { void StopSendingUpdates (INGetCarPowerLevelStatusIntent intent); [Export ("confirmGetCarPowerLevelStatus:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmGetCarPowerLevelStatus -#endif - (INGetCarPowerLevelStatusIntent intent, Action completion); + void Confirm (INGetCarPowerLevelStatusIntent intent, Action completion); [Export ("resolveCarNameForGetCarPowerLevelStatus:withCompletion:")] void ResolveCarName (INGetCarPowerLevelStatusIntent intent, Action completion); @@ -8905,19 +8290,13 @@ interface INGetCarPowerLevelStatusIntentResponse { [NullAllowed, Export ("carIdentifier")] string CarIdentifier { get; set; } -#if false // I wish BindAs was a thing right now [BindAs (typeof (float?))] -#endif - [Internal] [NullAllowed, Export ("fuelPercentRemaining", ArgumentSemantic.Copy)] - NSNumber _FuelPercentRemaining { get; set; } + NSNumber FuelPercentRemaining { get; set; } -#if false // I wish BindAs was a thing right now [BindAs (typeof (float?))] -#endif - [Internal] [NullAllowed, Export ("chargePercentRemaining", ArgumentSemantic.Copy)] - NSNumber _ChargePercentRemaining { get; set; } + NSNumber ChargePercentRemaining { get; set; } [NullAllowed, Export ("distanceRemaining", ArgumentSemantic.Copy)] NSMeasurement DistanceRemaining { get; set; } @@ -9037,21 +8416,12 @@ interface INPayBillIntent { [Deprecated (PlatformName.MacCatalyst, 15, 0)] [Protocol] interface INPayBillIntentHandling { - -#if NET [Abstract] -#endif [Export ("handlePayBill:completion:")] void HandlePayBill (INPayBillIntent intent, Action completion); [Export ("confirmPayBill:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmPayBill -#endif - (INPayBillIntent intent, Action completion); + void Confirm (INPayBillIntent intent, Action completion); [Export ("resolveBillPayeeForPayBill:withCompletion:")] void ResolveBillPayee (INPayBillIntent intent, Action completion); @@ -9285,30 +8655,14 @@ interface INPaymentAmountResolutionResult { interface INPaymentStatusResolutionResult { [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("successWithResolvedPaymentStatus:")] - INPaymentStatusResolutionResult SuccessWithResolvedPaymentStatus (INPaymentStatus resolvedPaymentStatus); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("successWithResolvedValue:")] - INPaymentStatusResolutionResult SuccessWithResolvedValue (INPaymentStatus resolvedValue); + INPaymentStatusResolutionResult GetSuccess (INPaymentStatus resolvedValue); [MacCatalyst (13, 1)] - [Internal] [Static] [Export ("confirmationRequiredWithPaymentStatusToConfirm:")] - INPaymentStatusResolutionResult ConfirmationRequiredWithPaymentStatusToConfirm (INPaymentStatus paymentStatusToConfirm); - - [Internal] - [Deprecated (PlatformName.iOS, 11, 0)] - [Deprecated (PlatformName.MacCatalyst, 13, 1)] - [Static] - [Export ("confirmationRequiredWithValueToConfirm:")] - INPaymentStatusResolutionResult ConfirmationRequiredWithValueToConfirm (INPaymentStatus valueToConfirm); + INPaymentStatusResolutionResult GetConfirmationRequired (INPaymentStatus valueToConfirm); // Fixes bug 43205. We need to return the inherited type not the base type // because users won't be able to downcast easily @@ -9380,21 +8734,12 @@ interface INSearchForBillsIntent { [Deprecated (PlatformName.MacCatalyst, 15, 0)] [Protocol] interface INSearchForBillsIntentHandling { - -#if NET [Abstract] -#endif [Export ("handleSearchForBills:completion:")] void HandleSearch (INSearchForBillsIntent intent, Action completion); [Export ("confirmSearchForBills:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSearch -#endif - (INSearchForBillsIntent intent, Action completion); + void Confirm (INSearchForBillsIntent intent, Action completion); [Export ("resolveBillPayeeForSearchForBills:withCompletion:")] void ResolveBillPayee (INSearchForBillsIntent intent, Action completion); @@ -9447,12 +8792,9 @@ interface INSetCarLockStatusIntent { [Export ("initWithLocked:carName:")] NativeHandle Constructor ([NullAllowed] NSNumber locked, [NullAllowed] INSpeakableString carName); -#if false // I wish BindAs was a thing right now [BindAs (typeof (bool?))] -#endif - [Internal] [Export ("locked", ArgumentSemantic.Copy), NullAllowed] - NSNumber _Locked { get; } + NSNumber Locked { get; } [Export ("carName", ArgumentSemantic.Copy), NullAllowed] INSpeakableString CarName { get; } @@ -9469,13 +8811,7 @@ interface INSetCarLockStatusIntentHandling { void HandleSetCarLockStatus (INSetCarLockStatusIntent intent, Action completion); [Export ("confirmSetCarLockStatus:completion:")] - void -#if NET // Follow Swift's naming, fixes bug https://bugzilla.xamarin.com/show_bug.cgi?id=59164 - Confirm -#else - ConfirmSetCarLockStatus -#endif - (INSetCarLockStatusIntent intent, Action completion); + void Confirm (INSetCarLockStatusIntent intent, Action completion); [Export ("resolveLockedForSetCarLockStatus:withCompletion:")] void ResolveLocked (INSetCarLockStatusIntent intent, Action completion); @@ -10574,12 +9910,8 @@ interface INNotebookItemTypeResolutionResult { INNotebookItemTypeResolutionResult GetConfirmationRequired (NSObject itemToConfirm, nint reason); } -#if NET /// Represents a custom interface parameter for a developer-defined Siri interaction. [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] @@ -10613,12 +9945,8 @@ interface INParameter : NSCopying, NSSecureCoding { nuint GetIndex (string subKeyPath); } -#if NET /// A repetition rule for date ranges. [NoMac] -#elif MONOMAC - [Obsoleted (PlatformName.MacOSX, 10,0, message: "Unavailable on macOS, will be removed in the future.")] -#endif [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] @@ -14268,6 +13596,7 @@ interface INStartCallIntent : UNNotificationContentProviding { [Deprecated (PlatformName.iOS, 14, 0, message: "Use '.ctor (INCallRecordFilter, INCallRecord, INCallAudioRoute, INCallDestinationType, INPerson[], INCallCapability)' overload instead.")] [Deprecated (PlatformName.MacCatalyst, 14, 0, message: "Use '.ctor (INCallRecordFilter, INCallRecord, INCallAudioRoute, INCallDestinationType, INPerson[], INCallCapability)' overload instead.")] + [Deprecated (PlatformName.MacOSX, 12, 0, message: "Use '.ctor (INCallRecordFilter, INCallRecord, INCallAudioRoute, INCallDestinationType, INPerson[], INCallCapability)' overload instead.")] [Export ("initWithAudioRoute:destinationType:contacts:recordTypeForRedialing:callCapability:")] NativeHandle Constructor (INCallAudioRoute audioRoute, INCallDestinationType destinationType, [NullAllowed] INPerson [] contacts, INCallRecordType recordTypeForRedialing, INCallCapability callCapability); @@ -14294,6 +13623,7 @@ interface INStartCallIntent : UNNotificationContentProviding { [Deprecated (PlatformName.iOS, 14, 0)] [Deprecated (PlatformName.MacCatalyst, 14, 0)] + [Deprecated (PlatformName.MacOSX, 12, 0)] [Export ("recordTypeForRedialing", ArgumentSemantic.Assign)] INCallRecordType RecordTypeForRedialing { get; } diff --git a/src/metal.cs b/src/metal.cs index 34e4abd28161..a913d1b0dc8c 100644 --- a/src/metal.cs +++ b/src/metal.cs @@ -2211,10 +2211,6 @@ partial interface MTLTextureDescriptor : NSCopying { [Export ("mipmapLevelCount")] nuint MipmapLevelCount { get; set; } - [Deprecated (PlatformName.MacOSX, 13, 0)] - [Deprecated (PlatformName.iOS, 16, 0)] - [Deprecated (PlatformName.TvOS, 16, 0)] - [Deprecated (PlatformName.MacCatalyst, 16, 0)] [Export ("sampleCount")] nuint SampleCount { get; set; } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.Generator.cs index 5f7de2c40ec4..3fc642bf1127 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.Generator.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.Generator.cs @@ -5,6 +5,7 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -289,4 +290,33 @@ internal Binding (BindingInfo bindingInfo, string name, ImmutableArray @ ClassDeclarationSyntax classDeclarationSyntax => new Binding (classDeclarationSyntax, context), _ => null }; + + /// + public override string ToString () + { + var sb = new StringBuilder ("Changes: {"); + sb.Append ($"BindingData: '{BindingInfo}', Name: '{Name}', Namespace: ["); + sb.AppendJoin (", ", Namespace); + sb.Append ($"], FullyQualifiedSymbol: '{FullyQualifiedSymbol}', Base: '{Base ?? "null"}', SymbolAvailability: {SymbolAvailability}, "); + sb.Append ("Interfaces: ["); + sb.AppendJoin (", ", Interfaces); + sb.Append ("], Attributes: ["); + sb.AppendJoin (", ", Attributes); + sb.Append ("], UsingDirectives: ["); + sb.AppendJoin (", ", UsingDirectives); + sb.Append ("], Modifiers: ["); + sb.AppendJoin (", ", Modifiers); + sb.Append ("], EnumMembers: ["); + sb.AppendJoin (", ", EnumMembers); + sb.Append ("], Constructors: ["); + sb.AppendJoin (", ", Constructors); + sb.Append ("], Properties: ["); + sb.AppendJoin (", ", Properties); + sb.Append ("], Methods: ["); + sb.AppendJoin (", ", Methods); + sb.Append ("], Events: ["); + sb.AppendJoin (", ", Events); + sb.Append ("] }"); + return sb.ToString (); + } } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs index a9004343b224..275cf769eb9a 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Binding.cs @@ -155,33 +155,4 @@ public ImmutableArray Methods { init => methods = value; } - /// - public override string ToString () - { - var sb = new StringBuilder ("Changes: {"); - sb.Append ($"BindingData: '{BindingInfo}', Name: '{Name}', Namespace: ["); - sb.AppendJoin (", ", Namespace); - sb.Append ($"], FullyQualifiedSymbol: '{FullyQualifiedSymbol}', Base: '{Base ?? "null"}', SymbolAvailability: {SymbolAvailability}, "); - sb.Append ("Interfaces: ["); - sb.AppendJoin (", ", Interfaces); - sb.Append ("], Attributes: ["); - sb.AppendJoin (", ", Attributes); - sb.Append ("], UsingDirectives: ["); - sb.AppendJoin (", ", UsingDirectives); - sb.Append ("], Modifiers: ["); - sb.AppendJoin (", ", Modifiers); - sb.Append ("], EnumMembers: ["); - sb.AppendJoin (", ", EnumMembers); - sb.Append ("], Constructors: ["); - sb.AppendJoin (", ", Constructors); - sb.Append ("], Properties: ["); - sb.AppendJoin (", ", Properties); - sb.Append ("], Methods: ["); - sb.AppendJoin (", ", Methods); - sb.Append ("], Events: ["); - sb.AppendJoin (", ", Events); - sb.Append ("] }"); - return sb.ToString (); - } - } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs index 2ccc0206b43a..82b6a19b8d76 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Constructor.Generator.cs @@ -25,7 +25,7 @@ public static bool TryCreate (ConstructorDeclarationSyntax declaration, RootCont // loop over the parameters of the construct since changes on those implies a change in the generated code foreach (var parameter in constructor.Parameters) { var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal]; - if (!Parameter.TryCreate (parameter, parameterDeclaration, context.SemanticModel, out var parameterChange)) + if (!Parameter.TryCreate (parameter, parameterDeclaration, context, out var parameterChange)) continue; parametersBucket.Add (parameterChange.Value); } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs index b4294e925fe3..c517ab7aaa9f 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Method.Generator.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; +using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.Attributes; @@ -46,6 +47,58 @@ readonly partial struct Method { public bool UsePlainString => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.PlainString); + /// + /// True if the generated code should retain the return value. + /// + public bool RetainReturnValue => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.RetainReturnValue); + + /// + /// True if the generated code should release the return value. + /// + public bool ReleaseReturnValue => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.ReleaseReturnValue); + + /// + /// True if the method was marked as a factory method. + /// + public bool IsFactory => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.Factory); + + /// + /// True if the return type of the method was returned as a proxy object. + /// + public bool IsProxy => ExportMethodData.Flags.HasFlag (ObjCBindings.Method.Proxy); + + /// + /// True if the generated method should use a temp return variable. + /// + public bool UseTempReturn { + get { + var byRefParameterCount = Parameters.Count (p => p.ReferenceKind != ReferenceKind.None); + + // based on the configuration flags of the method and the return type we can decide if we need a + // temp return type +#pragma warning disable format + return (Method: this, ByRefParameterCount: byRefParameterCount) switch { + // focus first on the flags, since those are manually added and have more precedence + { ByRefParameterCount: > 0 } => true, + { Method.ReleaseReturnValue: true } => true, + { Method.IsFactory: true } => true, + { Method.IsProxy: true } => true, + { Method.MarshalNativeExceptions: true, Method.ReturnType.IsVoid: false } => true, + + // focus on the return type + { Method.ReturnType: { IsVoid: false, NeedsStret: true } } => true, + { Method.ReturnType: { IsVoid: false, IsWrapped: true } } => true, + { Method.ReturnType.IsNativeEnum: true } => true, + { Method.ReturnType.SpecialType: SpecialType.System_Boolean + or SpecialType.System_Char or SpecialType.System_Delegate } => true, + { Method.ReturnType.IsDelegate: true } => true, + // default will be false + _ => false + }; +#pragma warning restore format + } + } + public Method (string type, string name, TypeInfo returnType, SymbolAvailability symbolAvailability, ExportData exportMethodData, @@ -76,7 +129,7 @@ public static bool TryCreate (MethodDeclarationSyntax declaration, RootContext c // loop over the parameters of the construct since changes on those implies a change in the generated code foreach (var parameter in method.Parameters) { var parameterDeclaration = declaration.ParameterList.Parameters [parameter.Ordinal]; - if (!Parameter.TryCreate (parameter, parameterDeclaration, context.SemanticModel, out var parameterChange)) + if (!Parameter.TryCreate (parameter, parameterDeclaration, context, out var parameterChange)) continue; parametersBucket.Add (parameterChange.Value); } @@ -90,7 +143,7 @@ public static bool TryCreate (MethodDeclarationSyntax declaration, RootContext c change = new ( type: method.ContainingSymbol.ToDisplayString ().Trim (), // we want the full name name: method.Name, - returnType: new TypeInfo (method.ReturnType), + returnType: new TypeInfo (method.ReturnType, context.Compilation), symbolAvailability: method.GetSupportedPlatforms (), exportMethodData: exportData, attributes: attributes, diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs index 92c6dd302b66..0b13811b63cb 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Parameter.Generator.cs @@ -5,6 +5,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Context; using Microsoft.Macios.Generator.Extensions; namespace Microsoft.Macios.Generator.DataModel; @@ -40,7 +41,7 @@ public bool NeedsNullCheck { } } - public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declaration, SemanticModel semanticModel, + public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declaration, RootContext context, [NotNullWhen (true)] out Parameter? parameter) { DelegateInfo? delegateInfo = null; @@ -49,7 +50,7 @@ public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declarati DelegateInfo.TryCreate (namedTypeSymbol.DelegateInvokeMethod, out delegateInfo); } - parameter = new (symbol.Ordinal, new (symbol.Type), symbol.Name) { + parameter = new (symbol.Ordinal, new (symbol.Type, context.Compilation), symbol.Name) { BindAs = symbol.GetBindFromData (), IsOptional = symbol.IsOptional, IsParams = symbol.IsParams, @@ -57,7 +58,7 @@ public static bool TryCreate (IParameterSymbol symbol, ParameterSyntax declarati DefaultValue = (symbol.HasExplicitDefaultValue) ? symbol.ExplicitDefaultValue?.ToString () : null, ReferenceKind = symbol.RefKind.ToReferenceKind (), Delegate = delegateInfo, - Attributes = declaration.GetAttributeCodeChanges (semanticModel), + Attributes = declaration.GetAttributeCodeChanges (context.SemanticModel), }; return true; } diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs index 261492127b8d..c8a3d0cfa409 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs @@ -82,7 +82,53 @@ public bool UsePlainString /// /// Return if the method invocation should be wrapped by a NSAutoReleasePool. /// - public bool AutoRelease => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Method.AutoRelease); + public bool AutoRelease => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.AutoRelease); + + /// + /// True if the generated code should retain the return value. + /// + public bool RetainReturnValue + => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.RetainReturnValue); + + /// + /// True if the generated code should release the return value. + /// + public bool ReleaseReturnValue + => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.ReleaseReturnValue); + + /// + /// True if the return type of the method was returned as a proxy object. + /// + public bool IsProxy => IsProperty && ExportPropertyData.Value.Flags.HasFlag (ObjCBindings.Property.Proxy); + + /// + /// True if the generated property should use a temp return variable. + /// + public bool UseTempReturn { + get { + // based on the configuration flags of the method and the return type we can decide if we need a + // temp return type +#pragma warning disable format + return this switch { + // focus first on the flags, since those are manually added and have more precedence + { ReleaseReturnValue: true } => true, + { IsProxy: true } => true, + { MarshalNativeExceptions: true, ReturnType.IsVoid: false } => true, + { RequiresDirtyCheck: true } => true, + + // focus on the return type + { ReturnType: { IsVoid: false, NeedsStret: true } } => true, + { ReturnType.IsNativeEnum: true } => true, + { ReturnType.SpecialType: SpecialType.System_Boolean + or SpecialType.System_Char or SpecialType.System_Delegate } => true, + { ReturnType.IsDelegate: true } => true, + // default will be false + _ => false + }; +#pragma warning restore format + } + + } readonly bool? needsBackingField = null; /// @@ -200,7 +246,7 @@ public static bool TryCreate (PropertyDeclarationSyntax declaration, RootContext change = new ( name: memberName, - returnType: new (propertySymbol.Type), + returnType: new (propertySymbol.Type, context.Compilation), symbolAvailability: propertySupportedPlatforms, attributes: attributes, modifiers: [.. declaration.Modifiers], diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs index 6d6bd94348f4..1ed536b5598b 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/TypeInfo.Generator.cs @@ -13,12 +13,22 @@ readonly partial struct TypeInfo { /// public bool IsWrapped { get; init; } + /// + /// True if the type needs to use a stret call. + /// + public bool NeedsStret { get; init; } + + /// + /// True if the type represents a delegate. + /// + public bool IsDelegate { get; init; } + /// /// Returns, if the type is an array, if its elements are a wrapped object from the objc world. /// public bool ArrayElementTypeIsWrapped { get; init; } - internal TypeInfo (ITypeSymbol symbol) : + internal TypeInfo (ITypeSymbol symbol, Compilation compilation) : this ( symbol is IArrayTypeSymbol arrayTypeSymbol ? arrayTypeSymbol.ElementType.ToDisplayString () @@ -31,8 +41,10 @@ symbol is IArrayTypeSymbol arrayTypeSymbol IsReferenceType = symbol.IsReferenceType; IsStruct = symbol.TypeKind == TypeKind.Struct; IsInterface = symbol.TypeKind == TypeKind.Interface; + IsDelegate = symbol.TypeKind == TypeKind.Delegate; IsNativeIntegerType = symbol.IsNativeIntegerType; IsNativeEnum = symbol.HasAttribute (AttributesNames.NativeEnumAttribute); + NeedsStret = symbol.NeedsStret (compilation); // data that we can get from the symbol without being INamedType symbol.GetInheritance ( diff --git a/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs index bde51fd9c459..f871dd9b74f6 100644 --- a/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs +++ b/src/rgen/Microsoft.Macios.Generator/Emitters/BindingSyntaxFactory.ObjCRuntime.cs @@ -673,6 +673,27 @@ internal static LocalDeclarationStatementSyntax GetExceptionHandleAuxVariable () .NormalizeWhitespace (); // no special mono style } + /// + /// Returns a using statement or block for a local declaration. + /// + /// This allows to write the following for a binding: + /// + /// + /// var conde = @" + /// if ({variable} is not null) { + /// {Using (GetAutoreleasePoolVariable ())} + /// } + /// "; + /// + /// + /// + /// + /// + internal static StatementSyntax Using (LocalDeclarationStatementSyntax declaration) + { + return declaration.WithUsingKeyword (Token (SyntaxKind.UsingKeyword).WithTrailingTrivia (Space)); + } + static string? GetObjCMessageSendMethodName (ExportData exportData, TypeInfo returnType, ImmutableArray parameters, bool isSuper = false, bool isStret = false) where T : Enum diff --git a/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs b/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs index c8a88a4163ab..370f54c6e734 100644 --- a/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs +++ b/src/rgen/Microsoft.Macios.Generator/Extensions/SemanticModelExtensions.cs @@ -8,6 +8,25 @@ namespace Microsoft.Macios.Generator.Extensions; static partial class SemanticModelExtensions { + /// + /// Return an array with the namespaces in for the symbol. + /// + /// The symbol whose namespaces we want to retrieve. + /// An array with the namespaces that contain the symbol from bigger to smaller one. + public static ImmutableArray GetNamespaceArray (this ISymbol? symbol) + { + var bucket = ImmutableArray.CreateBuilder (); + var ns = symbol?.ContainingNamespace; + while (ns is not null) { + if (!string.IsNullOrWhiteSpace (ns.Name)) + // prepend the namespace so that we can read from top to bottom + bucket.Insert (0, ns.Name); + ns = ns.ContainingNamespace; + } + + return bucket.ToImmutable (); + } + /// /// Retrieves all the data from a symbol needed for a binding/transformation. /// @@ -27,15 +46,6 @@ public static void GetSymbolData (ISymbol? symbol, name = symbol?.Name ?? string.Empty; baseClass = null; var interfacesBucket = ImmutableArray.CreateBuilder (); - var bucket = ImmutableArray.CreateBuilder (); - var ns = symbol?.ContainingNamespace; - while (ns is not null) { - if (!string.IsNullOrWhiteSpace (ns.Name)) - // prepend the namespace so that we can read from top to bottom - bucket.Insert (0, ns.Name); - ns = ns.ContainingNamespace; - } - if (symbol is INamedTypeSymbol namedTypeSymbol) { baseClass = namedTypeSymbol.BaseType?.ToDisplayString ().Trim (); foreach (var symbolInterface in namedTypeSymbol.Interfaces) { @@ -44,7 +54,7 @@ public static void GetSymbolData (ISymbol? symbol, } symbolAvailability = symbol?.GetSupportedPlatforms () ?? new SymbolAvailability (); interfaces = interfacesBucket.ToImmutable (); - namespaces = bucket.ToImmutableArray (); + namespaces = symbol.GetNamespaceArray (); } } diff --git a/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs b/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs index 9d69de6b7fa0..9aa35defa490 100644 --- a/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs +++ b/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs @@ -126,7 +126,7 @@ static class AttributesNames { /// The [Internal] attribute can be applied to methods or properties and it has the effect of flagging the /// generated code with the internal C# keyword making the code only accessible to code in the generated assembly. /// - [BindingFlag (AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] + [BindingFlag (AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Interface)] public const string InternalAttribute = "InternalAttribute"; public const string IntroducedAttribute = "IntroducedAttribute"; diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs index e25a468c5528..152c65b07cb4 100644 --- a/src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Binding.Transformer.cs @@ -2,13 +2,16 @@ // Licensed under the MIT License. using System.Collections.Immutable; +using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.Availability; using Microsoft.Macios.Generator.Context; using Microsoft.Macios.Generator.Extensions; +using Microsoft.Macios.Transformer.Attributes; using Microsoft.Macios.Transformer.DataModel; +using Microsoft.Macios.Transformer.Extensions; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.Macios.Generator.DataModel; @@ -21,10 +24,22 @@ readonly partial struct Binding { public BindingType BindingType => BindingInfo.BindingType; /// - /// Returhs the binding data of the binding for the given code changes. + /// Returns the binding data of the binding for the given code changes. /// public BindingInfo BindingInfo { get; init; } + + readonly ImmutableArray protocols = ImmutableArray.Empty; + + /// + /// Returns the list of protocols that the binding implements. + /// The names of the protocols DO NOT include the 'I' prefix. + /// + public ImmutableArray Protocols { + get => protocols; + init => protocols = value; + } + /// /// Internal constructor added for testing purposes. /// @@ -49,7 +64,7 @@ internal Binding (string symbolName, FullyQualifiedSymbol = fullyQualifiedSymbol; } - internal Binding (EnumDeclarationSyntax enumDeclaration, ISymbol symbol, RootContext context) + internal Binding (EnumDeclarationSyntax enumDeclaration, INamedTypeSymbol symbol, RootContext context) { SemanticModelExtensions.GetSymbolData ( symbol: symbol, @@ -87,4 +102,147 @@ internal Binding (EnumDeclarationSyntax enumDeclaration, ISymbol symbol, RootCon EnumMembers = bucket.ToImmutable (); } + + /// + /// Retrieve the type of a binding based on its attributes. + /// + /// The dictionary with the attributes of the symbol. + /// The base type attribute of the binding. + /// The type of binding or BindingType.Unknown if it could not be calculated. + static BindingType GetBindingType (Dictionary> attributes, BaseTypeData? baseTypeAttribute) + { + BindingType bindingType; + if (attributes.HasProtocolFlag () || attributes.HasModelFlag ()) { + bindingType = BindingType.Protocol; + } else if (attributes.HasCategoryFlag ()) { + bindingType = BindingType.Category; + } else if (attributes.HasCoreImageFilterAttribute ()) { + bindingType = BindingType.CoreImageFilter; + } else if (baseTypeAttribute is not null) { + bindingType = BindingType.Class; + } else { + // we do not know what type of binding this is, we will discard it later + bindingType = BindingType.Unknown; + } + + return bindingType; + } + + /// + /// Retrieve the base class for a given binding based on its binding infor. + /// + /// The symbol whose base class we want to retrieve.. + /// The binding information. + /// The base class to use for the new style SDK based on the binding information. + static string GetBaseClass (INamedTypeSymbol symbol, BindingInfo bindingInfo) + { + // collecting the base class and the interface is a little more complicated in the older SDK style because + // we have to make the difference between a class base and a protocol base +#pragma warning disable format + return bindingInfo.BindingType switch { + // for classes, use the base type attribute if it exists, otherwise use the default + BindingType.Class => bindingInfo.BaseTypeData?.BaseType ?? "Foundation.NSObject", + BindingType.CoreImageFilter => bindingInfo.BaseTypeData?.BaseType ?? "Foundation.NSObject", + // categories are extension classes and they always inherit from object + BindingType.Category => "object", + // protocols do not have a base class, if anything, they implement other protocols + BindingType.Protocol => string.Empty, + // for unknown types, use the default + _ => "object" + }; +#pragma warning restore format + } + + /// + /// Collects all the interfaces and protocols implemented by a given symbol. + /// + /// The symbol under query. + /// An out array in which the interfaces will be added. + /// An out array in which the protocols will be added. Protocols will not have the 'I' prefix + /// added. + static void GetInterfaceAndProtocols (INamedTypeSymbol symbol, out ImmutableArray interfaces, + out ImmutableArray protocols) + { + // Collecting interfaces is different between the old than the new SDK styles. We need to make the difference + // between actual interfaces and protocols. Protocols, in the old SDK definition, do not have the 'I' prefix, but + // we should not only guide ourselves on the name, but also on the attributes that the user used. + var interfacesBucket = ImmutableArray.CreateBuilder (); + var protocolsBucket = ImmutableArray.CreateBuilder (); + foreach (var symbolInterface in symbol.Interfaces) { + // decide if we are dealing with a protocol/model or interface by looking at the attributes + var interfaceAttrs = symbolInterface.GetAttributeData (); + if (interfaceAttrs.HasProtocolFlag () || interfaceAttrs.HasModelFlag ()) { + protocolsBucket.Add (symbolInterface.ToDisplayString ().Trim ()); + } else { + interfacesBucket.Add (symbolInterface.ToDisplayString ().Trim ()); + } + } + interfaces = interfacesBucket.ToImmutable (); + protocols = protocolsBucket.ToImmutable (); + } + + /// + /// Create a new binding based on the interface declaration. Because in the old SDK old the bindings + /// are represented by an interface, this constructor will ensure that the correct binding type is set. + /// + /// An interface that declares a binding. + /// + /// The current compilation context. + internal Binding (InterfaceDeclarationSyntax interfaceDeclarationSyntax, INamedTypeSymbol symbol, RootContext context) + { + // basic properties of the binding + FullyQualifiedSymbol = interfaceDeclarationSyntax.GetFullyQualifiedIdentifier (); + UsingDirectives = interfaceDeclarationSyntax.SyntaxTree.CollectUsingStatements (); + AttributesDictionary = symbol.GetAttributeData (); + var baseTypeAttribute = symbol.GetBaseTypeData (); + BindingInfo = new (baseTypeAttribute, GetBindingType (AttributesDictionary, baseTypeAttribute)); + name = symbol.Name; + availability = symbol.GetAvailabilityForSymbol (); + namespaces = symbol.GetNamespaceArray (); + baseClass = GetBaseClass (symbol, BindingInfo); + + // retrieve the interfaces and protocols, notice that this are two out params + GetInterfaceAndProtocols (symbol, out interfaces, out protocols); + + // use the helper struct to get the modifiers + var flags = new ModifiersFlags ( + hasAbstractFlag: HasAbstractFlag, + hasInternalFlag: HasInternalFlag, + hasNewFlag: false, // makes no sense on a class/interface + hasOverrideFlag: false, // makes no sense on a class/interface + hasStaticFlag: HasStaticFlag || BindingInfo.BindingType == BindingType.Category // add static for categories + ); + Modifiers = flags.ToClassModifiersArray (); + } + + /// + public override string ToString () + { + var sb = new StringBuilder ("Changes: {"); + sb.Append ($"BindingData: '{BindingInfo}', Name: '{Name}', Namespace: ["); + sb.AppendJoin (", ", Namespace); + sb.Append ($"], FullyQualifiedSymbol: '{FullyQualifiedSymbol}', Base: '{Base ?? "null"}', SymbolAvailability: {SymbolAvailability}, "); + sb.Append ("Interfaces: ["); + sb.AppendJoin (", ", Interfaces); + sb.Append ("], Protocols: ["); + sb.AppendJoin (", ", Protocols); + sb.Append ("], Attributes: ["); + sb.AppendJoin (", ", Attributes); + sb.Append ("], UsingDirectives: ["); + sb.AppendJoin (", ", UsingDirectives); + sb.Append ("], Modifiers: ["); + sb.AppendJoin (", ", Modifiers); + sb.Append ("], EnumMembers: ["); + sb.AppendJoin (", ", EnumMembers); + sb.Append ("], Constructors: ["); + sb.AppendJoin (", ", Constructors); + sb.Append ("], Properties: ["); + sb.AppendJoin (", ", Properties); + sb.Append ("], Methods: ["); + sb.AppendJoin (", ", Methods); + sb.Append ("], Events: ["); + sb.AppendJoin (", ", Events); + sb.Append ("] }"); + return sb.ToString (); + } } diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs index 08d9cc6689ab..dab789c9dd72 100644 --- a/src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Method.Transformer.cs @@ -57,7 +57,7 @@ public Method (string type, // create a helper struct to retrieve the modifiers var flags = new ModifiersFlags (HasAbstractFlag, HasInternalFlag, HasNewFlag, HasOverrideFlag, HasStaticFlag); - Modifiers = flags.ToModifiersArray (); + Modifiers = flags.ToMethodModifiersArray (); } public static bool TryCreate (MethodDeclarationSyntax declaration, RootContext context, diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs index 0d09de4b2e65..d3418f14f55c 100644 --- a/src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/ModifiersFlags.cs @@ -38,10 +38,10 @@ public ModifiersFlags (bool hasAbstractFlag, bool hasInternalFlag, bool hasNewFl } /// - /// Returns the list of modifiers to be used with the provided set of flags. + /// Returns the list of modifiers to be used with the provided set of flags for a method/property. /// /// The list of modifiers to use to write the transformed method/property. - public ImmutableArray ToModifiersArray () + public ImmutableArray ToMethodModifiersArray () { #pragma warning disable format // Modifiers are special because we might be dealing with several flags that the user has set in the method. @@ -98,7 +98,7 @@ public ImmutableArray ToModifiersArray () // general case, but internal { HasInternalFlag: true} => - [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.VirtualKeyword)], + [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)], // general case _ => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.VirtualKeyword), Token (SyntaxKind.PartialKeyword)] @@ -106,4 +106,73 @@ public ImmutableArray ToModifiersArray () #pragma warning restore format } + /// + /// Returns the list of modifiers to be used with the provided set of flags for a method/property. + /// + /// The list of modifiers to use to write the transformed method/property. + public ImmutableArray ToClassModifiersArray () + { +#pragma warning disable format + // Modifiers are special because we might be dealing with several flags that the user has set in the method. + // We have to add the partial keyword so that we can have the partial implementation of the method later generated + // by the roslyn code generator + return this switch { + // internal static partial + { HasNewFlag: false, HasStaticFlag: true, HasInternalFlag: true } + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // public static partial + { HasNewFlag: false, HasStaticFlag: true, HasInternalFlag: false } + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // internal new static partial + { HasNewFlag: true, HasStaticFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // public new static partial + { HasNewFlag: true, HasStaticFlag: true, HasInternalFlag: false } + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.StaticKeyword), Token (SyntaxKind.PartialKeyword)], + + // public new virtual partial + { HasNewFlag: true, HasStaticFlag: false, HasAbstractFlag: false, HasInternalFlag: false } + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.PartialKeyword)], + + // internal new virtual partial + { HasNewFlag: true, HasStaticFlag: false, HasAbstractFlag: false, HasInternalFlag: true } + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.PartialKeyword)], + + // public new abstract + { HasNewFlag: true, HasAbstractFlag: true, HasInternalFlag: false} + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.AbstractKeyword)], + + // internal new abstract + { HasNewFlag: true, HasAbstractFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.NewKeyword), Token (SyntaxKind.AbstractKeyword)], + + // public override partial + { HasNewFlag: false, HasOverrideFlag: true, HasInternalFlag: false} + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.OverrideKeyword), Token (SyntaxKind.PartialKeyword)], + + // internal override partial + { HasNewFlag: false, HasOverrideFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.OverrideKeyword), Token (SyntaxKind.PartialKeyword)], + + // public abstract + { HasAbstractFlag: true, HasInternalFlag: false} + => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.AbstractKeyword)], + + // internal abstract + { HasAbstractFlag: true, HasInternalFlag: true} + => [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.AbstractKeyword)], + + // general case, but internal + { HasInternalFlag: true} => + [Token (SyntaxKind.InternalKeyword), Token (SyntaxKind.PartialKeyword)], + + // general case + _ => [Token (SyntaxKind.PublicKeyword), Token (SyntaxKind.PartialKeyword)] + }; +#pragma warning restore format + } + } diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs index 7e9d95085f4b..cfb71902ae95 100644 --- a/src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/Property.Transformer.cs @@ -95,7 +95,7 @@ internal Property (string name, } else { // create a helper struct to retrieve the modifiers var flags = new ModifiersFlags (HasAbstractFlag, HasInternalFlag, HasNewFlag, HasOverrideFlag, HasStaticFlag); - Modifiers = flags.ToModifiersArray (); + Modifiers = flags.ToMethodModifiersArray (); } } diff --git a/src/rgen/Microsoft.Macios.Transformer/DataModel/TransformerBindingEqualityComparer.cs b/src/rgen/Microsoft.Macios.Transformer/DataModel/TransformerBindingEqualityComparer.cs new file mode 100644 index 000000000000..877564d6b132 --- /dev/null +++ b/src/rgen/Microsoft.Macios.Transformer/DataModel/TransformerBindingEqualityComparer.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.Macios.Generator; +using Microsoft.Macios.Generator.DataModel; + +namespace Microsoft.Macios.Transformer.DataModel; + +class TransformerBindingEqualityComparer : BindingEqualityComparer { + + public override bool Equals (Binding x, Binding y) + { + // call the base, if they are equals, compare the new properties + if (!base.Equals (x, y)) + return false; + + // comparer for when order does not matter. + var ignoreOrderComparer = new CollectionComparer (StringComparer.InvariantCulture); + if (!ignoreOrderComparer.Equals (x.Protocols, y.Protocols)) + return false; + return true; + } +} diff --git a/src/rsp/dotnet/macos-defines-dotnet.rsp b/src/rsp/dotnet/macos-defines-dotnet.rsp index eac757368e9c..7e586f97417f 100644 --- a/src/rsp/dotnet/macos-defines-dotnet.rsp +++ b/src/rsp/dotnet/macos-defines-dotnet.rsp @@ -29,6 +29,7 @@ -d:HAS_COREDATA -d:HAS_COREFOUNDATION -d:HAS_COREGRAPHICS +-d:HAS_COREHAPTICS -d:HAS_COREIMAGE -d:HAS_CORELOCATION -d:HAS_COREMEDIA diff --git a/src/social.cs b/src/social.cs index 8f8a9dcf3fc4..6ae5e0d8e650 100644 --- a/src/social.cs +++ b/src/social.cs @@ -70,6 +70,41 @@ interface SLServiceType { NSString LinkedIn { get; } } + /// Enumeration with the various kinds of social services that can be used. + /// This enumeration is used to map into the underlying set of services offered by the social framework. It is intended to assist code completion while developing and take the gueswork out of using the framework in some entry points that take an NSString as a parameter. + enum SLServiceKind { + [Deprecated (PlatformName.iOS, 11, 0, message: "Use Facebook SDK instead.")] + [Deprecated (PlatformName.MacOSX, 10, 13, message: "Use Facebook SDK instead.")] + [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use Facebook SDK instead.")] + [Field ("SLServiceTypeFacebook")] + Facebook, + + [Deprecated (PlatformName.iOS, 11, 0, message: "Use Twitter SDK instead.")] + [Deprecated (PlatformName.MacOSX, 10, 13, message: "Use Twitter SDK instead.")] + [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use Twitter SDK instead.")] + [Field ("SLServiceTypeTwitter")] + Twitter, + + [Deprecated (PlatformName.iOS, 11, 0, message: "Use Sina Weibo SDK instead.")] + [Deprecated (PlatformName.MacOSX, 10, 13, message: "Use Sina Weibo SDK instead.")] + [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use Sina Weibo SDK instead.")] + [Field ("SLServiceTypeSinaWeibo")] + SinaWeibo, + + [Deprecated (PlatformName.iOS, 11, 0, message: "Use Tencent Weibo SDK instead.")] + [Deprecated (PlatformName.MacOSX, 10, 13, message: "Use Tencent Weibo SDK instead.")] + [Field ("SLServiceTypeTencentWeibo")] + [MacCatalyst (13, 1)] + [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use Tencent Weibo SDK instead.")] + TencentWeibo, + + [Deprecated (PlatformName.MacOSX, 10, 13, message: "Use LinkedIn SDK instead.")] + [Field ("SLServiceTypeLinkedIn")] + [NoiOS] + [NoMacCatalyst] + LinkedIn, + } + /// A request made to a social service. /// /// Apple documentation for SLRequest @@ -81,6 +116,10 @@ interface SLRequest { [Export ("requestForServiceType:requestMethod:URL:parameters:")] SLRequest Create (NSString serviceType, SLRequestMethod requestMethod, NSUrl url, [NullAllowed] NSDictionary parameters); + [Static] + [Wrap ("Create (serviceKind.GetConstant ()!, method, url, parameters)")] + SLRequest Create (SLServiceKind serviceKind, SLRequestMethod method, NSUrl url, [NullAllowed] NSDictionary parameters); + [Deprecated (PlatformName.iOS, 15, 0, message: "Use the non-Apple SDK relating to your account type instead.")] [Deprecated (PlatformName.MacOSX, 12, 0, message: "Use the non-Apple SDK relating to your account type instead.")] [Deprecated (PlatformName.MacCatalyst, 15, 0, message: "Use the non-Apple SDK relating to your account type instead.")] diff --git a/tests/cecil-tests/ApiAvailabilityTest.cs b/tests/cecil-tests/ApiAvailabilityTest.cs index 989251215106..3f92fd43fc3d 100644 --- a/tests/cecil-tests/ApiAvailabilityTest.cs +++ b/tests/cecil-tests/ApiAvailabilityTest.cs @@ -120,8 +120,6 @@ public void FindMissingObsoleteAttributes () "CoreGraphics.CGContext.ShowText(System.Byte[])", "CoreGraphics.CGContext.ShowText(System.String, System.Int32)", "CoreGraphics.CGContext.ShowText(System.String)", - "CoreGraphics.CGContext.ShowTextAtPoint(System.Runtime.InteropServices.NFloat, System.Runtime.InteropServices.NFloat, System.String, System.Int32)", - "CoreGraphics.CGContext.ShowTextAtPoint(System.Runtime.InteropServices.NFloat, System.Runtime.InteropServices.NFloat, System.String)", "CoreGraphics.CGImage PassKit.PKShareablePassMetadata::PassThumbnailImage()", "CoreLocation.CLAuthorizationStatus CoreLocation.CLAuthorizationStatus::Authorized", "CoreLocation.CLAuthorizationStatus CoreLocation.CLAuthorizationStatus::AuthorizedWhenInUse", @@ -176,14 +174,6 @@ public void FindMissingObsoleteAttributes () "HealthKit.HKWorkoutEvent.Create(HealthKit.HKWorkoutEventType, Foundation.NSDate)", "HomeKit.HMEventTrigger.CreatePredicateForEvaluatingTriggerOccurringAfterSignificantEvent(HomeKit.HMSignificantEvent, Foundation.NSDateComponents)", "HomeKit.HMEventTrigger.CreatePredicateForEvaluatingTriggerOccurringBeforeSignificantEvent(HomeKit.HMSignificantEvent, Foundation.NSDateComponents)", - "Intents.INCallRecordType Intents.INStartCallIntent::RecordTypeForRedialing()", - "Intents.INCarChargingConnectorType Intents.INCarChargingConnectorType::Tesla", - "Intents.INSetClimateSettingsInCarIntent..ctor(System.Nullable`1, System.Nullable`1, System.Nullable`1, System.Nullable`1, Intents.INCarAirCirculationMode, Foundation.NSNumber, Foundation.NSNumber, Intents.INRelativeSetting, Foundation.NSMeasurement`1, Intents.INRelativeSetting, Intents.INCarSeat)", - "Intents.INSetDefrosterSettingsInCarIntent..ctor(System.Nullable`1, Intents.INCarDefroster)", - "Intents.INSetProfileInCarIntent..ctor(Foundation.NSNumber, System.String, Foundation.NSNumber)", - "Intents.INSetProfileInCarIntent..ctor(Foundation.NSNumber, System.String, System.Nullable`1)", - "Intents.INSetSeatSettingsInCarIntent..ctor(System.Nullable`1, System.Nullable`1, System.Nullable`1, Intents.INCarSeat, Foundation.NSNumber, Intents.INRelativeSetting)", - "Intents.INStartCallIntent..ctor(Intents.INCallAudioRoute, Intents.INCallDestinationType, Intents.INPerson[], Intents.INCallRecordType, Intents.INCallCapability)", "MapKit.MKOverlayView", "MediaPlayer.MPVolumeSettings.AlertHide()", "MediaPlayer.MPVolumeSettings.AlertShow()", diff --git a/tests/cecil-tests/ConstructorTest.KnownFailures.cs b/tests/cecil-tests/ConstructorTest.KnownFailures.cs index 3520ac353fa6..3b8d9fd54b69 100644 --- a/tests/cecil-tests/ConstructorTest.KnownFailures.cs +++ b/tests/cecil-tests/ConstructorTest.KnownFailures.cs @@ -54,9 +54,6 @@ public partial class ConstructorTest { "HomeKit.HMMatterTopology::.ctor(Foundation.NSObjectFlag)", "HomeKit.HMMatterTopology::.ctor(HomeKit.HMMatterHome[])", "HomeKit.HMMatterTopology::.ctor(ObjCRuntime.NativeHandle)", - "Intents.INPriceRange::.ctor(Intents.INPriceRangeOption,Foundation.NSDecimalNumber,System.String)", - "Intents.INSaveProfileInCarIntent::.ctor(Foundation.NSNumber,System.String)", - "Intents.INSetProfileInCarIntent::.ctor(Foundation.NSNumber,System.String,Foundation.NSNumber)", "MapKit.MKMapCameraZoomRange::.ctor(System.Double,MapKit.MKMapCameraZoomRangeType)", "MapKit.MKPointOfInterestFilter::.ctor(MapKit.MKPointOfInterestCategory[],MapKit.MKPointOfInterestFilterType)", "ModelIO.MDLMesh::.ctor(ModelIO.MDLMesh,System.Int32,System.UInt32,ModelIO.IMDLMeshBufferAllocator)", diff --git a/tests/cecil-tests/Documentation.KnownFailures.txt b/tests/cecil-tests/Documentation.KnownFailures.txt index 218d01ad7ee1..8c19b46077af 100644 --- a/tests/cecil-tests/Documentation.KnownFailures.txt +++ b/tests/cecil-tests/Documentation.KnownFailures.txt @@ -33453,6 +33453,7 @@ M:Foundation.NSBundleResourceRequest.ConditionallyBeginAccessingResourcesAsync M:Foundation.NSCache.add_WillEvictObject(System.EventHandler{Foundation.NSObjectEventArgs}) M:Foundation.NSCache.Dispose(System.Boolean) M:Foundation.NSCache.remove_WillEvictObject(System.EventHandler{Foundation.NSObjectEventArgs}) +M:Foundation.NSCache.SetObjectForKey(Foundation.NSObject,Foundation.NSObject) M:Foundation.NSCacheDelegate_Extensions.WillEvictObject(Foundation.INSCacheDelegate,Foundation.NSCache,Foundation.NSObject) M:Foundation.NSCalendar.#ctor(Foundation.NSCalendarType) M:Foundation.NSCoder.DecodeBytes @@ -36287,8 +36288,6 @@ M:Intents.INBillDetails.Copy(Foundation.NSZone) M:Intents.INBillDetails.EncodeTo(Foundation.NSCoder) M:Intents.INBillPayee.Copy(Foundation.NSZone) M:Intents.INBillPayee.EncodeTo(Foundation.NSCoder) -M:Intents.INBillTypeResolutionResult.GetConfirmationRequired(Intents.INBillType) -M:Intents.INBillTypeResolutionResult.GetSuccess(Intents.INBillType) M:Intents.INBoatReservation.Copy(Foundation.NSZone) M:Intents.INBoatReservation.EncodeTo(Foundation.NSCoder) M:Intents.INBoatTrip.Copy(Foundation.NSZone) @@ -36310,25 +36309,13 @@ M:Intents.INCallRecord.Copy(Foundation.NSZone) M:Intents.INCallRecord.EncodeTo(Foundation.NSCoder) M:Intents.INCallRecordFilter.Copy(Foundation.NSZone) M:Intents.INCallRecordFilter.EncodeTo(Foundation.NSCoder) -M:Intents.INCallRecordTypeResolutionResult.GetConfirmationRequired(Intents.INCallRecordType) -M:Intents.INCallRecordTypeResolutionResult.GetSuccess(Intents.INCallRecordType) M:Intents.INCancelRideIntentHandling_Extensions.Confirm(Intents.IINCancelRideIntentHandling,Intents.INCancelRideIntent,System.Action{Intents.INCancelRideIntentResponse}) M:Intents.INCancelWorkoutIntentHandling_Extensions.Confirm(Intents.IINCancelWorkoutIntentHandling,Intents.INCancelWorkoutIntent,System.Action{Intents.INCancelWorkoutIntentResponse}) M:Intents.INCancelWorkoutIntentHandling_Extensions.ResolveWorkoutName(Intents.IINCancelWorkoutIntentHandling,Intents.INCancelWorkoutIntent,System.Action{Intents.INSpeakableStringResolutionResult}) M:Intents.INCar.Copy(Foundation.NSZone) M:Intents.INCar.EncodeTo(Foundation.NSCoder) -M:Intents.INCarAirCirculationModeResolutionResult.GetConfirmationRequired(Intents.INCarAirCirculationMode) -M:Intents.INCarAirCirculationModeResolutionResult.GetSuccess(Intents.INCarAirCirculationMode) -M:Intents.INCarAudioSourceResolutionResult.GetConfirmationRequired(Intents.INCarAudioSource) -M:Intents.INCarAudioSourceResolutionResult.GetSuccess(Intents.INCarAudioSource) -M:Intents.INCarDefrosterResolutionResult.GetConfirmationRequired(Intents.INCarDefroster) -M:Intents.INCarDefrosterResolutionResult.GetSuccess(Intents.INCarDefroster) M:Intents.INCarHeadUnit.Copy(Foundation.NSZone) M:Intents.INCarHeadUnit.EncodeTo(Foundation.NSCoder) -M:Intents.INCarSeatResolutionResult.GetConfirmationRequired(Intents.INCarSeat) -M:Intents.INCarSeatResolutionResult.GetSuccess(Intents.INCarSeat) -M:Intents.INCarSignalOptionsResolutionResult.GetConfirmationRequired(Intents.INCarSignalOptions) -M:Intents.INCarSignalOptionsResolutionResult.GetSuccess(Intents.INCarSignalOptions) M:Intents.INCreateNoteIntentHandling_Extensions.Confirm(Intents.IINCreateNoteIntentHandling,Intents.INCreateNoteIntent,System.Action{Intents.INCreateNoteIntentResponse}) M:Intents.INCreateNoteIntentHandling_Extensions.ResolveContent(Intents.IINCreateNoteIntentHandling,Intents.INCreateNoteIntent,System.Action{Intents.INNoteContentResolutionResult}) M:Intents.INCreateNoteIntentHandling_Extensions.ResolveGroupName(Intents.IINCreateNoteIntentHandling,Intents.INCreateNoteIntent,System.Action{Intents.INSpeakableStringResolutionResult}) @@ -36419,10 +36406,6 @@ M:Intents.INMediaSearch.Copy(Foundation.NSZone) M:Intents.INMediaSearch.EncodeTo(Foundation.NSCoder) M:Intents.INMessage.Copy(Foundation.NSZone) M:Intents.INMessage.EncodeTo(Foundation.NSCoder) -M:Intents.INMessageAttributeOptionsResolutionResult.GetConfirmationRequired(Intents.INMessageAttributeOptions) -M:Intents.INMessageAttributeOptionsResolutionResult.GetSuccess(Intents.INMessageAttributeOptions) -M:Intents.INMessageAttributeResolutionResult.GetConfirmationRequired(Intents.INMessageAttribute) -M:Intents.INMessageAttributeResolutionResult.GetSuccess(Intents.INMessageAttribute) M:Intents.INMessageLinkMetadata.Copy(Foundation.NSZone) M:Intents.INMessageLinkMetadata.EncodeTo(Foundation.NSCoder) M:Intents.INMessageReaction.Copy(Foundation.NSZone) @@ -36460,8 +36443,6 @@ M:Intents.INPaymentMethod.Copy(Foundation.NSZone) M:Intents.INPaymentMethod.EncodeTo(Foundation.NSCoder) M:Intents.INPaymentRecord.Copy(Foundation.NSZone) M:Intents.INPaymentRecord.EncodeTo(Foundation.NSCoder) -M:Intents.INPaymentStatusResolutionResult.GetConfirmationRequired(Intents.INPaymentStatus) -M:Intents.INPaymentStatusResolutionResult.GetSuccess(Intents.INPaymentStatus) M:Intents.INPerson.#ctor(Intents.INPersonHandle,Foundation.NSPersonNameComponents,System.String,Intents.INImage,System.String,System.String,System.Boolean,Intents.INPersonSuggestionType,Intents.INPerson.INPersonType) M:Intents.INPerson.#ctor(Intents.INPersonHandle,Foundation.NSPersonNameComponents,System.String,Intents.INImage,System.String,System.String,System.Boolean,Intents.INPersonSuggestionType) M:Intents.INPerson.Copy(Foundation.NSZone) @@ -36480,14 +36461,8 @@ M:Intents.INPreferences.RequestSiriAuthorizationAsync M:Intents.INPriceRange.#ctor(Intents.INPriceRangeOption,Foundation.NSDecimalNumber,System.String) M:Intents.INPriceRange.Copy(Foundation.NSZone) M:Intents.INPriceRange.EncodeTo(Foundation.NSCoder) -M:Intents.INRadioTypeResolutionResult.GetConfirmationRequired(Intents.INRadioType) -M:Intents.INRadioTypeResolutionResult.GetSuccess(Intents.INRadioType) M:Intents.INRecurrenceRule.Copy(Foundation.NSZone) M:Intents.INRecurrenceRule.EncodeTo(Foundation.NSCoder) -M:Intents.INRelativeReferenceResolutionResult.GetConfirmationRequired(Intents.INRelativeReference) -M:Intents.INRelativeReferenceResolutionResult.GetSuccess(Intents.INRelativeReference) -M:Intents.INRelativeSettingResolutionResult.GetConfirmationRequired(Intents.INRelativeSetting) -M:Intents.INRelativeSettingResolutionResult.GetSuccess(Intents.INRelativeSetting) M:Intents.INRelevanceProvider.Copy(Foundation.NSZone) M:Intents.INRelevanceProvider.EncodeTo(Foundation.NSCoder) M:Intents.INRelevantShortcut.Copy(Foundation.NSZone) @@ -36540,7 +36515,6 @@ M:Intents.INRideStatus.Copy(Foundation.NSZone) M:Intents.INRideStatus.EncodeTo(Foundation.NSCoder) M:Intents.INRideVehicle.Copy(Foundation.NSZone) M:Intents.INRideVehicle.EncodeTo(Foundation.NSCoder) -M:Intents.INSaveProfileInCarIntent.#ctor(Foundation.NSNumber,System.String) M:Intents.INSaveProfileInCarIntentHandling_Extensions.Confirm(Intents.IINSaveProfileInCarIntentHandling,Intents.INSaveProfileInCarIntent,System.Action{Intents.INSaveProfileInCarIntentResponse}) M:Intents.INSaveProfileInCarIntentHandling_Extensions.ResolveProfileName(Intents.IINSaveProfileInCarIntentHandling,Intents.INSaveProfileInCarIntent,System.Action{Intents.INStringResolutionResult}) M:Intents.INSaveProfileInCarIntentHandling_Extensions.ResolveProfileNumber(Intents.IINSaveProfileInCarIntentHandling,Intents.INSaveProfileInCarIntent,System.Action{Intents.INIntegerResolutionResult}) @@ -36632,7 +36606,6 @@ M:Intents.INSetDefrosterSettingsInCarIntentHandling_Extensions.ResolveDefroster( M:Intents.INSetDefrosterSettingsInCarIntentHandling_Extensions.ResolveEnable(Intents.IINSetDefrosterSettingsInCarIntentHandling,Intents.INSetDefrosterSettingsInCarIntent,System.Action{Intents.INBooleanResolutionResult}) M:Intents.INSetMessageAttributeIntentHandling_Extensions.Confirm(Intents.IINSetMessageAttributeIntentHandling,Intents.INSetMessageAttributeIntent,System.Action{Intents.INSetMessageAttributeIntentResponse}) M:Intents.INSetMessageAttributeIntentHandling_Extensions.ResolveAttribute(Intents.IINSetMessageAttributeIntentHandling,Intents.INSetMessageAttributeIntent,System.Action{Intents.INMessageAttributeResolutionResult}) -M:Intents.INSetProfileInCarIntent.#ctor(Foundation.NSNumber,System.String,Foundation.NSNumber) M:Intents.INSetProfileInCarIntent.#ctor(Foundation.NSNumber,System.String,System.Nullable{System.Boolean}) M:Intents.INSetProfileInCarIntentHandling_Extensions.Confirm(Intents.IINSetProfileInCarIntentHandling,Intents.INSetProfileInCarIntent,System.Action{Intents.INSetProfileInCarIntentResponse}) M:Intents.INSetProfileInCarIntentHandling_Extensions.ResolveCarName(Intents.IINSetProfileInCarIntentHandling,Intents.INSetProfileInCarIntent,System.Action{Intents.INSpeakableStringResolutionResult}) @@ -36671,7 +36644,6 @@ M:Intents.INSnoozeTasksIntentHandling_Extensions.ResolveTasks(Intents.IINSnoozeT M:Intents.INSpatialEventTrigger.Copy(Foundation.NSZone) M:Intents.INSpatialEventTrigger.EncodeTo(Foundation.NSCoder) M:Intents.INSpeakable_Extensions.GetIdentifier(Intents.IINSpeakable) -M:Intents.INSpeakableString.#ctor(System.String,System.String,System.String) M:Intents.INSpeakableString.Copy(Foundation.NSZone) M:Intents.INSpeakableString.EncodeTo(Foundation.NSCoder) M:Intents.INStartAudioCallIntentHandling_Extensions.Confirm(Intents.IINStartAudioCallIntentHandling,Intents.INStartAudioCallIntent,System.Action{Intents.INStartAudioCallIntentResponse}) @@ -36731,10 +36703,6 @@ M:Intents.INVoiceShortcut.Copy(Foundation.NSZone) M:Intents.INVoiceShortcut.EncodeTo(Foundation.NSCoder) M:Intents.INVoiceShortcutCenter.GetAllVoiceShortcutsAsync M:Intents.INVoiceShortcutCenter.GetVoiceShortcutAsync(Foundation.NSUuid) -M:Intents.INWorkoutGoalUnitTypeResolutionResult.GetConfirmationRequired(Intents.INWorkoutGoalUnitType) -M:Intents.INWorkoutGoalUnitTypeResolutionResult.GetSuccess(Intents.INWorkoutGoalUnitType) -M:Intents.INWorkoutLocationTypeResolutionResult.GetConfirmationRequired(Intents.INWorkoutLocationType) -M:Intents.INWorkoutLocationTypeResolutionResult.GetSuccess(Intents.INWorkoutLocationType) M:Intents.NSExtensionContext_ShareExtension.GetIntent(Foundation.NSExtensionContext) M:Intents.NSUserActivity_IntentsAdditions.GetInteraction(Foundation.NSUserActivity) M:Intents.NSUserActivity_IntentsAdditions.GetShortcutAvailability(Foundation.NSUserActivity) @@ -62379,9 +62347,6 @@ P:Intents.IINSpeakable.SpokenPhrase P:Intents.IINSpeakable.VocabularyIdentifier P:Intents.INCallRecord.CallDuration P:Intents.INCallRecord.Unseen -P:Intents.INGetCarLockStatusIntentResponse.Locked -P:Intents.INGetCarPowerLevelStatusIntentResponse.ChargePercentRemaining -P:Intents.INGetCarPowerLevelStatusIntentResponse.FuelPercentRemaining P:Intents.INIntent.Identifier P:Intents.INIntentResolutionResult.NeedsValue P:Intents.INIntentResolutionResult.NotRequired @@ -62395,11 +62360,8 @@ P:Intents.INRideCompletionStatus.Canceled P:Intents.INRideCompletionStatus.Completed P:Intents.INRideCompletionStatus.MissedPickup P:Intents.INRideCompletionStatus.Outstanding -P:Intents.INRideOption.UsesMeteredFare P:Intents.INSearchCallHistoryIntent.Unseen P:Intents.INSendMessageIntentDonationMetadata.ReplyToCurrentUser -P:Intents.INSetCarLockStatusIntent.Locked -P:Intents.INStartWorkoutIntent.IsOpenEnded P:IntentsUI.IINUIHostedViewSiriProviding.DisplaysMap P:IntentsUI.IINUIHostedViewSiriProviding.DisplaysMessage P:IntentsUI.IINUIHostedViewSiriProviding.DisplaysPaymentTransaction diff --git a/tests/cecil-tests/SetHandleTest.KnownFailures.cs b/tests/cecil-tests/SetHandleTest.KnownFailures.cs index d030c159b86a..f34743ac4f2f 100644 --- a/tests/cecil-tests/SetHandleTest.KnownFailures.cs +++ b/tests/cecil-tests/SetHandleTest.KnownFailures.cs @@ -35,7 +35,6 @@ public partial class SetHandleTest { "GameKit.GKScore::.ctor(System.String)", "GameplayKit.GKPath::.ctor(System.Numerics.Vector2[],System.Single,System.Boolean)", "GameplayKit.GKPath::.ctor(System.Numerics.Vector3[],System.Single,System.Boolean)", - "Intents.INPriceRange::.ctor(Intents.INPriceRangeOption,Foundation.NSDecimalNumber,System.String)", "ModelIO.MDLNoiseTexture::.ctor(System.Single,System.String,CoreGraphics.NVector2i,ModelIO.MDLTextureChannelEncoding,ModelIO.MDLNoiseTextureType)", "MultipeerConnectivity.MCSession::.ctor(MultipeerConnectivity.MCPeerID,Security.SecIdentity,MultipeerConnectivity.MCEncryptionPreference)", "MultipeerConnectivity.MCSession::.ctor(MultipeerConnectivity.MCPeerID,Security.SecIdentity,Security.SecCertificate[],MultipeerConnectivity.MCEncryptionPreference)", diff --git a/tests/common/MonoTouch.Dialog/Elements.cs b/tests/common/MonoTouch.Dialog/Elements.cs index 6bd56b5b7897..e6dad909b5f3 100644 --- a/tests/common/MonoTouch.Dialog/Elements.cs +++ b/tests/common/MonoTouch.Dialog/Elements.cs @@ -765,7 +765,7 @@ public override bool Matches (string text) /// options and can render images or background images either from UIImage parameters /// or by downloading them from the net. /// - public partial class StyledStringElement : StringElement, IImageUpdated, IColorizeBackground { + public partial class StyledStringElement : StringElement, IColorizeBackground { static NSString [] skey = { new NSString (".1"), new NSString (".2"), new NSString (".3"), new NSString (".4") }; public StyledStringElement (string caption) : base (caption) { } @@ -793,9 +793,7 @@ public StyledStringElement (string caption, string value, UITableViewCellStyle s ExtraInfo extraInfo; class ExtraInfo { - public UIImage Image; // Maybe add BackgroundImage? public UIColor BackgroundColor, DetailColor; - public Uri Uri, BackgroundUri; } ExtraInfo OnImageInfo () @@ -805,36 +803,12 @@ ExtraInfo OnImageInfo () return extraInfo; } - // Uses the specified image (use this or ImageUri) - public UIImage Image { - get { - return extraInfo is null ? null : extraInfo.Image; - } - set { - OnImageInfo ().Image = value; - extraInfo.Uri = null; - } - } - - // Loads the image from the specified uri (use this or Image) - public Uri ImageUri { - get { - return extraInfo is null ? null : extraInfo.Uri; - } - set { - OnImageInfo ().Uri = value; - extraInfo.Image = null; - } - } - - // Background color for the cell (alternative: BackgroundUri) public UIColor BackgroundColor { get { return extraInfo is null ? null : extraInfo.BackgroundColor; } set { OnImageInfo ().BackgroundColor = value; - extraInfo.BackgroundUri = null; } } @@ -847,17 +821,6 @@ public UIColor DetailColor { } } - // Uri for a Background image (alternatiev: BackgroundColor) - public Uri BackgroundUri { - get { - return extraInfo is null ? null : extraInfo.BackgroundUri; - } - set { - OnImageInfo ().BackgroundUri = value; - extraInfo.BackgroundColor = null; - } - } - protected virtual string GetKey (int style) { return skey [style]; @@ -893,19 +856,6 @@ protected void PrepareCell (UITableViewCell cell) if (extraInfo is null) { ClearBackground (cell); } else { - var imgView = cell.ImageView; - UIImage img; - - if (imgView is not null) { - if (extraInfo.Uri is not null) - img = ImageLoader.DefaultRequestImage (extraInfo.Uri, this); - else if (extraInfo.Image is not null) - img = extraInfo.Image; - else - img = null; - imgView.Image = img; - } - if (cell.DetailTextLabel is not null) cell.DetailTextLabel.TextColor = extraInfo.DetailColor ?? UIColor.Gray; } @@ -934,24 +884,10 @@ void IColorizeBackground.WillDisplay (UITableView tableView, UITableViewCell cel if (extraInfo.BackgroundColor is not null) { cell.TextLabel.BackgroundColor = UIColor.Clear; cell.BackgroundColor = extraInfo.BackgroundColor; - } else if (extraInfo.BackgroundUri is not null) { - var img = ImageLoader.DefaultRequestImage (extraInfo.BackgroundUri, this); - cell.TextLabel.BackgroundColor = UIColor.Clear; - cell.BackgroundColor = img is null ? UIColor.White : UIColor.FromPatternImage (img); } else ClearBackground (cell); } - void IImageUpdated.UpdatedImage (Uri uri) - { - if (uri is null || extraInfo is null) - return; - var root = GetImmediateRootElement (); - if (root is null || root.TableView is null) - return; - root.TableView.ReloadRows (new NSIndexPath [] { IndexPath }, UITableViewRowAnimation.None); - } - internal void AccessoryTap () { NSAction tapped = AccessoryTapped; @@ -966,8 +902,7 @@ internal static class Helper { static public CGSize StringSize (this string self, UIFont font) { using (var str = (NSString) self) { - return str.GetSizeUsingAttributes (new UIStringAttributes () - { + return str.GetSizeUsingAttributes (new UIStringAttributes () { Font = font, }); } @@ -982,11 +917,9 @@ static public CGSize StringSize (this string self, UIFont font, CGSize constrain static public CGSize StringSize (this NSString self, UIFont font, CGSize constrainedToSize, UILineBreakMode lineBreakMode) { - return self.GetBoundingRect (constrainedToSize, NSStringDrawingOptions.UsesLineFragmentOrigin, new UIStringAttributes () - { + return self.GetBoundingRect (constrainedToSize, NSStringDrawingOptions.UsesLineFragmentOrigin, new UIStringAttributes () { Font = font, - ParagraphStyle = new NSMutableParagraphStyle () - { + ParagraphStyle = new NSMutableParagraphStyle () { LineBreakMode = lineBreakMode, }, }, null).Size; @@ -1000,8 +933,7 @@ static public CGSize StringSize (this NSString self, UIFont font, float forWidth static public void DrawString (this string self, CGRect rect, UIFont font) { using (var str = (NSString) self) { - NSStringDrawing.DrawString (str, rect, new UIStringAttributes () - { + NSStringDrawing.DrawString (str, rect, new UIStringAttributes () { Font = font, }); } @@ -1010,11 +942,9 @@ static public void DrawString (this string self, CGRect rect, UIFont font) static public void DrawString (this string self, CGPoint point, float width, UIFont font, UILineBreakMode lineBreakMode) { using (var str = (NSString) self) { - NSStringDrawing.DrawString (str, point, new UIStringAttributes () - { + NSStringDrawing.DrawString (str, point, new UIStringAttributes () { Font = font, - ParagraphStyle = new NSMutableParagraphStyle () - { + ParagraphStyle = new NSMutableParagraphStyle () { LineBreakMode = lineBreakMode, }, }); @@ -1024,11 +954,9 @@ static public void DrawString (this string self, CGPoint point, float width, UIF static public void DrawString (this string self, CGRect rect, UIFont font, UILineBreakMode lineBreakMode, UITextAlignment alignment) { using (var str = (NSString) self) { - NSStringDrawing.DrawString (str, rect, new UIStringAttributes () - { + NSStringDrawing.DrawString (str, rect, new UIStringAttributes () { Font = font, - ParagraphStyle = new NSMutableParagraphStyle () - { + ParagraphStyle = new NSMutableParagraphStyle () { LineBreakMode = lineBreakMode, Alignment = alignment, }, @@ -1079,57 +1007,6 @@ public virtual nfloat GetHeight (UITableView tableView, NSIndexPath indexPath) } } - public partial class ImageStringElement : StringElement { - static NSString skey = new NSString ("ImageStringElement"); - UIImage image; - public UITableViewCellAccessory Accessory { get; set; } - - public ImageStringElement (string caption, UIImage image) : base (caption) - { - this.image = image; - this.Accessory = UITableViewCellAccessory.None; - } - - public ImageStringElement (string caption, string value, UIImage image) : base (caption, value) - { - this.image = image; - this.Accessory = UITableViewCellAccessory.None; - } - - public ImageStringElement (string caption, NSAction tapped, UIImage image) : base (caption, tapped) - { - this.image = image; - this.Accessory = UITableViewCellAccessory.None; - } - - protected override NSString CellKey { - get { - return skey; - } - } - public override UITableViewCell GetCell (UITableView tv) - { - var cell = tv.DequeueReusableCell (CellKey); - if (cell is null) { - cell = new UITableViewCell (Value is null ? UITableViewCellStyle.Default : UITableViewCellStyle.Subtitle, CellKey); - cell.SelectionStyle = UITableViewCellSelectionStyle.Blue; - } - - cell.Accessory = Accessory; - cell.TextLabel.Text = Caption; - cell.TextLabel.TextAlignment = Alignment; - - cell.ImageView.Image = image; - - // The check is needed because the cell might have been recycled. - if (cell.DetailTextLabel is not null) - cell.DetailTextLabel.Text = Value is null ? "" : Value; - - return cell; - } - - } - /// /// This interface is implemented by Element classes that will have /// different heights @@ -1268,194 +1145,6 @@ public override void Selected (DialogViewController dvc, UITableView tableView, } - public partial class ImageElement : Element { - public UIImage Value; - static CGRect rect = new CGRect (0, 0, dimx, dimy); - static NSString ikey = new NSString ("ImageElement"); - UIImage scaled; - - // There's no UIImagePickerController in tvOS (and I couldn't find any suitable replacement either). -#if !__TVOS__ - UIPopoverController popover; - - // Apple leaks this one, so share across all. - static UIImagePickerController picker; -#endif // !__TVOS__ - - // Height for rows - const int dimx = 48; - const int dimy = 43; - - // radius for rounding - const int rad = 10; - - static UIImage MakeEmpty () - { - using (var cs = CGColorSpace.CreateDeviceRGB ()) { - using (var bit = new CGBitmapContext (IntPtr.Zero, dimx, dimy, 8, 0, cs, CGImageAlphaInfo.PremultipliedFirst)) { - bit.SetStrokeColor (1, 0, 0, 0.5f); - bit.FillRect (new CGRect (0, 0, dimx, dimy)); - - return UIImage.FromImage (bit.ToImage ()); - } - } - } - - UIImage Scale (UIImage source) - { - UIGraphics.BeginImageContext (new CGSize (dimx, dimy)); - var ctx = UIGraphics.GetCurrentContext (); - - var img = source.CGImage; - ctx.TranslateCTM (0, dimy); - if (img.Width > img.Height) - ctx.ScaleCTM (1, (nfloat) (-img.Width / dimy)); - else - ctx.ScaleCTM ((nfloat) img.Height / dimx, -1); - - ctx.DrawImage (rect, source.CGImage); - - var ret = UIGraphics.GetImageFromCurrentImageContext (); - UIGraphics.EndImageContext (); - return ret; - } - - public ImageElement (UIImage image) : base ("") - { - if (image is null) { - Value = MakeEmpty (); - scaled = Value; - } else { - Value = image; - scaled = Scale (Value); - } - } - - protected override NSString CellKey { - get { - return ikey; - } - } - - public override UITableViewCell GetCell (UITableView tv) - { - var cell = tv.DequeueReusableCell (CellKey); - if (cell is null) { - cell = new UITableViewCell (UITableViewCellStyle.Default, CellKey); - } - - if (scaled is null) - return cell; - - Section psection = Parent as Section; - bool roundTop = psection.Elements [0] == this; - bool roundBottom = psection.Elements [psection.Elements.Count - 1] == this; - - using (var cs = CGColorSpace.CreateDeviceRGB ()) { - using (var bit = new CGBitmapContext (IntPtr.Zero, dimx, dimy, 8, 0, cs, CGImageAlphaInfo.PremultipliedFirst)) { - // Clipping path for the image, different on top, middle and bottom. - if (roundBottom) { - bit.AddArc (rad, rad, rad, (float) Math.PI, (float) (3 * Math.PI / 2), false); - } else { - bit.MoveTo (0, rad); - bit.AddLineToPoint (0, 0); - } - bit.AddLineToPoint (dimx, 0); - bit.AddLineToPoint (dimx, dimy); - - if (roundTop) { - bit.AddArc (rad, dimy - rad, rad, (float) (Math.PI / 2), (float) Math.PI, false); - bit.AddLineToPoint (0, rad); - } else { - bit.AddLineToPoint (0, dimy); - } - bit.Clip (); - bit.DrawImage (rect, scaled.CGImage); - - cell.ImageView.Image = UIImage.FromImage (bit.ToImage ()); - } - } - return cell; - } - - protected override void Dispose (bool disposing) - { - if (disposing) { - if (scaled is not null) { - scaled.Dispose (); - Value.Dispose (); - scaled = null; - Value = null; - } - } - base.Dispose (disposing); - } - -#if !__TVOS__ - class MyDelegate : UIImagePickerControllerDelegate { - ImageElement container; - UITableView table; - NSIndexPath path; - - public MyDelegate (ImageElement container, UITableView table, NSIndexPath path) - { - this.container = container; - this.table = table; - this.path = path; - } - -#if !NET - public override void FinishedPickingImage (UIImagePickerController picker, UIImage image, NSDictionary editingInfo) - { - container.Picked (image); - table.ReloadRows (new NSIndexPath [] { path }, UITableViewRowAnimation.None); - } -#else - public override void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) - { - var image = (UIImage) (info [UIImagePickerController.OriginalImage] ?? info [UIImagePickerController.EditedImage]); - container.Picked (image); - table.ReloadRows (new NSIndexPath [] { path }, UITableViewRowAnimation.None); - } -#endif - } - - void Picked (UIImage image) - { - Value = image; - scaled = Scale (image); - currentController.DismissModalViewController (true); - } - - UIViewController currentController; - public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path) - { - if (picker is null) - picker = new UIImagePickerController (); - picker.Delegate = new MyDelegate (this, tableView, path); - - switch (UIDevice.CurrentDevice.UserInterfaceIdiom) { - case UIUserInterfaceIdiom.Pad: - CGRect useRect; - popover = new UIPopoverController (picker); - var cell = tableView.CellAt (path); - if (cell is null) - useRect = rect; - else - useRect = cell.Frame; - popover.PresentFromRect (useRect, dvc.View, UIPopoverArrowDirection.Any, true); - break; - - default: - case UIUserInterfaceIdiom.Phone: - dvc.ActivateController (picker); - break; - } - currentController = dvc; - } -#endif // !__TVOS__ - } - /// /// An element that can be used to enter text. /// diff --git a/tests/common/MonoTouch.Dialog/Elements/ElementBadge.cs b/tests/common/MonoTouch.Dialog/Elements/ElementBadge.cs deleted file mode 100644 index acf1a26976b4..000000000000 --- a/tests/common/MonoTouch.Dialog/Elements/ElementBadge.cs +++ /dev/null @@ -1,156 +0,0 @@ -// -// ElementBadge.cs: defines the Badge Element. -// -// Author: -// Miguel de Icaza (miguel@gnome.org) -// -// Copyright 2010, Novell, Inc. -// -// Code licensed under the MIT X11 license -// -using System; -using System.Collections; -using System.Collections.Generic; -using System.Drawing; - -using UIKit; -using CoreGraphics; -using Foundation; -using ObjCRuntime; - -using NSAction = global::System.Action; - -namespace MonoTouch.Dialog { - /// - /// This element can be used to show an image with some text - /// - /// - /// The font can be configured after the element has been created - /// by assignign to the Font property; If you want to render - /// multiple lines of text, set the MultiLine property to true. - /// - /// If no font is specified, it will default to Helvetica 17. - /// - /// A static method MakeCalendarBadge is provided that can - /// render a calendar badge like the iPhone OS. It will compose - /// the text on top of the image which is expected to be 57x57 - /// - public partial class BadgeElement : Element, IElementSizing { - static NSString ckey = new NSString ("badgeKey"); - public event NSAction Tapped; - public UILineBreakMode LineBreakMode = UILineBreakMode.TailTruncation; - public UIViewContentMode ContentMode = UIViewContentMode.Left; - public int Lines = 1; - public UITableViewCellAccessory Accessory = UITableViewCellAccessory.None; - UIImage image; - UIFont font; - - public BadgeElement (UIImage badgeImage, string cellText) - : this (badgeImage, cellText, null) - { - } - - public BadgeElement (UIImage badgeImage, string cellText, NSAction tapped) : base (cellText) - { - if (badgeImage is null) - throw new ArgumentNullException ("badgeImage"); - - image = badgeImage; - if (tapped is not null) - Tapped += tapped; - } - - public UIFont Font { - get { - if (font is null) - font = UIFont.FromName ("Helvetica", 17f); - return font; - } - set { - if (font is not null) - font.Dispose (); - font = value; - } - } - - public override UITableViewCell GetCell (UITableView tv) - { - var cell = tv.DequeueReusableCell (ckey); - if (cell is null) { - cell = new UITableViewCell (UITableViewCellStyle.Default, ckey) { - SelectionStyle = UITableViewCellSelectionStyle.Blue - }; - } - cell.Accessory = Accessory; - var tl = cell.TextLabel; - tl.Text = Caption; - tl.Font = Font; - tl.LineBreakMode = LineBreakMode; - tl.Lines = Lines; - tl.ContentMode = ContentMode; - - cell.ImageView.Image = image; - - return cell; - } - - protected override void Dispose (bool disposing) - { - base.Dispose (disposing); - } - - public nfloat GetHeight (UITableView tableView, NSIndexPath indexPath) - { - CGSize size = new CGSize (tableView.Bounds.Width - 40, nfloat.MaxValue); - nfloat height = Caption.StringSize (Font, size, LineBreakMode).Height + 10; - - // Image is 57 pixels tall, add some padding - return (nfloat) Math.Max (height, 63); - } - - public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path) - { - if (Tapped is not null) - Tapped (); - tableView.DeselectRow (path, true); - } - - public static UIImage MakeCalendarBadge (UIImage template, string smallText, string bigText) - { - using (var cs = CGColorSpace.CreateDeviceRGB ()) { - using (var context = new CGBitmapContext (IntPtr.Zero, 57, 57, 8, 57 * 4, cs, CGImageAlphaInfo.PremultipliedLast)) { - //context.ScaleCTM (0.5f, -1); - context.TranslateCTM (0, 0); - context.DrawImage (new CGRect (0, 0, 57, 57), template.CGImage); - context.SetFillColor (1, 1, 1, 1); - - context.SelectFont ("Helvetica", 10f, CGTextEncoding.MacRoman); - - // Pretty lame way of measuring strings, as documented: - var start = context.TextPosition.X; - context.SetTextDrawingMode (CGTextDrawingMode.Invisible); - context.ShowText (smallText); - var width = context.TextPosition.X - start; - - context.SetTextDrawingMode (CGTextDrawingMode.Fill); - context.ShowTextAtPoint ((57 - width) / 2, 46, smallText); - - // The big string - context.SelectFont ("Helvetica-Bold", 32, CGTextEncoding.MacRoman); - start = context.TextPosition.X; - context.SetTextDrawingMode (CGTextDrawingMode.Invisible); - context.ShowText (bigText); - width = context.TextPosition.X - start; - - context.SetFillColor (0, 0, 0, 1); - context.SetTextDrawingMode (CGTextDrawingMode.Fill); - context.ShowTextAtPoint ((57 - width) / 2, 9, bigText); - - context.StrokePath (); - - return UIImage.FromImage (context.ToImage ()); - } - } - } - } -} diff --git a/tests/common/MonoTouch.Dialog/Utilities/ImageLoader.cs b/tests/common/MonoTouch.Dialog/Utilities/ImageLoader.cs deleted file mode 100644 index 55c4a2511ea1..000000000000 --- a/tests/common/MonoTouch.Dialog/Utilities/ImageLoader.cs +++ /dev/null @@ -1,352 +0,0 @@ -// Copyright 2010-2011 Miguel de Icaza -// -// Based on the TweetStation specific ImageStore -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading; -using System.Security.Cryptography; - -using Foundation; -using UIKit; -using CoreGraphics; - -using MonoTouch.Dialog.Utilities; - -namespace MonoTouch.Dialog.Utilities { - /// - /// This interface needs to be implemented to be notified when an image - /// has been downloaded. The notification will happen on the UI thread. - /// Upon notification, the code should call RequestImage again, this time - /// the image will be loaded from the on-disk cache or the in-memory cache. - /// - public interface IImageUpdated { - void UpdatedImage (Uri uri); - } - - /// - /// Network image loader, with local file system cache and in-memory cache - /// - /// - /// By default, using the static public methods will use an in-memory cache - /// for 50 images and 4 megs total. The behavior of the static methods - /// can be modified by setting the public DefaultLoader property to a value - /// that the user configured. - /// - /// The instance methods can be used to create different imageloader with - /// different properties. - /// - /// Keep in mind that the phone does not have a lot of memory, and using - /// the cache with the unlimited value (0) even with a number of items in - /// the cache can consume memory very quickly. - /// - /// Use the Purge method to release all the memory kept in the caches on - /// low memory conditions, or when the application is sent to the background. - /// - - public class ImageLoader { - public readonly static string BaseDir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".."); - const int MaxRequests = 6; - static string PicDir; - - // Cache of recently used images - LRUCache cache; - - // A list of requests that have been issues, with a list of objects to notify. - static Dictionary> pendingRequests; - - // A list of updates that have completed, we must notify the main thread about them. - static HashSet queuedUpdates; - - // A queue used to avoid flooding the network stack with HTTP requests - static Stack requestQueue; - - static NSString nsDispatcher = new NSString ("x"); - - static MD5 checksum = MD5.Create (); - - /// - /// This contains the default loader which is configured to be 50 images - /// up to 4 megs of memory. Assigning to this property a new value will - /// change the behavior. This property is lazyly computed, the first time - /// an image is requested. - /// - public static ImageLoader DefaultLoader; - - static ImageLoader () - { - PicDir = Path.Combine (BaseDir, "Library/Caches/Pictures.MonoTouch.Dialog/"); - - if (!Directory.Exists (PicDir)) - Directory.CreateDirectory (PicDir); - - pendingRequests = new Dictionary> (); - queuedUpdates = new HashSet (); - requestQueue = new Stack (); - } - - /// - /// Creates a new instance of the image loader - /// - /// - /// The maximum number of entries in the LRU cache - /// - /// - /// The maximum number of bytes to consume by the image loader cache. - /// - public ImageLoader (int cacheSize, int memoryLimit) - { - cache = new LRUCache (cacheSize, memoryLimit, sizer); - } - - static int sizer (UIImage img) - { - var cg = img.CGImage; - return (int) (cg.BytesPerRow * cg.Height); - } - - /// - /// Purges the contents of the DefaultLoader - /// - public static void Purge () - { - if (DefaultLoader is not null) - DefaultLoader.PurgeCache (); - } - - /// - /// Purges the cache of this instance of the ImageLoader, releasing - /// all the memory used by the images in the caches. - /// - public void PurgeCache () - { - lock (cache) - cache.Purge (); - } - - static int hex (int v) - { - if (v < 10) - return '0' + v; - return 'a' + v - 10; - } - - static string md5 (string input) - { - var bytes = checksum.ComputeHash (Encoding.UTF8.GetBytes (input)); - var ret = new char [32]; - for (int i = 0; i < 16; i++) { - ret [i * 2] = (char) hex (bytes [i] >> 4); - ret [i * 2 + 1] = (char) hex (bytes [i] & 0xf); - } - return new string (ret); - } - - /// - /// Requests an image to be loaded using the default image loader - /// - /// - /// The URI for the image to load - /// - /// - /// A class implementing the IImageUpdated interface that will be invoked when the image has been loaded - /// - /// - /// If the image has already been downloaded, or is in the cache, this will return the image as a UIImage. - /// - public static UIImage DefaultRequestImage (Uri uri, IImageUpdated notify) - { - if (DefaultLoader is null) - DefaultLoader = new ImageLoader (50, 4 * 1024 * 1024); - return DefaultLoader.RequestImage (uri, notify); - } - - /// - /// Requests an image to be loaded from the network - /// - /// - /// The URI for the image to load - /// - /// - /// A class implementing the IImageUpdated interface that will be invoked when the image has been loaded - /// - /// - /// If the image has already been downloaded, or is in the cache, this will return the image as a UIImage. - /// - public UIImage RequestImage (Uri uri, IImageUpdated notify) - { - UIImage ret; - - lock (cache) { - ret = cache [uri]; - if (ret is not null) - return ret; - } - - lock (requestQueue) { - if (pendingRequests.ContainsKey (uri)) { - if (!pendingRequests [uri].Contains (notify)) - pendingRequests [uri].Add (notify); - return null; - } - } - - string picfile = uri.IsFile ? uri.LocalPath : PicDir + md5 (uri.AbsoluteUri); - if (File.Exists (picfile)) { - ret = UIImage.FromFile (picfile); - if (ret is not null) { - lock (cache) - cache [uri] = ret; - return ret; - } - } - if (uri.IsFile) - return null; - QueueRequest (uri, notify); - return null; - } - - static void QueueRequest (Uri uri, IImageUpdated notify) - { - if (notify is null) - throw new ArgumentNullException ("notify"); - - lock (requestQueue) { - if (pendingRequests.ContainsKey (uri)) { - //Util.Log ("pendingRequest: added new listener for {0}", id); - pendingRequests [uri].Add (notify); - return; - } - var slot = new List (4); - slot.Add (notify); - pendingRequests [uri] = slot; - - if (picDownloaders >= MaxRequests) - requestQueue.Push (uri); - else { - ThreadPool.QueueUserWorkItem (delegate - { - try { - StartPicDownload (uri); - } catch (Exception e) { - Console.WriteLine (e); - } - }); - } - } - } - - static bool Download (Uri uri) - { - try { - NSUrlResponse response; - NSError error; - - var target = PicDir + md5 (uri.AbsoluteUri); - var req = new NSUrlRequest (new NSUrl (uri.AbsoluteUri.ToString ()), NSUrlRequestCachePolicy.UseProtocolCachePolicy, 120); - var data = NSUrlConnection.SendSynchronousRequest (req, out response, out error); - return data.Save (target, true, out error); - } catch (Exception e) { - Console.WriteLine ("Problem with {0} {1}", uri, e); - return false; - } - } - - static long picDownloaders; - - static void StartPicDownload (Uri uri) - { - Interlocked.Increment (ref picDownloaders); - try { - _StartPicDownload (uri); - } catch (Exception e) { - Console.Error.WriteLine ("CRITICAL: should have never happened {0}", e); - } - //Util.Log ("Leaving StartPicDownload {0}", picDownloaders); - Interlocked.Decrement (ref picDownloaders); - } - - static void _StartPicDownload (Uri uri) - { - do { - bool downloaded = false; - - //System.Threading.Thread.Sleep (5000); - downloaded = Download (uri); - //if (!downloaded) - // Console.WriteLine ("Error fetching picture for {0} to {1}", uri, target); - - // Cluster all updates together - bool doInvoke = false; - - lock (requestQueue) { - if (downloaded) { - queuedUpdates.Add (uri); - - // If this is the first queued update, must notify - if (queuedUpdates.Count == 1) - doInvoke = true; - } else - pendingRequests.Remove (uri); - - // Try to get more jobs. - if (requestQueue.Count > 0) { - uri = requestQueue.Pop (); - if (uri is null) { - Console.Error.WriteLine ("Dropping request {0} because url is null", uri); - pendingRequests.Remove (uri); - uri = null; - } - } else { - //Util.Log ("Leaving because requestQueue.Count = {0} NOTE: {1}", requestQueue.Count, pendingRequests.Count); - uri = null; - } - } - if (doInvoke) - nsDispatcher.BeginInvokeOnMainThread (NotifyImageListeners); - - } while (uri is not null); - } - - // Runs on the main thread - static void NotifyImageListeners () - { - lock (requestQueue) { - foreach (var quri in queuedUpdates) { - var list = pendingRequests [quri]; - pendingRequests.Remove (quri); - foreach (var pr in list) { - try { - pr.UpdatedImage (quri); - } catch (Exception e) { - Console.WriteLine (e); - } - } - } - queuedUpdates.Clear (); - } - } - } -} diff --git a/tests/dotnet/UnitTests/BundleStructureTest.cs b/tests/dotnet/UnitTests/BundleStructureTest.cs index 77ab696b2301..30409b760d20 100644 --- a/tests/dotnet/UnitTests/BundleStructureTest.cs +++ b/tests/dotnet/UnitTests/BundleStructureTest.cs @@ -644,19 +644,6 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat expectedWarnings.AddRange (expectedWarnings); } - var xcArch = GetXCFrameworkArchitectures (platform, runtimeIdentifiers); - foreach (var rid in rids) { - var zip = Path.Combine (testsDirectory, "bindings-xcframework-test", "dotnet", platformString, "bin", configuration, tfm, "bindings-framework-test.resources.zip"); - var zippedFrameworks = File.Exists (zip); - if (zippedFrameworks) { - expectedWarnings.Add ($"The framework {Path.Combine ("obj", configuration, tfm, rid, "bindings-framework-test.resources.zip", "XStaticObjectTest.xcframework", xcArch, "XStaticObjectTest.framework")} is a framework of static libraries, and will not be copied to the app."); - expectedWarnings.Add ($"The framework {Path.Combine ("obj", configuration, tfm, rid, "bindings-framework-test.resources.zip", "XStaticArTest.xcframework", xcArch, "XStaticArTest.framework")} is a framework of static libraries, and will not be copied to the app."); - } else { - expectedWarnings.Add ($"The framework {Path.Combine (testsDirectory, "bindings-xcframework-test", "dotnet", platformString, "bin", configuration, tfm, "bindings-framework-test.resources", "XStaticObjectTest.xcframework", xcArch, "XStaticObjectTest.framework")} is a framework of static libraries, and will not be copied to the app."); - expectedWarnings.Add ($"The framework {Path.Combine (testsDirectory, "bindings-xcframework-test", "dotnet", platformString, "bin", configuration, tfm, "bindings-framework-test.resources", "XStaticArTest.xcframework", xcArch, "XStaticArTest.framework")} is a framework of static libraries, and will not be copied to the app."); - } - } - if (signature == CodeSignature.None && (platform == ApplePlatform.MacCatalyst || platform == ApplePlatform.MacOSX)) { expectedWarnings.Add ($"Found files in the root directory of the app bundle. This will likely cause codesign to fail. Files:\n{Path.Combine ("bin", configuration, tfm, runtimeIdentifiers.IndexOf (';') >= 0 ? string.Empty : runtimeIdentifiers, "BundleStructure.app", "UnknownJ.bin")}"); } diff --git a/tests/dotnet/UnitTests/ProjectTest.cs b/tests/dotnet/UnitTests/ProjectTest.cs index d1696f8d48dd..47dcaa1ff7e6 100644 --- a/tests/dotnet/UnitTests/ProjectTest.cs +++ b/tests/dotnet/UnitTests/ProjectTest.cs @@ -253,7 +253,11 @@ public void BuildBundledResources (string platform, string prefix, bool? bundleO var project_path = Path.Combine (project_dir, $"{assemblyName}.csproj"); Clean (project_path); - var result = DotNet.AssertBuild (project_path, verbosity); + + var properties = GetDefaultProperties (); + if (bundleOriginalResources.HasValue) + properties ["BundleOriginalResources"] = bundleOriginalResources.Value ? "true" : "false"; + var result = DotNet.AssertBuild (project_path, properties); var lines = BinLog.PrintToLines (result.BinLogPath); // Find the resulting binding assembly from the build log var assemblies = FilterToAssembly (lines, assemblyName); @@ -263,14 +267,17 @@ public void BuildBundledResources (string platform, string prefix, bool? bundleO var asm = assemblies.First (); Assert.That (asm, Does.Exist, "Assembly existence"); - // Verify that there's one resource in the binding assembly, and its name + // Verify the resource count in the binding assembly, and their names var ad = AssemblyDefinition.ReadAssembly (asm, new ReaderParameters { ReadingMode = ReadingMode.Deferred }); - Assert.That (ad.MainModule.Resources.Count, Is.EqualTo (3), "3 resources"); - // Sort the resources before we assert, since we don't care about the order, and sorted order makes the asserts simpler. - var resources = ad.MainModule.Resources.OrderBy (v => v.Name).ToArray (); - Assert.That (resources [0].Name, Is.EqualTo ($"__{prefix}_content_basn3p08__with__loc.png"), $"__{prefix}_content_basn3p08__with__loc.png"); - Assert.That (resources [1].Name, Is.EqualTo ($"__{prefix}_content_basn3p08.png"), $"__{prefix}_content_basn3p08.png"); - Assert.That (resources [2].Name, Is.EqualTo ($"__{prefix}_content_xamvideotest.mp4"), $"__{prefix}_content_xamvideotest.mp4"); + var resources = ad.MainModule.Resources.Select (v => v.Name).ToArray (); + var expectedResources = new string [] { + "basn3p08.png", + "basn3p08__with__loc.png", + "xamvideotest.mp4", + }; + var oldPrefixed = expectedResources.Select (v => $"__{prefix}_content_{v}").ToArray (); + var newPrefixed = expectedResources.Select (v => $"__{prefix}_item_BundleResource_{v}").ToArray (); + Assert.That (resources, Is.EquivalentTo (oldPrefixed).Or.EquivalentTo (newPrefixed), "Resources"); } [TestCase ("iOS")] diff --git a/tests/dotnet/UnitTests/WindowsTest.cs b/tests/dotnet/UnitTests/WindowsTest.cs index 940718382167..69865ce8357d 100644 --- a/tests/dotnet/UnitTests/WindowsTest.cs +++ b/tests/dotnet/UnitTests/WindowsTest.cs @@ -207,17 +207,6 @@ public void BundleStructureWithRemoteMac (ApplePlatform platform, string runtime expectedWarnings.AddRange (expectedWarnings); } - var zippedFrameworks = platform == ApplePlatform.MacCatalyst || platform == ApplePlatform.MacOSX; - foreach (var rid in rids) { - if (zippedFrameworks) { - expectedWarnings.Add ($"The framework {Path.Combine ("obj", configuration, tfm, rid, "bindings-xcframework-test.resources.zip", "XStaticObjectTest.framework")} is a framework of static libraries, and will not be copied to the app."); - expectedWarnings.Add ($"The framework {Path.Combine ("obj", configuration, tfm, rid, "bindings-xcframework-test.resources.zip", "XStaticArTest.framework")} is a framework of static libraries, and will not be copied to the app."); - } else { - expectedWarnings.Add ($"The framework {Path.Combine (testsDirectory, "bindings-xcframework-test", "dotnet", platformString, "bin", configuration, tfm, "bindings-framework-test.resources", "XStaticObjectTest.xcframework", runtimeIdentifiers, "XStaticObjectTest.framework")} is a framework of static libraries, and will not be copied to the app."); - expectedWarnings.Add ($"The framework {Path.Combine (testsDirectory, "bindings-xcframework-test", "dotnet", platformString, "bin", configuration, tfm, "bindings-framework-test.resources", "XStaticArTest.xcframework", runtimeIdentifiers, "XStaticArTest.framework")} is a framework of static libraries, and will not be copied to the app."); - } - } - if (signature == BundleStructureTest.CodeSignature.None && (platform == ApplePlatform.MacCatalyst || platform == ApplePlatform.MacOSX)) { expectedWarnings.Add ($"Found files in the root directory of the app bundle. This will likely cause codesign to fail. Files:\n{Path.Combine ("bin", configuration, tfm, runtimeIdentifiers.IndexOf (';') >= 0 ? string.Empty : runtimeIdentifiers, "BundleStructure.app", "UnknownJ.bin")}"); } diff --git a/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs b/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs index b535403fc23d..8b334d97d1aa 100644 --- a/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs +++ b/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs @@ -21,20 +21,20 @@ using NUnit.Framework; namespace MonoTouchFixtures.DeviceDiscoveryExtension { - + [TestFixture] [Preserve (AllMembers = true)] public class DDDeviceTest { - + [Test] public void NetworkEndpointTest () { - TestRuntime.AssertXcodeVersion (14,0); + TestRuntime.AssertXcodeVersion (14, 0); var uuid = Guid.NewGuid (); var endpoint = NWEndpoint.Create ("www.microsoft.com", "https"); var device = new DDDevice ("MyDevice", DDDeviceCategory.LaptopComputer, UTType.CreateFromIdentifier ("com.adobe.pdf"), uuid.ToString ()); - + device.NetworkEndpoint = endpoint; var tmpEndpoint = device.NetworkEndpoint; diff --git a/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs b/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs index a6c7077f9d13..d1ba58890cc9 100644 --- a/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs +++ b/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs @@ -18,11 +18,11 @@ using Xamarin.Utils; namespace MonoTouchFixtures.DeviceDiscoveryUI { - + [TestFixture] [Preserve (AllMembers = true)] public class DDDevicePickerViewControllerTest { - + const string serviceName = "MyAppService"; [OneTimeSetUp] @@ -34,7 +34,7 @@ public void IsSupportedTest () var browserDescriptor = NWBrowserDescriptor.CreateApplicationServiceName (serviceName); var parameters = NWParameters.CreateApplicationService (); var isSupported = DDDevicePickerViewController.IsSupported (browserDescriptor, parameters); - + // DDDevicePickerViewController seems to work only for devices if (TestRuntime.IsSimulator) Assert.IsFalse (isSupported, "IsSupported"); @@ -51,7 +51,7 @@ public void InitWithBrowseDescriptorAndParametersTest () var browserDescriptor = NWBrowserDescriptor.CreateApplicationServiceName (serviceName); var parameters = NWParameters.CreateApplicationService (); var isSupported = DDDevicePickerViewController.IsSupported (browserDescriptor, parameters); - + // If this fails, please, double check that MyAppService is registered within the Info.plist // https://developer.apple.com/documentation/bundleresources/information_property_list/nsapplicationservices Assert.IsTrue (isSupported, $"The {serviceName} key might not be registered in the Info.plist."); @@ -69,11 +69,11 @@ public void SetDevicePickerTest () var browserDescriptor = NWBrowserDescriptor.CreateApplicationServiceName (serviceName); var parameters = NWParameters.CreateApplicationService (); var isSupported = DDDevicePickerViewController.IsSupported (browserDescriptor, parameters); - + // If this fails, please, double check that MyAppService is registered within the Info.plist // https://developer.apple.com/documentation/bundleresources/information_property_list/nsapplicationservices Assert.IsTrue (isSupported, $"The {serviceName} key might not be registered in the Info.plist."); - + Assert.DoesNotThrow (() => { var devicePicker = new DDDevicePickerViewController (browserDescriptor, parameters); devicePicker.SetDevicePicker ((endpoint, error) => { }); diff --git a/tests/monotouch-test/Foundation/CookieTest.cs b/tests/monotouch-test/Foundation/CookieTest.cs index 58b5cc95a7f4..32f1804d4a77 100644 --- a/tests/monotouch-test/Foundation/CookieTest.cs +++ b/tests/monotouch-test/Foundation/CookieTest.cs @@ -174,7 +174,9 @@ public void DotNetInterop_NonSession () c.CommentUri = new Uri ("http://comment.uri"); c.Discard = false; c.Expires = DateTime.Now.AddDays (1); +#pragma warning disable SM02360 // "Websites must specify the HttpOnly attribute on sensitive cookies" - this is a cookie test, we're not sending any requests, so it's safe to ignore c.HttpOnly = false; +#pragma warning restore SM02360 c.Port = "\"80\""; c.Secure = true; c.Version = 1; diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/FromDeclarationTests.cs similarity index 93% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/FromDeclarationTests.cs index d1812cf5fea4..36bec3269ec6 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/FromDeclarationTests.cs @@ -10,47 +10,15 @@ using Microsoft.Macios.Generator.Attributes; using Microsoft.Macios.Generator.Availability; using Microsoft.Macios.Generator.DataModel; -using ObjCRuntime; using Xamarin.Tests; using Xamarin.Utils; using Xunit; using static Microsoft.Macios.Generator.Tests.TestDataFactory; -namespace Microsoft.Macios.Generator.Tests.DataModel; +namespace Microsoft.Macios.Generator.Tests.DataModel.MethodTests; -public class MethodTests : BaseGeneratorTestClass { +public class FromDeclarationTests : BaseGeneratorTestClass { - [Fact] - public void IsThreadSafe () - { - var method = new Method ( - type: "NS.MyClass", - name: "MyMethod", - returnType: ReturnTypeForVoid (), - symbolAvailability: new (), - exportMethodData: new ("selector", ArgumentSemantic.None, ObjCBindings.Method.IsThreadSafe), - attributes: [], - modifiers: [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword), - ], - parameters: [] - ); - Assert.True (method.IsThreadSafe); - - method = new Method ( - type: "NS.MyClass", - name: "MyMethod", - returnType: ReturnTypeForVoid (), - symbolAvailability: new (), - exportMethodData: new ("selector", ArgumentSemantic.None, ObjCBindings.Method.Default), - attributes: [], - modifiers: [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword), - ], - parameters: [] - ); - Assert.False (method.IsThreadSafe); - } class TestDataFromMethodDeclaration : IEnumerable { public IEnumerator GetEnumerator () { diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/GeneralMethodTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/GeneralMethodTests.cs new file mode 100644 index 000000000000..11c778d093df --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/GeneralMethodTests.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#pragma warning disable APL0003 +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.Macios.Generator.DataModel; +using ObjCRuntime; +using Xunit; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; + +namespace Microsoft.Macios.Generator.Tests.DataModel.MethodTests; + +public class GeneralMethodTests { + + [Fact] + public void IsThreadSafe () + { + var method = new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + exportMethodData: new ("selector", ArgumentSemantic.None, ObjCBindings.Method.IsThreadSafe), + attributes: [], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [] + ); + Assert.True (method.IsThreadSafe); + + method = new Method ( + type: "NS.MyClass", + name: "MyMethod", + returnType: ReturnTypeForVoid (), + symbolAvailability: new (), + exportMethodData: new ("selector", ArgumentSemantic.None, ObjCBindings.Method.Default), + attributes: [], + modifiers: [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword), + ], + parameters: [] + ); + Assert.False (method.IsThreadSafe); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/MethodComparerTests.cs similarity index 99% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodComparerTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/MethodComparerTests.cs index d53701ada804..bcf99c4b9f1f 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/MethodComparerTests.cs @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + using System; using Microsoft.CodeAnalysis.CSharp; using Microsoft.Macios.Generator.DataModel; using Xunit; using static Microsoft.Macios.Generator.Tests.TestDataFactory; -namespace Microsoft.Macios.Generator.Tests.DataModel; +namespace Microsoft.Macios.Generator.Tests.DataModel.MethodTests; public class MethodComparerTests { readonly MethodComparer comparer = new (); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodEqualityComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/MethodEqualityComparerTests.cs similarity index 99% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodEqualityComparerTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/MethodEqualityComparerTests.cs index 2fa98c191ba7..656bb515ea25 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodEqualityComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/MethodEqualityComparerTests.cs @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + using System.Collections.Immutable; using Microsoft.Macios.Generator.DataModel; using Xunit; using static Microsoft.Macios.Generator.Tests.TestDataFactory; -namespace Microsoft.Macios.Generator.Tests.DataModel; +namespace Microsoft.Macios.Generator.Tests.DataModel.MethodTests; public class MethodEqualityComparerTests { readonly MethodsEqualityComparer equalityComparer = new (); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/NeedsTempReturnTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/NeedsTempReturnTests.cs new file mode 100644 index 000000000000..d3cbbe6eccef --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/MethodTests/NeedsTempReturnTests.cs @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#pragma warning disable APL0003 +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using Xunit; + +namespace Microsoft.Macios.Generator.Tests.DataModel.MethodTests; + +public class NeedsTempReturnTests : BaseGeneratorTestClass { + + class TestDataUseTempReturn : IEnumerable { + public IEnumerator GetEnumerator () + { + const string nsobjectMethod = @" +using System; +using ObjCBindings; +using Foundation; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual NSUrl GetAppStoreReceiptUrl (); +} +"; + yield return [ + nsobjectMethod, + true + ]; + + const string stringMethod = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual string GetBuiltinPluginsPath (); +"; + yield return [ + stringMethod, + false + ]; + + const string boolMethod = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual bool GetBuiltinPluginsPath () +"; + yield return [ + boolMethod, + true + ]; + + const string charMethod = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual char GetBuiltinPluginsPath (); +"; + yield return [ + charMethod, + true + ]; + + const string nfloatMethod = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual nfloat GetBuiltinPluginsPath (); +"; + yield return [ + nfloatMethod, + false + ]; + + const string stretType = @" +using System; +using ObjCBindings; +using CoreGraphics; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual NMatrix4 GetBuiltinPluginsPath (); +"; + yield return [ + stretType, + true + ]; + + const string nativeEnumType = @" +using System; +using AVFoundation; +using ObjCBindings; +using CoreGraphics; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual AVAudioApplicationMicrophoneInjectionPermission GetBuiltinPluginsPath (); +"; + yield return [ + nativeEnumType, + true + ]; + + const string delegateMethod = @" +using System; +using AVFoundation; +using ObjCBindings; +using CoreGraphics; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual Action GetBuiltinPluginsPath (); +"; + yield return [ + delegateMethod, + true + ]; + + const string marshalNativeExceptions = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"", Flags = Method.MarshalNativeExceptions)] + public virtual string GetBuiltinPluginsPath (); +"; + yield return [ + marshalNativeExceptions, + true + ]; + + const string factoryMethod = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"", Flags = Method.Factory)] + public virtual string GetBuiltinPluginsPath (); +"; + yield return [ + factoryMethod, + true + ]; + + const string byRefParameters = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual string GetBuiltinPluginsPath (out NSError error); +"; + yield return [ + byRefParameters, + true + ]; + } + + IEnumerator IEnumerable.GetEnumerator () + => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void FromMethodDeclaration (ApplePlatform platform, string inputText, bool expected) + { + var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); + Assert.Single (syntaxTrees); + var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); + var declaration = syntaxTrees [0].GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + Assert.True (Method.TryCreate (declaration, semanticModel, out var changes)); + Assert.NotNull (changes); + Assert.Equal (expected, changes.Value.UseTempReturn); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/FromDeclarationTests.cs similarity index 73% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/FromDeclarationTests.cs index ef4187730fc2..3890132df9bb 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/FromDeclarationTests.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + #pragma warning disable APL0003 using System.Collections; using System.Collections.Generic; @@ -13,424 +14,11 @@ using Xamarin.Tests; using Xamarin.Utils; using Xunit; -using Property = Microsoft.Macios.Generator.DataModel.Property; using static Microsoft.Macios.Generator.Tests.TestDataFactory; -namespace Microsoft.Macios.Generator.Tests.DataModel; - -public class PropertyTests : BaseGeneratorTestClass { - - [Theory] - [InlineData ("Name")] - [InlineData ("Surname")] - [InlineData ("Date")] - public void BackingFieldTests (string propertyName) - { - var property = new Property ( - name: propertyName, - returnType: ReturnTypeForString (), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - Assert.Equal ($"_{propertyName}", property.BackingField); - } - - [Fact] - public void IsThreadSafeProperty () - { - var property = new Property ( - name: "MyProperty", - returnType: ReturnTypeForString (), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ) { - ExportPropertyData = new ("myProperty", ArgumentSemantic.None, ObjCBindings.Property.IsThreadSafe) - }; - Assert.True (property.IsThreadSafe); - - property = new Property ( - name: "MyProperty", - returnType: ReturnTypeForString (), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ) { - ExportPropertyData = new ("myProperty", ArgumentSemantic.None, ObjCBindings.Property.Default) - }; - Assert.False (property.IsThreadSafe); - } - - [Fact] - public void CompareDiffName () - { - var x = new Property ( - name: "First", - returnType: ReturnTypeForString (), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - var y = new Property ( - name: "Second", - returnType: ReturnTypeForString (), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } - - [Fact] - public void CompareDiffType () - { - var x = new Property ( - name: "First", - returnType: ReturnTypeForString (), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - var y = new Property ( - name: "First", - returnType: ReturnTypeForInt (), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } - - [Fact] - public void CompareDiffIsReferenceType () - { - var x = new Property ( - name: "First", - returnType: new ( - name: "string", - isBlittable: false, - isSmartEnum: false, - isNullable: false, - isArray: false, - isReferenceType: false - ), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - var y = new Property ( - name: "First", - returnType: new ( - name: "string", - isBlittable: false, - isSmartEnum: false, - isNullable: false, - isArray: false, - isReferenceType: true - ), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - - Assert.False (condition: x.Equals (other: y)); - Assert.False (condition: y.Equals (other: x)); - Assert.False (condition: x == y); - Assert.True (condition: x != y); - } - - [Fact] - public void CompareDiffIsBlittableType () - { - var x = new Property ( - name: "First", - returnType: new ( - name: "string", - isBlittable: true, - isSmartEnum: false, - isNullable: false, - isArray: false, - isReferenceType: false - ), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - var y = new Property ( - name: "First", - returnType: new ( - name: "string", - isBlittable: false, - isSmartEnum: false, - isNullable: false, - isArray: false, - isReferenceType: false - ), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } - - [Fact] - public void CompareDiffIsSmartEnum () - { - var x = new Property ( - name: "First", - returnType: new ( - name: "string", - isBlittable: false, - isSmartEnum: true, - isNullable: false, - isArray: false, - isReferenceType: false - ), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - var y = new Property ( - name: "First", - returnType: new ( - name: "string", - isBlittable: false, - isSmartEnum: false, - isNullable: false, - isArray: false, - isReferenceType: false - ), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } - - [Fact] - public void CompareDiffAttrs () - { - var x = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [], []); - var y = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr2"), - ], [], []); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } +namespace Microsoft.Macios.Generator.Tests.DataModel.PropertyTests; - [Fact] - public void CompareDiffModifiers () - { - var x = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.AbstractKeyword) - ], []); - var y = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword) - ], []); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } - - [Fact] - public void CompareDiffAccessors () - { - var x = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword) - ], [ - new ( - accessorKind: AccessorKind.Getter, - symbolAvailability: new (), - exportPropertyData: null, - attributes: [], - modifiers: [] - ), - new ( - accessorKind: AccessorKind.Setter, - symbolAvailability: new (), - exportPropertyData: null, - attributes: [], - modifiers: [] - ), - ]); - var y = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword) - ], [ - new ( - accessorKind: AccessorKind.Getter, - symbolAvailability: new (), - exportPropertyData: null, - attributes: [], - modifiers: [] - ), - ]); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } - - [Fact] - public void CompareDiffAccessorsExportData () - { - var x = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword) - ], [ - new ( - accessorKind: AccessorKind.Getter, - symbolAvailability: new (), - exportPropertyData: new ("name"), - attributes: [], - modifiers: [] - ), - ]); - var y = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword) - ], [ - new ( - accessorKind: AccessorKind.Getter, - symbolAvailability: new (), - exportPropertyData: new ("surname"), - attributes: [], - modifiers: [] - ), - ]); - - Assert.False (x.Equals (y)); - Assert.False (y.Equals (x)); - Assert.False (x == y); - Assert.True (x != y); - } - - [Fact] - public void CompareEquals () - { - var x = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword) - ], [ - new ( - accessorKind: AccessorKind.Getter, - symbolAvailability: new (), - exportPropertyData: null, - attributes: [], - modifiers: [] - ), - new ( - accessorKind: AccessorKind.Setter, - symbolAvailability: new (), - exportPropertyData: null, - attributes: [], - modifiers: [] - ), - ]); - var y = new Property ("First", ReturnTypeForString (), new (), [ - new ("Attr1"), - new ("Attr2"), - ], [ - SyntaxFactory.Token (SyntaxKind.PublicKeyword) - ], [ - new ( - accessorKind: AccessorKind.Getter, - symbolAvailability: new (), - exportPropertyData: null, - attributes: [], - modifiers: [] - ), - new ( - accessorKind: AccessorKind.Setter, - symbolAvailability: new (), - exportPropertyData: null, - attributes: [], - modifiers: [] - ), - ]); - - Assert.True (x.Equals (y)); - Assert.True (y.Equals (x)); - Assert.True (x == y); - Assert.False (x != y); - } - - [Theory] - [InlineData (ObjCBindings.Property.Default, false)] - [InlineData (ObjCBindings.Property.Notification, true)] -#pragma warning disable xUnit1025 - [InlineData (ObjCBindings.Property.Notification | ObjCBindings.Property.Default, true)] -#pragma warning restore xUnit1025 - public void IsNotification (ObjCBindings.Property flag, bool expectedResult) - { - var property = new Property ( - name: "Test", - returnType: new TypeInfo ("string"), - symbolAvailability: new (), - attributes: [], - modifiers: [], - accessors: [] - ) { - ExportFieldData = new (new FieldData ("name", flag), ""), - }; - Assert.Equal (expectedResult, property.IsNotification); - } +public class FromDeclarationTests : BaseGeneratorTestClass { class TestDataFromPropertyDeclaration : IEnumerable { public IEnumerator GetEnumerator () diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/GeneralPropertyTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/GeneralPropertyTests.cs new file mode 100644 index 000000000000..e898c6948806 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/GeneralPropertyTests.cs @@ -0,0 +1,427 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +#pragma warning disable APL0003 +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.DataModel; +using ObjCRuntime; +using Xunit; +using Property = Microsoft.Macios.Generator.DataModel.Property; +using static Microsoft.Macios.Generator.Tests.TestDataFactory; + +namespace Microsoft.Macios.Generator.Tests.DataModel.PropertyTests; + +public class GeneralPropertyTests { + + [Theory] + [InlineData ("Name")] + [InlineData ("Surname")] + [InlineData ("Date")] + public void BackingFieldTests (string propertyName) + { + var property = new Property ( + name: propertyName, + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + Assert.Equal ($"_{propertyName}", property.BackingField); + } + + [Fact] + public void IsThreadSafeProperty () + { + var property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("myProperty", ArgumentSemantic.None, ObjCBindings.Property.IsThreadSafe) + }; + Assert.True (property.IsThreadSafe); + + property = new Property ( + name: "MyProperty", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportPropertyData = new ("myProperty", ArgumentSemantic.None, ObjCBindings.Property.Default) + }; + Assert.False (property.IsThreadSafe); + } + + [Fact] + public void CompareDiffName () + { + var x = new Property ( + name: "First", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + var y = new Property ( + name: "Second", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareDiffType () + { + var x = new Property ( + name: "First", + returnType: ReturnTypeForString (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + var y = new Property ( + name: "First", + returnType: ReturnTypeForInt (), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareDiffIsReferenceType () + { + var x = new Property ( + name: "First", + returnType: new ( + name: "string", + isBlittable: false, + isSmartEnum: false, + isNullable: false, + isArray: false, + isReferenceType: false + ), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + var y = new Property ( + name: "First", + returnType: new ( + name: "string", + isBlittable: false, + isSmartEnum: false, + isNullable: false, + isArray: false, + isReferenceType: true + ), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + + Assert.False (condition: x.Equals (other: y)); + Assert.False (condition: y.Equals (other: x)); + Assert.False (condition: x == y); + Assert.True (condition: x != y); + } + + [Fact] + public void CompareDiffIsBlittableType () + { + var x = new Property ( + name: "First", + returnType: new ( + name: "string", + isBlittable: true, + isSmartEnum: false, + isNullable: false, + isArray: false, + isReferenceType: false + ), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + var y = new Property ( + name: "First", + returnType: new ( + name: "string", + isBlittable: false, + isSmartEnum: false, + isNullable: false, + isArray: false, + isReferenceType: false + ), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareDiffIsSmartEnum () + { + var x = new Property ( + name: "First", + returnType: new ( + name: "string", + isBlittable: false, + isSmartEnum: true, + isNullable: false, + isArray: false, + isReferenceType: false + ), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + var y = new Property ( + name: "First", + returnType: new ( + name: "string", + isBlittable: false, + isSmartEnum: false, + isNullable: false, + isArray: false, + isReferenceType: false + ), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareDiffAttrs () + { + var x = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [], []); + var y = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr2"), + ], [], []); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareDiffModifiers () + { + var x = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.AbstractKeyword) + ], []); + var y = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword) + ], []); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareDiffAccessors () + { + var x = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword) + ], [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ]); + var y = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword) + ], [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ]); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareDiffAccessorsExportData () + { + var x = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword) + ], [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: new ("name"), + attributes: [], + modifiers: [] + ), + ]); + var y = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword) + ], [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: new ("surname"), + attributes: [], + modifiers: [] + ), + ]); + + Assert.False (x.Equals (y)); + Assert.False (y.Equals (x)); + Assert.False (x == y); + Assert.True (x != y); + } + + [Fact] + public void CompareEquals () + { + var x = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword) + ], [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ]); + var y = new Property ("First", ReturnTypeForString (), new (), [ + new ("Attr1"), + new ("Attr2"), + ], [ + SyntaxFactory.Token (SyntaxKind.PublicKeyword) + ], [ + new ( + accessorKind: AccessorKind.Getter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + new ( + accessorKind: AccessorKind.Setter, + symbolAvailability: new (), + exportPropertyData: null, + attributes: [], + modifiers: [] + ), + ]); + + Assert.True (x.Equals (y)); + Assert.True (y.Equals (x)); + Assert.True (x == y); + Assert.False (x != y); + } + + [Theory] + [InlineData (ObjCBindings.Property.Default, false)] + [InlineData (ObjCBindings.Property.Notification, true)] +#pragma warning disable xUnit1025 + [InlineData (ObjCBindings.Property.Notification | ObjCBindings.Property.Default, true)] +#pragma warning restore xUnit1025 + public void IsNotification (ObjCBindings.Property flag, bool expectedResult) + { + var property = new Property ( + name: "Test", + returnType: new TypeInfo ("string"), + symbolAvailability: new (), + attributes: [], + modifiers: [], + accessors: [] + ) { + ExportFieldData = new (new FieldData ("name", flag), ""), + }; + Assert.Equal (expectedResult, property.IsNotification); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/NeedsTempReturnTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/NeedsTempReturnTests.cs new file mode 100644 index 000000000000..24fd41b5912f --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/NeedsTempReturnTests.cs @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using Xunit; + +namespace Microsoft.Macios.Generator.Tests.DataModel.PropertyTests; + +public class NeedsTempReturnTests : BaseGeneratorTestClass { + + class TestDataUseTempReturn : IEnumerable { + public IEnumerator GetEnumerator () + { + const string nsobjectProperty = @" +using System; +using ObjCBindings; +using Foundation; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual NSUrl AppStoreReceiptUrl { get; } +} +"; + yield return [ + nsobjectProperty, + true + ]; + + const string stringProperty = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual string BuiltinPluginsPath { get; } +"; + yield return [ + stringProperty, + false + ]; + + const string boolProperty = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual bool BuiltinPluginsPath { get; } +"; + yield return [ + boolProperty, + true + ]; + + const string charProperty = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual char BuiltinPluginsPath { get; } +"; + yield return [ + charProperty, + true + ]; + + const string nfloatProperty = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual nfloat BuiltinPluginsPath { get; } +"; + yield return [ + nfloatProperty, + false + ]; + + const string stretType = @" +using System; +using ObjCBindings; +using CoreGraphics; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual NMatrix4 BuiltinPluginsPath { get; } +"; + yield return [ + stretType, + true + ]; + + const string nativeEnumType = @" +using System; +using AVFoundation; +using ObjCBindings; +using CoreGraphics; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual AVAudioApplicationMicrophoneInjectionPermission BuiltinPluginsPath { get; } +"; + yield return [ + nativeEnumType, + true + ]; + + const string delegateProperty = @" +using System; +using AVFoundation; +using ObjCBindings; +using CoreGraphics; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"")] + public virtual Action BuiltinPluginsPath { get; } +"; + yield return [ + delegateProperty, + true + ]; + + const string marshalNativeExceptions = @" +using System; +using ObjCBindings; + +namespace Test; + +public class TestClass { + [Export(""appStoreReceiptURL"", Flags = Property.MarshalNativeExceptions)] + public virtual string BuiltinPluginsPath { get; } +"; + yield return [ + marshalNativeExceptions, + true + ]; + + } + + IEnumerator IEnumerable.GetEnumerator () + => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void UseTempReturnTests (ApplePlatform platform, string inputText, bool expected) + { + var (compilation, syntaxTrees) = CreateCompilation (platform, sources: inputText); + Assert.Single (syntaxTrees); + var semanticModel = compilation.GetSemanticModel (syntaxTrees [0]); + var declaration = syntaxTrees [0].GetRoot () + .DescendantNodes ().OfType () + .FirstOrDefault (); + Assert.NotNull (declaration); + Assert.True (Property.TryCreate (declaration, semanticModel, out var changes)); + Assert.NotNull (changes); + Assert.Equal (expected, changes.Value.UseTempReturn); + } +} diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertiesEqualityComparerTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/PropertiesEqualityComparerTests.cs similarity index 98% rename from tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertiesEqualityComparerTests.cs rename to tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/PropertiesEqualityComparerTests.cs index ecc3fe1a84df..b9b93d5a0c3a 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertiesEqualityComparerTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/DataModel/PropertyTests/PropertiesEqualityComparerTests.cs @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. + using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp; using Microsoft.Macios.Generator.DataModel; using Xunit; -namespace Microsoft.Macios.Generator.Tests.DataModel; +namespace Microsoft.Macios.Generator.Tests.DataModel.PropertyTests; public class PropertiesEqualityComparerTests { readonly PropertiesEqualityComparer equalityComparer = new (); diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs index e2647ab54caa..ab1840b29dec 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Emitters/BindingSyntaxFactoryObjCRuntimeTests.cs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System; using System.Collections; using System.Collections.Generic; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Macios.Generator.DataModel; using Xunit; using static Microsoft.Macios.Generator.Emitters.BindingSyntaxFactory; @@ -12,11 +14,9 @@ namespace Microsoft.Macios.Generator.Tests.Emitters; public class BindingSyntaxFactoryObjCRuntimeTests { - class TestDataCastToNativeTests : IEnumerable { public IEnumerator GetEnumerator () { - // not enum parameter var boolParam = new Parameter ( position: 0, @@ -95,6 +95,7 @@ public IEnumerator GetEnumerator () yield return [longParam, "(long) myParam"]; } + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); } @@ -132,51 +133,60 @@ public IEnumerator GetEnumerator () yield return [ new Parameter (0, ReturnTypeForInt (isNullable: false), "myParam"), null!, - false]; + false + ]; // not nullable string[] yield return [ new Parameter (0, ReturnTypeForArray ("string", isNullable: false), "myParam"), "var nsa_myParam = NSArray.FromStrings (myParam);", - false]; + false + ]; yield return [ new Parameter (0, ReturnTypeForArray ("string", isNullable: false), "myParam"), "using var nsa_myParam = NSArray.FromStrings (myParam);", - true]; + true + ]; // nullable string [] yield return [ new Parameter (0, ReturnTypeForArray ("string", isNullable: true), "myParam"), "var nsa_myParam = myParam is null ? null : NSArray.FromStrings (myParam);", - false]; + false + ]; yield return [ new Parameter (0, ReturnTypeForArray ("string", isNullable: true), "myParam"), "using var nsa_myParam = myParam is null ? null : NSArray.FromStrings (myParam);", - true]; + true + ]; // nsstrings yield return [ new Parameter (0, ReturnTypeForArray ("NSString", isNullable: false), "myParam"), "var nsa_myParam = NSArray.FromNSObjects (myParam);", - false]; + false + ]; yield return [ new Parameter (0, ReturnTypeForArray ("NSString", isNullable: false), "myParam"), "using var nsa_myParam = NSArray.FromNSObjects (myParam);", - true]; + true + ]; yield return [ new Parameter (0, ReturnTypeForArray ("NSString", isNullable: true), "myParam"), "var nsa_myParam = myParam is null ? null : NSArray.FromNSObjects (myParam);", - false]; + false + ]; yield return [ new Parameter (0, ReturnTypeForArray ("NSString", isNullable: true), "myParam"), "using var nsa_myParam = myParam is null ? null : NSArray.FromNSObjects (myParam);", - true]; + true + ]; } IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); @@ -330,7 +340,6 @@ public IEnumerator GetEnumerator () new Parameter (0, ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_UInt64), "myParam"), "var nsb_myParam = NSNumber.FromUInt64 ((ulong) myParam);", ]; - } IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); @@ -490,9 +499,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForArray ("nint"), - name: "myParam") { - BindAs = new ("Foundation.NSNumber"), - }, + name: "myParam") { BindAs = new ("Foundation.NSNumber"), }, "var nsb_myParam = NSArray.FromNSObjects (obj => new NSNumber (obj), myParam);" ]; @@ -501,9 +508,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForArray ("CoreGraphics.CGAffineTransform", isStruct: true), - name: "myParam") { - BindAs = new ("Foundation.NSValue"), - }, + name: "myParam") { BindAs = new ("Foundation.NSValue"), }, "var nsb_myParam = NSArray.FromNSObjects (obj => new NSValue (obj), myParam);" ]; @@ -512,9 +517,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForArray ("MySmartEnum", isEnum: true, isSmartEnum: true), - name: "myParam") { - BindAs = new ("Foundation.NSString"), - }, + name: "myParam") { BindAs = new ("Foundation.NSString"), }, "var nsb_myParam = NSArray.FromNSObjects (obj => obj.GetConstant(), myParam);" ]; } @@ -543,9 +546,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_UInt64), - name: "myParam") { - BindAs = new ("Foundation.NSNumber"), - }, + name: "myParam") { BindAs = new ("Foundation.NSNumber"), }, "var nsb_myParam = NSNumber.FromUInt64 ((ulong) myParam);", ]; @@ -553,9 +554,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForArray ("nint"), - name: "myParam") { - BindAs = new ("Foundation.NSNumber"), - }, + name: "myParam") { BindAs = new ("Foundation.NSNumber"), }, "var nsb_myParam = NSArray.FromNSObjects (obj => new NSNumber (obj), myParam);" ]; @@ -564,9 +563,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForStruct ("CoreAnimation.CATransform3D"), - name: "myParam") { - BindAs = new ("Foundation.NSValue"), - }, + name: "myParam") { BindAs = new ("Foundation.NSValue"), }, "var nsb_myParam = NSValue.FromCATransform3D (myParam);", ]; @@ -574,9 +571,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForArray ("CoreGraphics.CGAffineTransform", isStruct: true), - name: "myParam") { - BindAs = new ("Foundation.NSValue"), - }, + name: "myParam") { BindAs = new ("Foundation.NSValue"), }, "var nsb_myParam = NSArray.FromNSObjects (obj => new NSValue (obj), myParam);" ]; @@ -585,9 +580,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForEnum ("CoreAnimation.CATransform3D", isSmartEnum: true), - name: "myParam") { - BindAs = new ("Foundation.NSString"), - }, + name: "myParam") { BindAs = new ("Foundation.NSString"), }, "var nsb_myParam = myParam.GetConstant ();", ]; @@ -595,9 +588,7 @@ public IEnumerator GetEnumerator () new Parameter ( position: 0, type: ReturnTypeForArray ("MySmartEnum", isEnum: true, isSmartEnum: true), - name: "myParam") { - BindAs = new ("Foundation.NSString"), - }, + name: "myParam") { BindAs = new ("Foundation.NSString"), }, "var nsb_myParam = NSArray.FromNSObjects (obj => obj.GetConstant(), myParam);" ]; @@ -609,7 +600,6 @@ public IEnumerator GetEnumerator () name: "myParam"), null! ]; - } IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); @@ -662,4 +652,81 @@ void GetExceptionHandleAuxVariableTests () var declaration = GetExceptionHandleAuxVariable (); Assert.Equal (expected, declaration.ToString ()); } + + class TestDataUsingTests : IEnumerable { + public IEnumerator GetEnumerator () + { + yield return [ + GetAutoreleasePoolVariable (), + "using var autorelease_pool = new NSAutoreleasePool ();", + ]; + + Parameter parameter = new ( + position: 0, + type: ReturnTypeForEnum ("MyEnum", underlyingType: SpecialType.System_UInt64), + name: "myParam") { BindAs = new ("Foundation.NSNumber") }; + + yield return [ + GetBindFromAuxVariable (parameter)!, + "using var nsb_myParam = NSNumber.FromUInt64 ((ulong) myParam);", + ]; + + parameter = new ( + position: 0, + type: ReturnTypeForArray ("nint"), + name: "myParam") { BindAs = new ("Foundation.NSNumber") }; + + yield return [ + GetBindFromAuxVariable (parameter)!, + "using var nsb_myParam = NSArray.FromNSObjects (obj => new NSNumber (obj), myParam);", + ]; + + parameter = new ( + position: 0, + type: ReturnTypeForStruct ("CoreAnimation.CATransform3D"), + name: "myParam") { BindAs = new ("Foundation.NSValue") }; + + yield return [ + GetBindFromAuxVariable (parameter)!, + "using var nsb_myParam = NSValue.FromCATransform3D (myParam);", + ]; + + parameter = new ( + position: 0, + type: ReturnTypeForArray ("CoreGraphics.CGAffineTransform", isStruct: true), + name: "myParam") { BindAs = new ("Foundation.NSValue") }; + + yield return [ + GetBindFromAuxVariable (parameter)!, + "using var nsb_myParam = NSArray.FromNSObjects (obj => new NSValue (obj), myParam);", + ]; + + parameter = new ( + position: 0, + type: ReturnTypeForEnum ("CoreAnimation.CATransform3D", isSmartEnum: true), + name: "myParam") { BindAs = new ("Foundation.NSString"), }; + + yield return [ + GetBindFromAuxVariable (parameter)!, + "using var nsb_myParam = myParam.GetConstant ();", + ]; + + parameter = new Parameter ( + position: 0, + type: ReturnTypeForArray ("MySmartEnum", isEnum: true, isSmartEnum: true), + name: "myParam") { BindAs = new ("Foundation.NSString"), }; + + yield return [ + GetBindFromAuxVariable (parameter)!, + "using var nsb_myParam = NSArray.FromNSObjects (obj => obj.GetConstant(), myParam);", + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [ClassData (typeof (TestDataUsingTests))] + void UsingTests (LocalDeclarationStatementSyntax declaration, string expectedDeclaration) + => Assert.Equal (expectedDeclaration, Using (declaration).ToString ()); } diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/BindingTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/BindingTests.cs new file mode 100644 index 000000000000..681b504c3f22 --- /dev/null +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/BindingTests.cs @@ -0,0 +1,415 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Macios.Generator.Attributes; +using Microsoft.Macios.Generator.Availability; +using Microsoft.Macios.Generator.DataModel; +using Microsoft.Macios.Transformer.DataModel; +using Xamarin.Tests; +using Xamarin.Utils; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Microsoft.Macios.Transformer.Tests.DataModel; + +public class BindingTests : BaseTransformerTestClass { + + readonly TransformerBindingEqualityComparer comparer = new (); + class TestDataTryCreate : IEnumerable { + public IEnumerator GetEnumerator () + { + var path = "/some/random/path.cs"; + var availabilityBuilder = SymbolAvailability.CreateBuilder (); + availabilityBuilder.Add (new SupportedOSPlatformData ("ios")); + availabilityBuilder.Add (new SupportedOSPlatformData ("tvos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("macos")); + availabilityBuilder.Add (new SupportedOSPlatformData ("maccatalyst")); + + const string simpleNSObject = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[BaseType (typeof (NSObject))] +interface MyNSArray : NSSecureCoding, NSMutableCopying, INSFastEnumeration, CKRecordValue { +} +"; + + yield return [ + (Source: simpleNSObject, Path: path), + new Binding ( + symbolName: "MyNSArray", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSArray", + info: new BindingInfo (new ("Foundation.NSObject"), BindingType.Class), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = "Foundation.NSObject", + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = ["Foundation.INSFastEnumeration"], + Protocols = [ + "Foundation.NSSecureCoding", + "Foundation.NSMutableCopying", + "CloudKit.CKRecordValue"], + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string internalSimpleNSObject = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[Internal] +[BaseType (typeof (NSObject))] +interface MyNSArray : NSSecureCoding, NSMutableCopying, INSFastEnumeration, CKRecordValue { +} +"; + + yield return [ + (Source: internalSimpleNSObject, Path: path), + new Binding ( + symbolName: "MyNSArray", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSArray", + info: new BindingInfo (new ("Foundation.NSObject"), BindingType.Class), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = "Foundation.NSObject", + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = ["Foundation.INSFastEnumeration"], + Protocols = [ + "Foundation.NSSecureCoding", + "Foundation.NSMutableCopying", + "CloudKit.CKRecordValue"], + Modifiers = [ + Token (SyntaxKind.InternalKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string staticNSObject = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[Static] +[BaseType (typeof (NSObject))] +interface MyNSArray { +} +"; + + yield return [ + (Source: staticNSObject, Path: path), + new Binding ( + symbolName: "MyNSArray", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSArray", + info: new BindingInfo (new ("Foundation.NSObject"), BindingType.Class), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = "Foundation.NSObject", + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = [], + Protocols = [], + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.StaticKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string nsObjectWithParent = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[BaseType (typeof (NSArray))] +interface MyNSArray : NSSecureCoding, NSMutableCopying, INSFastEnumeration, CKRecordValue { +} +"; + + yield return [ + (Source: nsObjectWithParent, Path: path), + new Binding ( + symbolName: "MyNSArray", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSArray", + info: new BindingInfo (new ("Foundation.NSArray"), BindingType.Class), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = "Foundation.NSArray", + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = ["Foundation.INSFastEnumeration"], + Protocols = [ + "Foundation.NSSecureCoding", + "Foundation.NSMutableCopying", + "CloudKit.CKRecordValue"], + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string publicCategory = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[Category, BaseType (typeof (NSOrderedSet))] +partial interface MyNSKeyValueSorting_NSOrderedSet { } +"; + + yield return [ + (Source: publicCategory, Path: path), + new Binding ( + symbolName: "MyNSKeyValueSorting_NSOrderedSet", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSKeyValueSorting_NSOrderedSet", + info: new BindingInfo (new ("Foundation.NSOrderedSet"), BindingType.Category), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = "object", + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = [], + Protocols = [], + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.StaticKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string internalCategory = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[Internal, Category, BaseType (typeof (NSOrderedSet))] +partial interface MyNSKeyValueSorting_NSOrderedSet { } +"; + + yield return [ + (Source: internalCategory, Path: path), + new Binding ( + symbolName: "MyNSKeyValueSorting_NSOrderedSet", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSKeyValueSorting_NSOrderedSet", + info: new BindingInfo (new ("Foundation.NSOrderedSet"), BindingType.Category), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = "object", + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = [], + Protocols = [], + Modifiers = [ + Token (SyntaxKind.InternalKeyword), + Token (SyntaxKind.StaticKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string simpleProtocol = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[Protocol, BaseType (typeof (NSObject))] +interface MyNSCacheDelegate { } + +"; + + yield return [ + (Source: simpleProtocol, Path: path), + new Binding ( + symbolName: "MyNSCacheDelegate", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSCacheDelegate", + info: new BindingInfo (new ("Foundation.NSObject"), BindingType.Protocol), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = string.Empty, + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = [], + Protocols = [], + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string protocolWithParent = @" +using System; +using Foundation; +using CloudKit; +using ObjCRuntime; + +namespace Test; + +[Protocol, BaseType (typeof (NSObject))] +interface MyNSCacheDelegate : NSSecureCoding { } + +"; + + yield return [ + (Source: protocolWithParent, Path: path), + new Binding ( + symbolName: "MyNSCacheDelegate", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyNSCacheDelegate", + info: new BindingInfo (new ("Foundation.NSObject"), BindingType.Protocol), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = string.Empty, + UsingDirectives = new HashSet { + "System", + "Foundation", + "CloudKit", + "ObjCRuntime" + }, + Interfaces = [], + Protocols = [ + "Foundation.NSSecureCoding", + ], + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + + const string coreImageFilter = @" +using System; +using Foundation; +using CoreImage; +using ObjCRuntime; + +namespace Test; + +[CoreImageFilter] +[BaseType (typeof (CIFilter))] +interface MyCIAccordionFoldTransition : CIAccordionFoldTransitionProtocol { +} +"; + + yield return [ + (Source: coreImageFilter, Path: path), + new Binding ( + symbolName: "MyCIAccordionFoldTransition", + @namespace: ["Test"], + fullyQualifiedSymbol: "Test.MyCIAccordionFoldTransition", + info: new BindingInfo (new ("CoreImage.CIFilter"), BindingType.CoreImageFilter), + symbolAvailability: availabilityBuilder.ToImmutable (), + attributes: new () + ) { + Base = "CoreImage.CIFilter", + UsingDirectives = new HashSet { + "System", + "Foundation", + "CoreImage", + "ObjCRuntime" + }, + Interfaces = [], + Protocols = ["CoreImage.CIAccordionFoldTransitionProtocol"], + Modifiers = [ + Token (SyntaxKind.PublicKeyword), + Token (SyntaxKind.PartialKeyword)] + } + ]; + } + + IEnumerator IEnumerable.GetEnumerator () => GetEnumerator (); + } + + [Theory] + [AllSupportedPlatformsClassData] + void TryCreateTests (ApplePlatform platform, (string Source, string Path) source, Binding expectedData) + { + var compilation = CreateCompilation (platform, sources: source); + var syntaxTree = compilation.SyntaxTrees.ForSource (source); + var trees = compilation.SyntaxTrees.Where (s => s.FilePath == source.Path).ToArray (); + Assert.Single (trees); + Assert.NotNull (syntaxTree); + + var semanticModel = compilation.GetSemanticModel (syntaxTree); + Assert.NotNull (semanticModel); + + var declaration = syntaxTree.GetRoot () + .DescendantNodes ().OfType () + .LastOrDefault (); + Assert.NotNull (declaration); + + var symbol = semanticModel.GetDeclaredSymbol (declaration); + Assert.NotNull (symbol); + + var binding = new Binding (declaration, symbol, new (semanticModel)); + Assert.Equal (expectedData, binding, comparer); + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/MethodTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/GeneralTests.cs similarity index 99% rename from tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/MethodTests.cs rename to tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/GeneralTests.cs index cb83b8919bb7..afb2ecc13ec4 100644 --- a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/MethodTests.cs +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/GeneralTests.cs @@ -16,7 +16,7 @@ namespace Microsoft.Macios.Transformer.Tests.DataModel; -public class MethodTests : BaseTransformerTestClass { +public class GeneralTests : BaseTransformerTestClass { [Theory] [InlineData ("Hello", false)] diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs index 07396190bfc6..43892ab4be97 100644 --- a/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/DataModel/SmartEnumTests.cs @@ -16,7 +16,7 @@ namespace Microsoft.Macios.Transformer.Tests.DataModel; public class SmartEnumTests : BaseTransformerTestClass { - readonly BindingEqualityComparer comparer = new (); + readonly TransformerBindingEqualityComparer comparer = new (); class TestDataTryCreate : IEnumerable { public IEnumerator GetEnumerator () { diff --git a/tests/xharness/Jenkins/TestServer.cs b/tests/xharness/Jenkins/TestServer.cs index 0c1609be8102..d739cdccfd96 100644 --- a/tests/xharness/Jenkins/TestServer.cs +++ b/tests/xharness/Jenkins/TestServer.cs @@ -95,7 +95,17 @@ IEnumerable find_tasks (StreamWriter writer, string ids) } string serveFile = null; - switch (request.Url.LocalPath) { + var localPath = request.Url.LocalPath; + if (localPath.Contains ("..") || localPath.Contains ("/") || localPath.Contains ("\\")) { + // Validate that we're not requested to serve any file on the file system. + // Ref: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/2351243 + response.StatusCode = 400; + response.StatusDescription = "Bad Request"; + response.OutputStream.Write (System.Text.Encoding.UTF8.GetBytes ("Invalid local path")); + return; + } + + switch (localPath) { case "/": response.ContentType = System.Net.Mime.MediaTypeNames.Text.Html; using (var writer = new StreamWriter (response.OutputStream)) { @@ -188,10 +198,10 @@ IEnumerable find_tasks (StreamWriter writer, string ids) writer.WriteLine ("unknown query: {0}", request.Url.Query); break; } - if (request.Url.LocalPath == "/select") { + if (localPath == "/select") { if (is_match.HasValue && is_match.Value) task.Ignored = false; - } else if (request.Url.LocalPath == "/deselect") { + } else if (localPath == "/deselect") { if (is_match.HasValue && is_match.Value) task.Ignored = true; } @@ -273,17 +283,17 @@ IEnumerable find_tasks (StreamWriter writer, string ids) response.Redirect (redirect_to); break; default: - var filename = Path.GetFileName (request.Url.LocalPath); - if (filename == "index.html" && Path.GetFileName (jenkins.LogDirectory) == Path.GetFileName (Path.GetDirectoryName (request.Url.LocalPath))) { + var filename = Path.GetFileName (localPath); + if (filename == "index.html" && Path.GetFileName (jenkins.LogDirectory) == Path.GetFileName (Path.GetDirectoryName (localPath))) { // We're asked for the report for the current test run, so re-generate it. jenkins.GenerateReport (); } if (serveFile is null) { - serveFile = Path.Combine (Path.GetDirectoryName (jenkins.LogDirectory), request.Url.LocalPath.Substring (1)); + serveFile = Path.Combine (Path.GetDirectoryName (jenkins.LogDirectory), localPath.Substring (1)); serveFile = Path.GetFullPath (serveFile); if (!serveFile.StartsWith (Path.GetDirectoryName (Path.GetFullPath (jenkins.LogDirectory)) + Path.DirectorySeparatorChar)) { - Console.WriteLine ($"400: {request.Url.LocalPath}"); + Console.WriteLine ($"400: {localPath}"); response.StatusCode = 400; response.OutputStream.WriteByte ((byte) '?'); break; @@ -316,7 +326,7 @@ IEnumerable find_tasks (StreamWriter writer, string ids) response.OutputStream.Write (buffer, 0, read); } } else { - Console.WriteLine ($"404: {request.Url.LocalPath}"); + Console.WriteLine ($"404: {localPath}"); response.StatusCode = 404; response.OutputStream.WriteByte ((byte) '?'); } diff --git a/tools/dotnet-linker/CecilExtensions.cs b/tools/dotnet-linker/CecilExtensions.cs index 7bc79c696a51..810cc0db91a5 100644 --- a/tools/dotnet-linker/CecilExtensions.cs +++ b/tools/dotnet-linker/CecilExtensions.cs @@ -50,6 +50,16 @@ public static MethodBody CreateBody (this MethodDefinition self, out ILProcessor return body; } + public static void GenerateILOffsets (this MethodBody body) + { + // This does not compute precise offsets, it just assigns a unique number to each instruction + // The trimmer relies on unique offsets to identify instructions + int instructionOffset = 0; + foreach (var instruction in body.Instructions) { + instruction.Offset = instructionOffset++; + } + } + public static void AddRange (this Mono.Collections.Generic.Collection self, IEnumerable? items) { if (items is null) @@ -124,10 +134,11 @@ public static MethodDefinition AddDefaultConstructor (this TypeDefinition type, { // Add default ctor that just calls the base ctor var defaultCtor = type.AddMethod (".ctor", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, abr.System_Void); - defaultCtor.CreateBody (out var il); + var body = defaultCtor.CreateBody (out var il); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Call, abr.System_Object__ctor); il.Emit (OpCodes.Ret); + body.GenerateILOffsets (); return defaultCtor; } diff --git a/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs b/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs index 2f1bf9954da4..0d3461aa7a45 100644 --- a/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs +++ b/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs @@ -264,6 +264,8 @@ void GenerateLookupTypeId (AssemblyTrampolineInfo infos, TypeDefinition registra // No match, return -1 il.Emit (OpCodes.Ldc_I4_M1); il.Emit (OpCodes.Ret); + + body.GenerateILOffsets (); } void GenerateLookupType (AssemblyTrampolineInfo infos, TypeDefinition registrarType, List types) @@ -304,6 +306,8 @@ void GenerateLookupType (AssemblyTrampolineInfo infos, TypeDefinition registrarT il.Emit (OpCodes.Initobj, abr.System_RuntimeTypeHandle); il.Emit (OpCodes.Ldloc, temporary); il.Emit (OpCodes.Ret); + + body.GenerateILOffsets (); } void GenerateConstructNSObject (TypeDefinition registrarType) @@ -360,6 +364,8 @@ void GenerateConstructNSObject (TypeDefinition registrarType) // return default (NSObject); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ret); + + body.GenerateILOffsets (); } void GenerateConstructINativeObject (TypeDefinition registrarType) @@ -417,6 +423,8 @@ void GenerateConstructINativeObject (TypeDefinition registrarType) // return default (NSObject) il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ret); + + body.GenerateILOffsets (); } void AddTypeInterfaceImplementation (TypeDefinition type, TypeReference iface) @@ -458,6 +466,8 @@ void ImplementConstructNSObjectFactoryMethod (TypeDefinition type, MethodReferen il.Emit (OpCodes.Newobj, ctor); il.Emit (OpCodes.Ret); + body.GenerateILOffsets (); + Annotations.Mark (createInstanceMethod); } @@ -530,6 +540,8 @@ void ImplementConstructINativeObjectFactoryMethod (TypeDefinition type, MethodRe throw new UnreachableException (); } + body.GenerateILOffsets (); + Annotations.Mark (createInstanceMethod); } @@ -568,7 +580,7 @@ void GenerateRegisterWrapperTypes (TypeDefinition type) var method = type.AddMethod ("RegisterWrapperTypes", MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig, abr.System_Void); method.AddParameter ("type", abr.System_Collections_Generic_Dictionary2.CreateGenericInstanceType (abr.System_RuntimeTypeHandle, abr.System_RuntimeTypeHandle)); method.Overrides.Add (abr.IManagedRegistrar_RegisterWrapperTypes); - method.CreateBody (out var il); + var body = method.CreateBody (out var il); // Find all the protocol interfaces that are defined in the current assembly, and their corresponding wrapper type, // and add the pair to the dictionary. @@ -596,6 +608,8 @@ void GenerateRegisterWrapperTypes (TypeDefinition type) } il.Emit (OpCodes.Ret); + + body.GenerateILOffsets (); } void GenerateLookupUnmanagedFunction (TypeDefinition registrar_type, IList trampolineInfos) @@ -619,7 +633,7 @@ void GenerateLookupUnmanagedFunction (TypeDefinition registrar_type, IList Date: Thu, 13 Feb 2025 18:09:19 +0100 Subject: [PATCH 5/5] Re-run 'make format-csproj'. --- .../AVAssetDownloadStorageManagementPolicy.cs | 2 +- src/AVFoundation/AVCaptureMetadataOutput.cs | 4 +- .../AVMetadataMachineReadableCodeObject.cs | 4 +- src/AVFoundation/AVOutputSettingsAssistant.cs | 6 +- src/AVRouting/AVCustomDeviceRoute.cs | 2 +- src/Accessibility/AXSettings.cs | 2 +- src/AddressBook/ABAddressBook.cs | 2 +- src/AppKit/Functions.cs | 4 +- src/AppKit/NSGraphics.cs | 4 +- src/AppKit/NSPasteboardReading.cs | 2 +- src/AudioToolbox/AudioConverter.cs | 4 +- src/AudioToolbox/AudioFile.cs | 2 +- src/AudioToolbox/AudioFileStream.cs | 2 +- src/AudioToolbox/AudioQueue.cs | 10 +- src/AudioToolbox/MusicTrack.cs | 2 +- src/AudioToolbox/SystemSound.cs | 2 +- src/AudioUnit/AUEnums.cs | 60 ++-- src/AudioUnit/AUGraph.cs | 8 +- src/AudioUnit/AudioComponent.cs | 21 +- src/AudioUnit/AudioComponentDescription.cs | 38 +-- src/AudioUnit/AudioUnit.cs | 9 +- src/AudioUnit/AudioUnitUtils.cs | 8 +- src/AudioUnit/ExtAudioFile.cs | 8 +- src/BrowserEngineKit/BEStructs.cs | 19 +- src/Compression/CompressionStreamStruct.cs | 8 +- src/Compression/TaskToApm.cs | 180 +++++------ src/CoreAnimation/CATextLayer.cs | 2 +- src/CoreAnimation/CATransform3D.cs | 8 +- src/CoreBluetooth/CBPeer.cs | 2 +- src/CoreFoundation/CFMessagePort.cs | 12 +- src/CoreGraphics/CGAffineTransform.cs | 22 +- src/CoreGraphics/CGColorSpace.cs | 2 +- src/CoreGraphics/CGDisplay.cs | 45 ++- src/CoreGraphics/CGEvent.cs | 58 ++-- src/CoreGraphics/CGEventSource.cs | 22 +- src/CoreGraphics/CGEventTypes.cs | 50 +-- src/CoreGraphics/CGImage.cs | 22 +- src/CoreGraphics/CGPattern.cs | 3 +- src/CoreGraphics/CGVector.cs | 4 +- src/CoreImage/Enums.cs | 2 +- src/CoreLocation/CLLocationManager.cs | 2 +- src/CoreMidi/MidiBluetoothDriver.cs | 8 +- src/CoreServices/FSEvents.cs | 34 +- src/CoreServices/LaunchServices.cs | 41 ++- src/CoreSpotlight/CSSearchableIndex.cs | 2 +- .../CSSearchableItemAttributeSet.cs | 13 +- src/CoreText/CTFontCollection.cs | 2 +- src/CoreText/CTFontManager.cs | 8 +- src/CoreVideo/CVDisplayLink.cs | 52 +-- src/CoreVideo/CVImageBuffer.cs | 2 +- src/Darwin/KernelNotification.cs | 146 ++++----- src/Darwin/SystemLog.cs | 60 ++-- src/FileProvider/Structs.cs | 5 +- src/Foundation/Enum.cs | 4 +- src/Foundation/NSAppleEventDescriptor.cs | 6 +- src/Foundation/NSAttributedString.cs | 8 +- src/Foundation/NSAttributedString.mac.cs | 10 +- src/Foundation/NSConnection.cs | 8 +- src/Foundation/NSHost.cs | 8 +- src/Foundation/NSIndexSet.cs | 38 +-- src/Foundation/NSNumber.mac.cs | 28 +- src/Foundation/NSObject.mac.cs | 2 +- src/Foundation/NSPropertyListSerialization.cs | 6 +- .../NSScriptCommandArgumentDescription.cs | 8 +- src/Foundation/NSScriptCommandDescription.cs | 16 +- .../NSScriptCommandDescriptionDictionary.cs | 20 +- src/Foundation/NSSecureCoding.cs | 3 +- src/Foundation/NSString.cs | 6 +- src/Foundation/NSThread.mac.cs | 13 +- src/Foundation/NSUrlDownload.cs | 2 +- src/GameKit/GKCompat.cs | 5 +- src/ImageIO/CGImageAnimation.cs | 40 +-- .../INSetClimateSettingsInCarIntent.cs | 2 +- src/MapKit/MapKit.cs | 2 +- src/MediaExtension/MEByteSource.cs | 8 +- .../MERawProcessingListParameter.cs | 2 +- src/MediaExtension/MESampleCursor.cs | 2 +- src/MediaToolbox/MTAudioProcessingTap.cs | 64 ++-- src/Metal/Defs.cs | 3 +- src/Metal/MTLArgumentEncoder.cs | 4 +- src/Metal/MTLArrays.cs | 3 +- src/Metal/MTLComputeCommandEncoder.cs | 4 +- .../MTLRasterizationRateLayerDescriptor.cs | 17 +- src/Metal/MTLResourceStateCommandEncoder.cs | 10 +- .../MPSGraphExecutable.cs | 8 +- src/MetricKit/MXMetaData.cs | 2 +- src/MetricKit/MXMetric.cs | 2 +- src/MetricKit/MXMetricPayload.cs | 2 +- ...IAlgorithmConvergenceStatusReasonValues.cs | 3 +- src/NearbyInteraction/NINearbyObject.cs | 15 +- src/Network/NWConnection.cs | 2 +- src/Network/NWConnectionGroup.cs | 2 +- src/Network/NWEndpoint.cs | 2 +- src/Network/NWEstablishmentReport.cs | 2 +- src/Network/NWEthernetChannel.cs | 22 +- src/Network/NWInterface.cs | 2 +- src/Network/NWParameters.cs | 4 +- src/Network/NWPath.cs | 2 +- src/Network/NWPrivacyContext.cs | 2 +- src/Network/NWProtocolDefinition.cs | 2 +- src/Network/NWProtocolFramerOptions.cs | 2 +- src/Network/NWProtocolMetadata.cs | 2 +- src/Network/NWProtocolOptions.cs | 2 +- src/Network/NWProtocolStack.cs | 2 +- src/Network/NWProxyConfig.cs | 2 +- src/Network/NWRelayHop.cs | 2 +- src/Network/NWResolverConfig.cs | 2 +- src/ObjCRuntime/BackingField.cs | 3 +- src/ObjCRuntime/BindAs.cs | 12 +- src/ObjCRuntime/Blocks.cs | 12 +- src/ObjCRuntime/Class.cs | 2 +- .../DelayedRegistrationAttribute.cs | 3 +- src/ObjCRuntime/Dlfcn.cs | 3 +- src/ObjCRuntime/INativeObject.cs | 2 +- src/ObjCRuntime/NativeHandle.cs | 4 +- src/ObjCRuntime/PlatformAvailability.cs | 2 +- src/ObjCRuntime/RegistrarHelper.cs | 24 +- src/ObjCRuntime/RequiredFrameworkAttribute.cs | 7 +- src/ObjCRuntime/Runtime.CoreCLR.cs | 52 +-- src/ObjCRuntime/Runtime.cs | 31 +- src/ObjCRuntime/Runtime.mac.cs | 4 +- src/PassKit/PKCompat.cs | 5 +- src/PdfKit/Enums.cs | 100 +++--- src/PhotosUI/PHEnums.cs | 4 +- src/QuickLook/Thumbnail.cs | 6 +- src/SceneKit/Defs.cs | 18 +- src/SceneKit/SCNMatrix4_dotnet.cs | 180 +++++------ src/SceneKit/SCNQuaternion.cs | 18 +- src/SceneKit/SCNVector3.cs | 88 +++--- src/SceneKit/SCNVector4.cs | 50 +-- src/Security/Authorization.cs | 80 ++--- src/Security/Enums.cs | 4 +- src/Security/Items.cs | 130 ++++---- src/Security/SecCertificate2.cs | 2 +- src/Security/SecIdentity2.cs | 2 +- src/Security/SecSharedCredential.cs | 26 +- src/Security/SecTrust2.cs | 2 +- src/Simd/MathHelper.cs | 3 +- src/Simd/MatrixFloat3x3RM.cs | 32 +- src/Simd/MatrixFloat4x3.cs | 2 +- src/Simd/QuaternionDouble.cs | 13 +- src/Simd/VectorDouble2.cs | 8 +- src/Simd/VectorDouble4.cs | 11 +- src/Simd/VectorInt2.cs | 8 +- src/Simd/VectorInt3.cs | 8 +- src/Simd/VectorInt4.cs | 8 +- src/StoreKit/SKOverlayAppClipConfiguration.cs | 7 +- src/StoreKit/SKOverlayAppConfiguration.cs | 7 +- src/System.Net.Http/CFNetworkHandler.cs | 2 +- src/UIKit/NSLayoutManager.cs | 2 +- src/UIKit/UIActionSheet.cs | 10 +- src/UIKit/UIAppearance.cs | 4 +- src/UIKit/UIButton.cs | 2 +- src/UIKit/UIDevice.cs | 2 +- src/UIKit/UIDocumentBrowserViewController.cs | 6 +- src/UIKit/UIImage.cs | 6 +- src/UIKit/UINavigationBar.cs | 4 +- src/UIKit/UIPasteboard.cs | 14 +- src/UIKit/UIPickerView.cs | 2 +- src/UIKit/UIPopoverPresentationController.cs | 2 +- src/UIKit/UIStringDrawing.cs | 2 +- src/UIKit/UITextAttributes.cs | 18 +- src/UIKit/UIToolbar.cs | 8 +- src/UIKit/UIVideo.cs | 12 +- src/VideoToolbox/VTCompressionSession.cs | 2 +- src/VideoToolbox/VTDecompressionSession.cs | 6 +- src/VideoToolbox/VTRawProcessingSession.cs | 4 +- src/accessorysetupkit.cs | 54 ++-- src/appkit.cs | 4 +- src/authenticationservices.cs | 9 +- src/avfoundation.cs | 10 +- src/backgroundassets.cs | 3 +- src/browserenginekit.cs | 297 ++++++++---------- src/contactsui.cs | 9 +- src/coreanimation.cs | 5 +- src/coredata.cs | 14 +- src/corehaptics.cs | 2 +- src/coreimage.cs | 6 +- src/corelocation.cs | 4 +- src/corenfc.cs | 8 +- src/coretext.cs | 9 +- src/cryptotokenkit.cs | 249 ++++++--------- src/eventkit.cs | 2 +- src/foundation.cs | 29 +- src/gamekit.cs | 16 +- src/healthkit.cs | 2 +- src/mapkit.cs | 10 +- src/mediaextension.cs | 225 ++++++------- src/mediaplayer.cs | 6 +- src/metal.cs | 2 +- src/metrickit.cs | 2 +- src/networkextension.cs | 4 +- src/quicklook.cs | 6 +- src/scenekit.cs | 2 +- src/sharedwithyou.cs | 12 +- src/soundanalysis.cs | 2 +- src/storekit.cs | 18 +- src/tvmlkit.cs | 9 +- src/uikit.cs | 4 +- src/webkit.cs | 6 +- src/xkit.cs | 76 ++--- 201 files changed, 1770 insertions(+), 1919 deletions(-) diff --git a/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs b/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs index 02331fe8f91a..b4bcb7ff7a81 100644 --- a/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs +++ b/src/AVFoundation/AVAssetDownloadStorageManagementPolicy.cs @@ -17,7 +17,7 @@ public virtual AVAssetDownloadedAssetEvictionPriority Priority { } public partial class AVMutableAssetDownloadStorageManagementPolicy { - + public override AVAssetDownloadedAssetEvictionPriority Priority { get { return AVAssetDownloadedAssetEvictionPriorityExtensions.GetValue (_Priority); } set { _Priority = value.GetConstant () ?? throw new ArgumentOutOfRangeException (nameof (Priority)); } diff --git a/src/AVFoundation/AVCaptureMetadataOutput.cs b/src/AVFoundation/AVCaptureMetadataOutput.cs index a4d7564bdeb2..48806d4fdf78 100644 --- a/src/AVFoundation/AVCaptureMetadataOutput.cs +++ b/src/AVFoundation/AVCaptureMetadataOutput.cs @@ -36,12 +36,12 @@ namespace AVFoundation { public partial class AVCaptureMetadataOutput { - + public AVMetadataObjectType AvailableMetadataObjectTypes { get { return AVMetadataObjectTypeExtensions.ToFlags (WeakAvailableMetadataObjectTypes); } } - public AVMetadataObjectType MetadataObjectTypes { + public AVMetadataObjectType MetadataObjectTypes { get { return AVMetadataObjectTypeExtensions.ToFlags (WeakMetadataObjectTypes); } set { WeakMetadataObjectTypes = value.ToArray (); } } diff --git a/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs b/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs index 0d40567dc4df..efa68e1be136 100644 --- a/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs +++ b/src/AVFoundation/AVMetadataMachineReadableCodeObject.cs @@ -36,12 +36,12 @@ namespace AVFoundation { public partial class AVMetadataMachineReadableCodeObject { - public CGPoint[]? Corners { + public CGPoint []? Corners { get { var arr = WeakCorners; if (arr is null) return null; - var rv = new CGPoint[arr.Length]; + var rv = new CGPoint [arr.Length]; for (int i = 0; i < rv.Length; i++) { var dict = arr [i]; CGPoint pnt; diff --git a/src/AVFoundation/AVOutputSettingsAssistant.cs b/src/AVFoundation/AVOutputSettingsAssistant.cs index 0b38d546a4a2..246b8e373345 100644 --- a/src/AVFoundation/AVOutputSettingsAssistant.cs +++ b/src/AVFoundation/AVOutputSettingsAssistant.cs @@ -20,19 +20,19 @@ public AVOutputSettingsAssistant? Preset640x480 { return FromPreset (_Preset640x480); } } - + public AVOutputSettingsAssistant? Preset960x540 { get { return FromPreset (_Preset960x540); } } - + public AVOutputSettingsAssistant? Preset1280x720 { get { return FromPreset (_Preset1280x720); } } - + public AVOutputSettingsAssistant? Preset1920x1080 { get { return FromPreset (_Preset1920x1080); diff --git a/src/AVRouting/AVCustomDeviceRoute.cs b/src/AVRouting/AVCustomDeviceRoute.cs index 0e48913281e2..20a878143495 100644 --- a/src/AVRouting/AVCustomDeviceRoute.cs +++ b/src/AVRouting/AVCustomDeviceRoute.cs @@ -13,7 +13,7 @@ namespace AVRouting { partial class AVCustomDeviceRoute { - public NWEndpoint NetworkEndpoint => new NWEndpoint (_NetworkEndpoint, owns: false); + public NWEndpoint NetworkEndpoint => new NWEndpoint (_NetworkEndpoint, owns: false); } } diff --git a/src/Accessibility/AXSettings.cs b/src/Accessibility/AXSettings.cs index 0d2cd574f394..760988c28a26 100644 --- a/src/Accessibility/AXSettings.cs +++ b/src/Accessibility/AXSettings.cs @@ -51,7 +51,7 @@ public static bool IsAssistiveAccessEnabled { [SupportedOSPlatform ("macos15.0")] [SupportedOSPlatform ("tvos18.0")] [DllImport (Constants.AccessibilityLibrary)] - unsafe static extern void AXOpenSettingsFeature (nint /* AXSettingsFeature */ feature, BlockLiteral *block); + unsafe static extern void AXOpenSettingsFeature (nint /* AXSettingsFeature */ feature, BlockLiteral* block); /// Open the Settings app to the specified section. /// The section to open. diff --git a/src/AddressBook/ABAddressBook.cs b/src/AddressBook/ABAddressBook.cs index cfcee0027fda..fbeeb3e682f1 100644 --- a/src/AddressBook/ABAddressBook.cs +++ b/src/AddressBook/ABAddressBook.cs @@ -85,7 +85,7 @@ static InitConstants () { #if __MACCATALYST__ // avoid TypeLoadException if used before macOS 11.x - if (!SystemVersion.CheckiOS (14,0)) + if (!SystemVersion.CheckiOS (14, 0)) return; #endif // ensure we can init. This is needed before iOS6 (as per doc). diff --git a/src/AppKit/Functions.cs b/src/AppKit/Functions.cs index afe5a2e27b13..4a4299de2950 100644 --- a/src/AppKit/Functions.cs +++ b/src/AppKit/Functions.cs @@ -36,9 +36,9 @@ namespace AppKit { #if MONOMAC // Class to access C functions public partial class AppKitFramework { - + [DllImport (Constants.AppKitLibrary)] - public static extern void NSBeep(); + public static extern void NSBeep (); } #endif } diff --git a/src/AppKit/NSGraphics.cs b/src/AppKit/NSGraphics.cs index 4d8d857e889e..617f034b17ef 100644 --- a/src/AppKit/NSGraphics.cs +++ b/src/AppKit/NSGraphics.cs @@ -181,7 +181,7 @@ public static void FrameRect (CGRect rect, nfloat frameWidth, NSCompositingOpera #if NET [SupportedOSPlatform ("macos")] - [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead." )] + [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead.")] #else [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use 'NSCursor.DisappearingItemCursor' instead.")] #endif @@ -190,7 +190,7 @@ public static void FrameRect (CGRect rect, nfloat frameWidth, NSCompositingOpera #if NET [SupportedOSPlatform ("macos")] - [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead." )] + [ObsoletedOSPlatform ("macos14.0", "Use 'NSCursor.DisappearingItemCursor' instead.")] #else [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use 'NSCursor.DisappearingItemCursor' instead.")] #endif diff --git a/src/AppKit/NSPasteboardReading.cs b/src/AppKit/NSPasteboardReading.cs index 04e90627818c..a6587fa1a415 100644 --- a/src/AppKit/NSPasteboardReading.cs +++ b/src/AppKit/NSPasteboardReading.cs @@ -11,7 +11,7 @@ namespace AppKit { public partial interface INSPasteboardReading { [BindingImpl (BindingImplOptions.Optimizable)] - public unsafe static T? CreateInstance (NSObject propertyList, NSPasteboardType type) where T: NSObject, INSPasteboardReading + public unsafe static T? CreateInstance (NSObject propertyList, NSPasteboardType type) where T : NSObject, INSPasteboardReading { return CreateInstance (propertyList, type.GetConstant ()!); } diff --git a/src/AudioToolbox/AudioConverter.cs b/src/AudioToolbox/AudioConverter.cs index 4a672adc6b86..b993c9f7208d 100644 --- a/src/AudioToolbox/AudioConverter.cs +++ b/src/AudioToolbox/AudioConverter.cs @@ -583,13 +583,13 @@ AudioConverterError FillComplexBuffer (ref int outputDataPacketSize, var packetSize = outputDataPacketSize; int* packetSizePtr = &packetSize; if (packetDescription is null) { - var returnOne = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr)packetSizePtr, (IntPtr) outputData, IntPtr.Zero); + var returnOne = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr) packetSizePtr, (IntPtr) outputData, IntPtr.Zero); outputDataPacketSize = packetSize; return returnOne; } fixed (AudioStreamPacketDescription* pdesc = packetDescription) { - var returnTwo = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr)packetSizePtr, (IntPtr) outputData, (IntPtr) pdesc); + var returnTwo = AudioConverterFillComplexBuffer (Handle, &FillComplexBufferShared, this_ptr, (IntPtr) packetSizePtr, (IntPtr) outputData, (IntPtr) pdesc); outputDataPacketSize = packetSize; return returnTwo; } diff --git a/src/AudioToolbox/AudioFile.cs b/src/AudioToolbox/AudioFile.cs index 71130c797555..83c5ca7ac299 100644 --- a/src/AudioToolbox/AudioFile.cs +++ b/src/AudioToolbox/AudioFile.cs @@ -1444,7 +1444,7 @@ public IntPtr GetProperty (AudioFileProperty property, out int size) return IntPtr.Zero; } #if NET - unsafe T? GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileProperty property) where T : unmanaged + unsafe T? GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileProperty property) where T : unmanaged #else unsafe T? GetProperty (AudioFileProperty property) where T : unmanaged #endif diff --git a/src/AudioToolbox/AudioFileStream.cs b/src/AudioToolbox/AudioFileStream.cs index 5c6395deb45a..d227efe43049 100644 --- a/src/AudioToolbox/AudioFileStream.cs +++ b/src/AudioToolbox/AudioFileStream.cs @@ -438,7 +438,7 @@ long GetLong (AudioFileStreamProperty property) } #if NET - unsafe T? GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileStreamProperty property) where T : unmanaged + unsafe T? GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioFileStreamProperty property) where T : unmanaged #else unsafe T? GetProperty (AudioFileStreamProperty property) where T : unmanaged #endif diff --git a/src/AudioToolbox/AudioQueue.cs b/src/AudioToolbox/AudioQueue.cs index 3d2a248651d8..1e7bee989edb 100644 --- a/src/AudioToolbox/AudioQueue.cs +++ b/src/AudioToolbox/AudioQueue.cs @@ -988,7 +988,7 @@ public IntPtr GetProperty (AudioQueueProperty property, out int size) // Should be private #if NET - public unsafe T GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioQueueProperty property) where T : struct + public unsafe T GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioQueueProperty property) where T : struct #else public unsafe T GetProperty (AudioQueueProperty property) where T : struct #endif @@ -1016,7 +1016,7 @@ public unsafe T GetProperty (AudioQueueProperty property) where T : struct } #if NET - unsafe T GetProperty<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioConverterPropertyID property) where T : struct + unsafe T GetProperty<[DynamicallyAccessedMembers (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T> (AudioConverterPropertyID property) where T : struct #else unsafe T GetProperty (AudioConverterPropertyID property) where T : struct #endif @@ -1189,7 +1189,7 @@ public AudioStreamBasicDescription AudioStreamDescription { #if !MONOMAC return GetProperty (AudioQueueProperty.StreamDescription); #else - return GetProperty (AudioConverterPropertyID.CurrentInputStreamDescription); + return GetProperty (AudioConverterPropertyID.CurrentInputStreamDescription); #endif } } @@ -1296,7 +1296,7 @@ extern static AudioQueueStatus AudioQueueProcessingTapNew (IntPtr inAQ, AudioQue #if NET unsafe { status = AudioQueueProcessingTapNew (handle, &AudioQueueProcessingTap.TapCallback, GCHandle.ToIntPtr (aqpt.Handle), flags, &maxFrames, - &processingFormat, &tapHandle); + &processingFormat, &tapHandle); } #else status = AudioQueueProcessingTapNew (handle, AudioQueueProcessingTap.CreateTapCallback, GCHandle.ToIntPtr (aqpt.Handle), flags, out maxFrames, @@ -1459,7 +1459,7 @@ public class OutputAudioQueue : AudioQueue { #if NET [DllImport (Constants.AudioToolboxLibrary)] extern unsafe static OSStatus AudioQueueNewOutput (AudioStreamBasicDescription* format, delegate* unmanaged callback, - IntPtr userData, IntPtr cfrunLoop_callbackRunloop, IntPtr cfstr_runMode, + IntPtr userData, IntPtr cfrunLoop_callbackRunloop, IntPtr cfstr_runMode, uint flags, IntPtr* audioQueue); #else static readonly AudioQueueOutputCallback dOutputCallback = output_callback; diff --git a/src/AudioToolbox/MusicTrack.cs b/src/AudioToolbox/MusicTrack.cs index 53d36bafc3cf..37866a3a50cc 100644 --- a/src/AudioToolbox/MusicTrack.cs +++ b/src/AudioToolbox/MusicTrack.cs @@ -309,7 +309,7 @@ public MusicPlayerStatus GetDestMidiEndpoint (out MidiEndpoint? outEndpoint) unsafe { result = MusicTrackGetDestMIDIEndpoint (Handle, &midiHandle); } - outEndpoint = (result == MusicPlayerStatus.Success)? new MidiEndpoint (midiHandle): null; + outEndpoint = (result == MusicPlayerStatus.Success) ? new MidiEndpoint (midiHandle) : null; return result; } #endif diff --git a/src/AudioToolbox/SystemSound.cs b/src/AudioToolbox/SystemSound.cs index 70295f4cb8c0..1e3d4be7f3fa 100644 --- a/src/AudioToolbox/SystemSound.cs +++ b/src/AudioToolbox/SystemSound.cs @@ -402,7 +402,7 @@ public AudioServicesError AddSystemSoundCompletion (Action routine, CFRunLoop? r runLoop.GetHandle (), IntPtr.Zero, // runLoopMode should be enum runLoopMode.GetHandle (), #if NET - &SoundCompletionShared, + &SoundCompletionShared, #else SoundCompletionCallback, #endif diff --git a/src/AudioUnit/AUEnums.cs b/src/AudioUnit/AUEnums.cs index 9eb7acba5f32..54a921159598 100644 --- a/src/AudioUnit/AUEnums.cs +++ b/src/AudioUnit/AUEnums.cs @@ -505,16 +505,16 @@ public enum AudioUnitParameterType // UInt32 in AudioUnitParameterInfo Mixer3DGain = 3, Mixer3DPlaybackRate = 4, #if MONOMAC - Mixer3DReverbBlend = 5, - Mixer3DGlobalReverbGain = 6, - Mixer3DOcclusionAttenuation = 7, - Mixer3DObstructionAttenuation = 8, - Mixer3DMinGain = 9, - Mixer3DMaxGain = 10, - Mixer3DPreAveragePower = 1000, - Mixer3DPrePeakHoldLevel = 2000, - Mixer3DPostAveragePower = 3000, - Mixer3DPostPeakHoldLevel = 4000, + Mixer3DReverbBlend = 5, + Mixer3DGlobalReverbGain = 6, + Mixer3DOcclusionAttenuation = 7, + Mixer3DObstructionAttenuation = 8, + Mixer3DMinGain = 9, + Mixer3DMaxGain = 10, + Mixer3DPreAveragePower = 1000, + Mixer3DPrePeakHoldLevel = 2000, + Mixer3DPostAveragePower = 3000, + Mixer3DPostPeakHoldLevel = 4000, #else Mixer3DEnable = 5, Mixer3DMinGain = 6, @@ -563,8 +563,8 @@ public enum AudioUnitParameterType // UInt32 in AudioUnitParameterInfo // AUTimePitch, AUTimePitch (offline), AUPitch units TimePitchRate = 0, #if MONOMAC - TimePitchPitch = 1, - TimePitchEffectBlend = 2, + TimePitchPitch = 1, + TimePitchEffectBlend = 2, #endif // AUNewTimePitch @@ -969,24 +969,24 @@ public enum AudioUnitSubType : uint { AudioFilePlayer = 0x6166706C, // 'afpl' #if MONOMAC - HALOutput = 0x6168616C, // 'ahal' - DefaultOutput = 0x64656620, // 'def ' - SystemOutput = 0x73797320, // 'sys ' - DLSSynth = 0x646C7320, // 'dls ' - TimePitch = 0x746D7074, // 'tmpt' - GraphicEQ = 0x67726571, // 'greq' - MultiBandCompressor = 0x6D636D70, // 'mcmp' - MatrixReverb = 0x6D726576, // 'mrev' - Pitch = 0x746D7074, // 'tmpt' - AUFilter = 0x66696C74, // 'filt - NetSend = 0x6E736E64, // 'nsnd' - RogerBeep = 0x726F6772, // 'rogr' - StereoMixer = 0x736D7872, // 'smxr' - SphericalHeadPanner = 0x73706872, // 'sphr' - VectorPanner = 0x76626173, // 'vbas' - SoundFieldPanner = 0x616D6269, // 'ambi' - HRTFPanner = 0x68727466, // 'hrtf' - NetReceive = 0x6E726376, // 'nrcv' + HALOutput = 0x6168616C, // 'ahal' + DefaultOutput = 0x64656620, // 'def ' + SystemOutput = 0x73797320, // 'sys ' + DLSSynth = 0x646C7320, // 'dls ' + TimePitch = 0x746D7074, // 'tmpt' + GraphicEQ = 0x67726571, // 'greq' + MultiBandCompressor = 0x6D636D70, // 'mcmp' + MatrixReverb = 0x6D726576, // 'mrev' + Pitch = 0x746D7074, // 'tmpt' + AUFilter = 0x66696C74, // 'filt + NetSend = 0x6E736E64, // 'nsnd' + RogerBeep = 0x726F6772, // 'rogr' + StereoMixer = 0x736D7872, // 'smxr' + SphericalHeadPanner = 0x73706872, // 'sphr' + VectorPanner = 0x76626173, // 'vbas' + SoundFieldPanner = 0x616D6269, // 'ambi' + HRTFPanner = 0x68727466, // 'hrtf' + NetReceive = 0x6E726376, // 'nrcv' #endif } diff --git a/src/AudioUnit/AUGraph.cs b/src/AudioUnit/AUGraph.cs index eaed2bec657b..e0637a5c1a94 100644 --- a/src/AudioUnit/AUGraph.cs +++ b/src/AudioUnit/AUGraph.cs @@ -175,7 +175,7 @@ public AudioUnitStatus RemoveRenderNotify (RenderDelegate callback) #if NET unsafe { if (graphUserCallbacks.Count == 0) - error = (AudioUnitStatus)AUGraphRemoveRenderNotify (Handle, &renderCallback, GCHandle.ToIntPtr (gcHandle)); + error = (AudioUnitStatus) AUGraphRemoveRenderNotify (Handle, &renderCallback, GCHandle.ToIntPtr (gcHandle)); } #else if (graphUserCallbacks.Count == 0) @@ -201,7 +201,7 @@ static CallbackShared static_CallbackShared { #if NET [UnmanagedCallersOnly] - static unsafe AudioUnitStatus renderCallback(IntPtr inRefCon, + static unsafe AudioUnitStatus renderCallback (IntPtr inRefCon, AudioUnitRenderActionFlags* _ioActionFlags, AudioTimeStamp* _inTimeStamp, uint _inBusNumber, @@ -530,14 +530,14 @@ protected override void Dispose (bool disposing) [DllImport (Constants.AudioToolboxLibrary)] #if NET - static unsafe extern int AUGraphAddRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon ); + static unsafe extern int AUGraphAddRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon); #else static extern int AUGraphAddRenderNotify (IntPtr inGraph, CallbackShared inCallback, IntPtr inRefCon); #endif #if NET [DllImport (Constants.AudioToolboxLibrary)] - static unsafe extern int AUGraphRemoveRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon ); + static unsafe extern int AUGraphRemoveRenderNotify (IntPtr inGraph, delegate* unmanaged inCallback, IntPtr inRefCon); #else [DllImport (Constants.AudioToolboxLibrary)] static extern int AUGraphRemoveRenderNotify (IntPtr inGraph, CallbackShared inCallback, IntPtr inRefCon); diff --git a/src/AudioUnit/AudioComponent.cs b/src/AudioUnit/AudioComponent.cs index f5a073cc670c..8cdc6261ab28 100644 --- a/src/AudioUnit/AudioComponent.cs +++ b/src/AudioUnit/AudioComponent.cs @@ -43,7 +43,7 @@ #else using AppKit; #if !COREBUILD -using UIImage=AppKit.NSImage; +using UIImage = AppKit.NSImage; #endif #endif @@ -512,7 +512,8 @@ public double LastActiveTime { [Mac (13,0)] [iOS (16,0)] #endif - public NSDictionary? GetConfigurationInfo (out int resultCode) { + public NSDictionary? GetConfigurationInfo (out int resultCode) + { IntPtr dictPtr; unsafe { resultCode = AudioComponentCopyConfigurationInfo (GetCheckedHandle (), &dictPtr); @@ -561,7 +562,8 @@ unsafe static extern int AudioComponentValidate (IntPtr /* AudioComponent* */ in [iOS (16,0)] [MacCatalyst (16,0)] #endif - public AudioComponentValidationResult Validate (NSDictionary? validationParameters, out int resultCode) { + public AudioComponentValidationResult Validate (NSDictionary? validationParameters, out int resultCode) + { AudioComponentValidationResult result; unsafe { resultCode = AudioComponentValidate (GetCheckedHandle (), validationParameters.GetHandle (), &result); @@ -597,7 +599,7 @@ static void TrampolineAction (IntPtr blockPtr, AudioComponentValidationResult re { var del = BlockLiteral.GetTarget> (blockPtr); if (del is not null) - del (result, Runtime.GetNSObject(dictionary)); + del (result, Runtime.GetNSObject (dictionary)); } #if NET @@ -625,10 +627,11 @@ static void TrampolineAction (IntPtr blockPtr, AudioComponentValidationResult re #endif [BindingImpl (BindingImplOptions.Optimizable)] public void ValidateAsync (NSDictionary? validationParameters, - Action onCompletion, out int resultCode) { + Action onCompletion, out int resultCode) + { if (onCompletion is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (onCompletion)); - + unsafe { #if NET delegate* unmanaged trampoline = &TrampolineAction; @@ -696,7 +699,7 @@ public void ValidateAsync (NSDictionary? validationParameters, #else [NoTV] #endif - public AudioComponentInfo[]? ComponentList { + public AudioComponentInfo []? ComponentList { get { var nameHandle = CFString.CreateNative (Name); try { @@ -707,10 +710,10 @@ public AudioComponentInfo[]? ComponentList { if (nsArray is null) return null; // make things easier for developers since we do not know how to have an implicit conversion from NSObject to AudioComponentInfo - var dics = NSArray.FromArray (nsArray); + var dics = NSArray.FromArray (nsArray); var result = new AudioComponentInfo [dics.Length]; for (var i = 0; i < result.Length; i++) { - result [i] = new AudioComponentInfo (dics[i]); + result [i] = new AudioComponentInfo (dics [i]); } return result; } diff --git a/src/AudioUnit/AudioComponentDescription.cs b/src/AudioUnit/AudioComponentDescription.cs index 48b801c68c16..019ee39f512f 100644 --- a/src/AudioUnit/AudioComponentDescription.cs +++ b/src/AudioUnit/AudioComponentDescription.cs @@ -97,9 +97,9 @@ public enum AudioComponentType : uint { // OSType in AudioComponentDescription public enum AudioTypeOutput { // OSType in AudioComponentDescription Generic = 0x67656e72, // 'genr' #if MONOMAC - HAL=0x6168616c, // 'ahal' - Default=0x64656620, // 'def' - System=0x73797320, // 'sys' + HAL = 0x6168616c, // 'ahal' + Default = 0x64656620, // 'def' + System = 0x73797320, // 'sys' #endif #if NET [SupportedOSPlatform ("macos")] @@ -113,7 +113,7 @@ public enum AudioTypeOutput { // OSType in AudioComponentDescription public enum AudioTypeMusicDevice { // OSType in AudioComponentDescription #if MONOMAC - DlsSynth = 0x646c7320, // 'dls ' + DlsSynth = 0x646c7320, // 'dls ' #endif Sampler = 0x73616d70, // 'samp' @@ -137,7 +137,7 @@ public enum AudioTypeConverter { // OSType in AudioComponentDescription RoundTripAAC = 0x72616163, // 'raac' MultiSplitter = 0x6d73706c, // 'mspl' #if MONOMAC - TimePitch=0x746d7074, // 'tmpt' + TimePitch = 0x746d7074, // 'tmpt' #else #if NET [SupportedOSPlatform ("ios")] @@ -188,13 +188,13 @@ public enum AudioTypeEffect { // OSType in AudioComponentDescription Distortion = 0x64697374, // 'dist' BandPassFilter = 0x62706173, // 'bpas' #if MONOMAC - GraphicEQ=0x67726571, // 'greq' - MultiBandCompressor=0x6d636d70, // 'mcmp' - MatrixReverb=0x6d726576, // 'mrev' - Pitch=0x70697463, // 'pitc' - AUFilter=0x66696c74, // 'filt' - NetSend=0x6e736e64, // 'nsnd' - RogerBeep=0x726f6772, // 'rogr' + GraphicEQ = 0x67726571, // 'greq' + MultiBandCompressor = 0x6d636d70, // 'mcmp' + MatrixReverb = 0x6d726576, // 'mrev' + Pitch = 0x70697463, // 'pitc' + AUFilter = 0x66696c74, // 'filt' + NetSend = 0x6e736e64, // 'nsnd' + RogerBeep = 0x726f6772, // 'rogr' #else #if NET [SupportedOSPlatform ("ios")] @@ -227,7 +227,7 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription Matrix = 0x6d786d78, // 'mxmx' Spacial = 0x3364656d, // Same as Embedded3D #if MONOMAC - Stereo=0x736d7872, // 'smxr' + Stereo = 0x736d7872, // 'smxr' #if NET [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("maccatalyst")] @@ -237,7 +237,7 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription #else [Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'Spacial' instead.")] #endif - ThreeD=0x33646d78, // '3dmx' + ThreeD = 0x33646d78, // '3dmx' #else #if NET [SupportedOSPlatform ("ios")] @@ -252,16 +252,16 @@ public enum AudioTypeMixer { // OSType in AudioComponentDescription public enum AudioTypePanner { // OSType in AudioComponentDescription #if MONOMAC - SphericalHead=0x73706872, // 'sphr' - Vector=0x76626173, // 'vbas' - SoundField=0x616d6269, // 'ambi' - rHRTF=0x68727466, // 'hrtf' + SphericalHead = 0x73706872, // 'sphr' + Vector = 0x76626173, // 'vbas' + SoundField = 0x616d6269, // 'ambi' + rHRTF = 0x68727466, // 'hrtf' #endif } public enum AudioTypeGenerator { // OSType in AudioComponentDescription #if MONOMAC - NetReceive=0x6e726376, // 'nrcv' + NetReceive = 0x6e726376, // 'nrcv' #endif ScheduledSoundPlayer = 0x7373706c, // 'sspl' AudioFilePlayer = 0x6166706c, // 'afpl' diff --git a/src/AudioUnit/AudioUnit.cs b/src/AudioUnit/AudioUnit.cs index 332c6302aa1f..ede6350113d9 100644 --- a/src/AudioUnit/AudioUnit.cs +++ b/src/AudioUnit/AudioUnit.cs @@ -131,14 +131,13 @@ internal AudioUnitException (int k) : base (Lookup (k)) #if NET [StructLayout (LayoutKind.Sequential)] - unsafe struct AURenderCallbackStruct - { + unsafe struct AURenderCallbackStruct { #if COREBUILD public delegate* unmanaged Proc; #else public delegate* unmanaged Proc; #endif - public IntPtr ProcRefCon; + public IntPtr ProcRefCon; } #else [StructLayout (LayoutKind.Sequential)] @@ -701,7 +700,7 @@ public AudioUnitStatus SetRenderCallback (RenderDelegate renderDelegate, AudioUn #if NET [UnmanagedCallersOnly] - static unsafe AudioUnitStatus RenderCallbackImpl (IntPtr clientData, AudioUnitRenderActionFlags* actionFlags, AudioTimeStamp* timeStamp, uint busNumber, uint numberFrames, IntPtr data) + static unsafe AudioUnitStatus RenderCallbackImpl (IntPtr clientData, AudioUnitRenderActionFlags* actionFlags, AudioTimeStamp* timeStamp, uint busNumber, uint numberFrames, IntPtr data) #else [MonoPInvokeCallback (typeof (CallbackShared))] static AudioUnitStatus RenderCallbackImpl (IntPtr clientData, ref AudioUnitRenderActionFlags actionFlags, ref AudioTimeStamp timeStamp, uint busNumber, uint numberFrames, IntPtr data) @@ -1173,7 +1172,7 @@ public AudioObjectPropertyAddress (AudioObjectPropertySelector selector, AudioOb #endif public unsafe class AURenderEventEnumerator : INativeObject #if COREBUILD - {} + { } #else , IEnumerator { AURenderEvent* current; diff --git a/src/AudioUnit/AudioUnitUtils.cs b/src/AudioUnit/AudioUnitUtils.cs index 9303de1a98d0..156b07afcda2 100644 --- a/src/AudioUnit/AudioUnitUtils.cs +++ b/src/AudioUnit/AudioUnitUtils.cs @@ -40,10 +40,10 @@ namespace AudioUnit { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public static class AudioUnitUtils { public const int SampleFractionBits = 24; diff --git a/src/AudioUnit/ExtAudioFile.cs b/src/AudioUnit/ExtAudioFile.cs index 83fab37e4822..06d154f43695 100644 --- a/src/AudioUnit/ExtAudioFile.cs +++ b/src/AudioUnit/ExtAudioFile.cs @@ -70,10 +70,10 @@ public enum ExtAudioFileError // Implictly cast to OSType } #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public class ExtAudioFile : IDisposable { IntPtr _extAudioFile; diff --git a/src/BrowserEngineKit/BEStructs.cs b/src/BrowserEngineKit/BEStructs.cs index b969768b35f7..c6f6a5c1e1dc 100644 --- a/src/BrowserEngineKit/BEStructs.cs +++ b/src/BrowserEngineKit/BEStructs.cs @@ -6,16 +6,15 @@ namespace BrowserEngineKit { #if IOS || MACCATALYST || TVOS - [SupportedOSPlatform ("ios17.4")] - [SupportedOSPlatform ("maccatalyst17.4")] - [SupportedOSPlatform ("tvos17.4")] - [UnsupportedOSPlatform ("macos")] - [StructLayout (LayoutKind.Sequential)] - public struct BEDirectionalTextRange - { - public nint Offset; - public nint Length; - } + [SupportedOSPlatform ("ios17.4")] + [SupportedOSPlatform ("maccatalyst17.4")] + [SupportedOSPlatform ("tvos17.4")] + [UnsupportedOSPlatform ("macos")] + [StructLayout (LayoutKind.Sequential)] + public struct BEDirectionalTextRange { + public nint Offset; + public nint Length; + } #endif // __IOS__ || __MACCATALYST__ } #endif // NET diff --git a/src/Compression/CompressionStreamStruct.cs b/src/Compression/CompressionStreamStruct.cs index 1bc4c1199b06..f50a88783d3d 100644 --- a/src/Compression/CompressionStreamStruct.cs +++ b/src/Compression/CompressionStreamStruct.cs @@ -8,10 +8,10 @@ namespace Compression { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("tvos")] #endif [StructLayout (LayoutKind.Sequential)] struct CompressionStreamStruct { diff --git a/src/Compression/TaskToApm.cs b/src/Compression/TaskToApm.cs index 4207ccc2c802..643eefcf889b 100644 --- a/src/Compression/TaskToApm.cs +++ b/src/Compression/TaskToApm.cs @@ -22,107 +22,99 @@ #nullable enable using System.Diagnostics; -namespace System.Threading.Tasks -{ - /// - /// Provides support for efficiently using Tasks to implement the APM (Begin/End) pattern. - /// - internal static class TaskToApm - { - /// - /// Marshals the Task as an IAsyncResult, using the supplied callback and state - /// to implement the APM pattern. - /// - /// The Task to be marshaled. - /// The callback to be invoked upon completion. - /// The state to be stored in the IAsyncResult. - /// An IAsyncResult to represent the task's asynchronous operation. - public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state) => - new TaskAsyncResult(task, state, callback); +namespace System.Threading.Tasks { + /// + /// Provides support for efficiently using Tasks to implement the APM (Begin/End) pattern. + /// + internal static class TaskToApm { + /// + /// Marshals the Task as an IAsyncResult, using the supplied callback and state + /// to implement the APM pattern. + /// + /// The Task to be marshaled. + /// The callback to be invoked upon completion. + /// The state to be stored in the IAsyncResult. + /// An IAsyncResult to represent the task's asynchronous operation. + public static IAsyncResult Begin (Task task, AsyncCallback? callback, object? state) => + new TaskAsyncResult (task, state, callback); - /// Processes an IAsyncResult returned by Begin. - /// The IAsyncResult to unwrap. - public static void End(IAsyncResult asyncResult) - { - if (asyncResult is TaskAsyncResult twar) - { - twar._task.GetAwaiter().GetResult(); - return; - } + /// Processes an IAsyncResult returned by Begin. + /// The IAsyncResult to unwrap. + public static void End (IAsyncResult asyncResult) + { + if (asyncResult is TaskAsyncResult twar) { + twar._task.GetAwaiter ().GetResult (); + return; + } - throw new ArgumentNullException(); - } + throw new ArgumentNullException (); + } - /// Processes an IAsyncResult returned by Begin. - /// The IAsyncResult to unwrap. - public static TResult End(IAsyncResult asyncResult) - { - if (asyncResult is TaskAsyncResult twar && twar._task is Task task) - { - return task.GetAwaiter().GetResult(); - } - throw new ArgumentNullException(); - } + /// Processes an IAsyncResult returned by Begin. + /// The IAsyncResult to unwrap. + public static TResult End (IAsyncResult asyncResult) + { + if (asyncResult is TaskAsyncResult twar && twar._task is Task task) { + return task.GetAwaiter ().GetResult (); + } + throw new ArgumentNullException (); + } - /// Provides a simple IAsyncResult that wraps a Task. - /// - /// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state, - /// but that's very rare, in particular in a situation where someone cares about allocation, and always - /// using TaskAsyncResult simplifies things and enables additional optimizations. - /// - internal sealed class TaskAsyncResult : IAsyncResult - { - /// The wrapped Task. - internal readonly Task _task; - /// Callback to invoke when the wrapped task completes. - private readonly AsyncCallback? _callback; + /// Provides a simple IAsyncResult that wraps a Task. + /// + /// We could use the Task as the IAsyncResult if the Task's AsyncState is the same as the object state, + /// but that's very rare, in particular in a situation where someone cares about allocation, and always + /// using TaskAsyncResult simplifies things and enables additional optimizations. + /// + internal sealed class TaskAsyncResult : IAsyncResult { + /// The wrapped Task. + internal readonly Task _task; + /// Callback to invoke when the wrapped task completes. + private readonly AsyncCallback? _callback; - /// Initializes the IAsyncResult with the Task to wrap and the associated object state. - /// The Task to wrap. - /// The new AsyncState value. - /// Callback to invoke when the wrapped task completes. - internal TaskAsyncResult(Task task, object? state, AsyncCallback? callback) - { - Debug.Assert(task is not null); - _task = task; - AsyncState = state; + /// Initializes the IAsyncResult with the Task to wrap and the associated object state. + /// The Task to wrap. + /// The new AsyncState value. + /// Callback to invoke when the wrapped task completes. + internal TaskAsyncResult (Task task, object? state, AsyncCallback? callback) + { + Debug.Assert (task is not null); + _task = task; + AsyncState = state; - if (task.IsCompleted) - { - // Synchronous completion. Invoke the callback. No need to store it. - CompletedSynchronously = true; - callback?.Invoke(this); - } - else if (callback is not null) - { - // Asynchronous completion, and we have a callback; schedule it. We use OnCompleted rather than ContinueWith in - // order to avoid running synchronously if the task has already completed by the time we get here but still run - // synchronously as part of the task's completion if the task completes after (the more common case). - _callback = callback; - _task.ConfigureAwait(continueOnCapturedContext: false) - .GetAwaiter() - .OnCompleted(InvokeCallback); // allocates a delegate, but avoids a closure - } - } + if (task.IsCompleted) { + // Synchronous completion. Invoke the callback. No need to store it. + CompletedSynchronously = true; + callback?.Invoke (this); + } else if (callback is not null) { + // Asynchronous completion, and we have a callback; schedule it. We use OnCompleted rather than ContinueWith in + // order to avoid running synchronously if the task has already completed by the time we get here but still run + // synchronously as part of the task's completion if the task completes after (the more common case). + _callback = callback; + _task.ConfigureAwait (continueOnCapturedContext: false) + .GetAwaiter () + .OnCompleted (InvokeCallback); // allocates a delegate, but avoids a closure + } + } - /// Invokes the callback. - private void InvokeCallback() - { - Debug.Assert(!CompletedSynchronously); - Debug.Assert(_callback is not null); - _callback.Invoke(this); - } + /// Invokes the callback. + private void InvokeCallback () + { + Debug.Assert (!CompletedSynchronously); + Debug.Assert (_callback is not null); + _callback.Invoke (this); + } - /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. - public object? AsyncState { get; } - /// Gets a value that indicates whether the asynchronous operation completed synchronously. - /// This is set lazily based on whether the has completed by the time this object is created. - public bool CompletedSynchronously { get; } - /// Gets a value that indicates whether the asynchronous operation has completed. - public bool IsCompleted => _task.IsCompleted; - /// Gets a that is used to wait for an asynchronous operation to complete. - public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle; - } - } + /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. + public object? AsyncState { get; } + /// Gets a value that indicates whether the asynchronous operation completed synchronously. + /// This is set lazily based on whether the has completed by the time this object is created. + public bool CompletedSynchronously { get; } + /// Gets a value that indicates whether the asynchronous operation has completed. + public bool IsCompleted => _task.IsCompleted; + /// Gets a that is used to wait for an asynchronous operation to complete. + public WaitHandle AsyncWaitHandle => ((IAsyncResult) _task).AsyncWaitHandle; + } + } } #endif diff --git a/src/CoreAnimation/CATextLayer.cs b/src/CoreAnimation/CATextLayer.cs index 135d5879a8cb..40a377a5ef8f 100644 --- a/src/CoreAnimation/CATextLayer.cs +++ b/src/CoreAnimation/CATextLayer.cs @@ -106,7 +106,7 @@ public object? WeakFont { set { #if MONOMAC var ns = value as NSFont; - if (ns is not null){ + if (ns is not null) { _Font = ns.Handle; return; } diff --git a/src/CoreAnimation/CATransform3D.cs b/src/CoreAnimation/CATransform3D.cs index 88845428cbc6..a9608e3f0cfe 100644 --- a/src/CoreAnimation/CATransform3D.cs +++ b/src/CoreAnimation/CATransform3D.cs @@ -267,10 +267,10 @@ public override string ToString () { return String.Format ("[{0} {1} {2} {3}; {4} {5} {6} {7}; {8} {9} {10} {11}; {12} {13} {14} {15}]", #if NET - M11, M12, M13, M14, - M21, M22, M23, M24, - M31, M32, M33, M34, - M41, M42, M43, M44); + M11, M12, M13, M14, + M21, M22, M23, M24, + M31, M32, M33, M34, + M41, M42, M43, M44); #else m11, m12, m13, m14, m21, m22, m23, m24, diff --git a/src/CoreBluetooth/CBPeer.cs b/src/CoreBluetooth/CBPeer.cs index 4d08fc531522..418b3b009123 100644 --- a/src/CoreBluetooth/CBPeer.cs +++ b/src/CoreBluetooth/CBPeer.cs @@ -7,7 +7,7 @@ #nullable enable namespace CoreBluetooth { - public partial class CBPeer { + public partial class CBPeer { #if !NET [Deprecated (PlatformName.iOS, 7, 0)] [Obsoleted (PlatformName.iOS, 9, 0)] diff --git a/src/CoreFoundation/CFMessagePort.cs b/src/CoreFoundation/CFMessagePort.cs index 7c71ba32ec86..741bbbfabf46 100644 --- a/src/CoreFoundation/CFMessagePort.cs +++ b/src/CoreFoundation/CFMessagePort.cs @@ -264,12 +264,12 @@ protected override void Dispose (bool disposing) if (context is not null) { #if NET unsafe { - if (context.Retain is not null) - contextProxy.retain = &RetainProxy; - if (context.Release is not null) - contextProxy.release = &ReleaseProxy; - if (context.CopyDescription is not null) - contextProxy.copyDescription = &CopyDescriptionProxy; + if (context.Retain is not null) + contextProxy.retain = &RetainProxy; + if (context.Release is not null) + contextProxy.release = &ReleaseProxy; + if (context.CopyDescription is not null) + contextProxy.copyDescription = &CopyDescriptionProxy; } #else if (context.Retain is not null) diff --git a/src/CoreGraphics/CGAffineTransform.cs b/src/CoreGraphics/CGAffineTransform.cs index 962babf65da9..3d8d4a02017d 100644 --- a/src/CoreGraphics/CGAffineTransform.cs +++ b/src/CoreGraphics/CGAffineTransform.cs @@ -162,11 +162,11 @@ public static CGAffineTransform Multiply (CGAffineTransform a, CGAffineTransform { #if NET return new CGAffineTransform (a.A * b.A + a.B * b.C, - a.A * b.B + a.B * b.D, - a.C * b.A + a.D * b.C, - a.C * b.B + a.D * b.D, - a.Tx * b.A + a.Ty * b.C + b.Tx, - a.Tx * b.B + a.Ty * b.D + b.Ty); + a.A * b.B + a.B * b.D, + a.C * b.A + a.D * b.C, + a.C * b.B + a.D * b.D, + a.Tx * b.A + a.Ty * b.C + b.Tx, + a.Tx * b.B + a.Ty * b.D + b.Ty); #else #pragma warning disable CS0618 // Type or member is obsolete return new CGAffineTransform (a.xx * b.xx + a.yx * b.xy, @@ -388,11 +388,11 @@ public bool IsIdentity { { #if NET return new CGAffineTransform (a.A * b.A + a.B * b.C, - a.A * b.B + a.B * b.D, - a.C * b.A + a.D * b.C, - a.C * b.B + a.D * b.D, - a.Tx * b.A + a.Ty * b.C + b.Tx, - a.Tx * b.B + a.Ty * b.D + b.Ty); + a.A * b.B + a.B * b.D, + a.C * b.A + a.D * b.C, + a.C * b.B + a.D * b.D, + a.Tx * b.A + a.Ty * b.C + b.Tx, + a.Tx * b.B + a.Ty * b.D + b.Ty); #else return new CGAffineTransform (a.xx * b.xx + a.yx * b.xy, a.xx * b.yx + a.yx * b.yy, @@ -426,7 +426,7 @@ public CGPoint TransformPoint (CGPoint point) { #if NET return new CGPoint (A * point.X + C * point.Y + Tx, - B * point.X + D * point.Y + Ty); + B * point.X + D * point.Y + Ty); #else return new CGPoint (xx * point.X + xy * point.Y + x0, yx * point.X + yy * point.Y + y0); diff --git a/src/CoreGraphics/CGColorSpace.cs b/src/CoreGraphics/CGColorSpace.cs index c0eb87cfa104..54163367aa75 100644 --- a/src/CoreGraphics/CGColorSpace.cs +++ b/src/CoreGraphics/CGColorSpace.cs @@ -512,7 +512,7 @@ public byte [] GetColorTable () /* CGColorSpaceRef __nullable */ IntPtr alternate); #if NET - public static CGColorSpace? CreateIccProfile (nfloat[]? range, CGDataProvider profile, CGColorSpace alternate) + public static CGColorSpace? CreateIccProfile (nfloat []? range, CGDataProvider profile, CGColorSpace alternate) #else public static CGColorSpace? CreateICCProfile (nfloat []? range, CGDataProvider profile, CGColorSpace alternate) #endif diff --git a/src/CoreGraphics/CGDisplay.cs b/src/CoreGraphics/CGDisplay.cs index 2c1630bed4c1..95d1519b1073 100644 --- a/src/CoreGraphics/CGDisplay.cs +++ b/src/CoreGraphics/CGDisplay.cs @@ -6,8 +6,7 @@ using ObjCRuntime; using Foundation; -namespace CoreGraphics -{ +namespace CoreGraphics { #if NET [SupportedOSPlatform ("maccatalyst")] @@ -15,8 +14,7 @@ namespace CoreGraphics #else [MacCatalyst (13,1)] #endif - public enum CGCaptureOptions : uint - { + public enum CGCaptureOptions : uint { None = 0, NoFill = 1 << 0 } @@ -27,19 +25,18 @@ public enum CGCaptureOptions : uint #else [MacCatalyst (13,1)] #endif - public static class CGDisplay - { + public static class CGDisplay { #if !COREBUILD [DllImport (Constants.CoreGraphicsLibrary)] static extern uint CGMainDisplayID (); public static int MainDisplayID { get { - return (int)CGMainDisplayID (); + return (int) CGMainDisplayID (); } } - [DllImport (Constants.CoreGraphicsLibrary, EntryPoint="CGDisplayModeGetTypeID")] + [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGDisplayModeGetTypeID")] public static extern nint GetTypeID (); [DllImport (Constants.CoreGraphicsLibrary)] @@ -47,7 +44,7 @@ public static int MainDisplayID { public static CGRect GetBounds (int display) { - return CGDisplayBounds ((uint)display); + return CGDisplayBounds ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -55,7 +52,7 @@ public static CGRect GetBounds (int display) public static nint GetWidth (int display) { - return (nint)CGDisplayPixelsWide ((uint)display); + return (nint) CGDisplayPixelsWide ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -63,7 +60,7 @@ public static nint GetWidth (int display) public static nint GetHeight (int display) { - return (nint)CGDisplayPixelsHigh ((uint)display); + return (nint) CGDisplayPixelsHigh ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -71,7 +68,7 @@ public static nint GetHeight (int display) public static int SetDisplayTransfer (int display, float redMin, float redMax, float redGamma, float greenMin, float greenMax, float greenGamma, float blueMin, float blueMax, float blueGamma) { - return CGSetDisplayTransferByFormula ((uint)display, redMin, redMax, redGamma, greenMin, greenMax, greenGamma, blueMin, blueMax, blueGamma); + return CGSetDisplayTransferByFormula ((uint) display, redMin, redMax, redGamma, greenMin, greenMax, greenGamma, blueMin, blueMax, blueGamma); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -79,7 +76,7 @@ public static int SetDisplayTransfer (int display, float redMin, float redMax, f public static int GetGammaTableCapacity (int display) { - return (int)CGDisplayGammaTableCapacity ((uint)display); + return (int) CGDisplayGammaTableCapacity ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGDisplayRestoreColorSyncSettings")] @@ -102,7 +99,7 @@ public static int GetGammaTableCapacity (int display) [ObsoletedOSPlatform ("maccatalyst13.1")] public static bool IsCaptured (int display) { - return CGDisplayIsCaptured ((uint)display) != 0; + return CGDisplayIsCaptured ((uint) display) != 0; } [DllImport (Constants.CoreGraphicsLibrary)] @@ -110,7 +107,7 @@ public static bool IsCaptured (int display) public static int Capture (int display) { - return CGDisplayCapture ((uint)display); + return CGDisplayCapture ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -118,7 +115,7 @@ public static int Capture (int display) public static int Capture (int display, CGCaptureOptions options) { - return CGDisplayCaptureWithOptions ((uint)display, options); + return CGDisplayCaptureWithOptions ((uint) display, options); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -126,13 +123,13 @@ public static int Capture (int display, CGCaptureOptions options) public static int Release (int display) { - return CGDisplayRelease ((uint)display); + return CGDisplayRelease ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGCaptureAllDisplays")] public static extern int CaptureAllDisplays (); - [DllImport (Constants.CoreGraphicsLibrary, EntryPoint="CGCaptureAllDisplaysWithOptions")] + [DllImport (Constants.CoreGraphicsLibrary, EntryPoint = "CGCaptureAllDisplaysWithOptions")] static extern int CaptureAllDisplays (CGCaptureOptions options); @@ -144,7 +141,7 @@ public static int Release (int display) public static int HideCursor (int display) { - return CGDisplayHideCursor ((uint)display); + return CGDisplayHideCursor ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -152,7 +149,7 @@ public static int HideCursor (int display) public static int ShowCursor (int display) { - return CGDisplayShowCursor ((uint)display); + return CGDisplayShowCursor ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -160,7 +157,7 @@ public static int ShowCursor (int display) public static int MoveCursor (int display, CGPoint point) { - return CGDisplayMoveCursorToPoint ((uint)display, point); + return CGDisplayMoveCursorToPoint ((uint) display, point); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -168,7 +165,7 @@ public static int MoveCursor (int display, CGPoint point) public static int GetOpenGLDisplayMask (int display) { - return (int)CGDisplayIDToOpenGLDisplayMask ((uint)display); + return (int) CGDisplayIDToOpenGLDisplayMask ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -176,7 +173,7 @@ public static int GetOpenGLDisplayMask (int display) public static int GetDisplayID (int displayMask) { - return (int)CGOpenGLDisplayMaskToDisplayID ((uint)displayMask); + return (int) CGOpenGLDisplayMaskToDisplayID ((uint) displayMask); } [DllImport (Constants.CoreGraphicsLibrary)] @@ -184,7 +181,7 @@ public static int GetDisplayID (int displayMask) public static int GetShieldingWindowID (int display) { - return (int)CGShieldingWindowID ((uint)display); + return (int) CGShieldingWindowID ((uint) display); } [DllImport (Constants.CoreGraphicsLibrary)] diff --git a/src/CoreGraphics/CGEvent.cs b/src/CoreGraphics/CGEvent.cs index bdec2da8e97f..e13ead361bdc 100644 --- a/src/CoreGraphics/CGEvent.cs +++ b/src/CoreGraphics/CGEvent.cs @@ -70,10 +70,10 @@ public void Dispose () static IntPtr TapCallback (IntPtr tapProxyEvent, CGEventType eventType, IntPtr eventRef, IntPtr userInfo) { var gch = GCHandle.FromIntPtr (userInfo); - var tapData = (TapData)gch.Target!; + var tapData = (TapData) gch.Target!; return tapData.Callback (tapProxyEvent, eventType, eventRef, tapData.UserInfo); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static unsafe IntPtr CGEventTapCreate (CGEventTapLocation location, CGEventTapPlacement place, CGEventTapOptions options, CGEventMask mask, delegate* unmanaged cback, IntPtr data); #else @@ -126,7 +126,7 @@ static IntPtr TapCallback (IntPtr tapProxyEvent, CGEventType eventType, IntPtr e [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventTapCreateForPSN (IntPtr processSerialNumer, CGEventTapPlacement place, CGEventTapOptions options, CGEventMask mask, CGEventTapCallback cback, IntPtr data); #endif - + #if !XAMCORE_5_0 [Obsolete ("The location parameter is not used. Consider using the overload without the location parameter.", false)] [System.ComponentModel.EditorBrowsable (System.ComponentModel.EditorBrowsableState.Never)] @@ -193,14 +193,14 @@ static IntPtr Create (NSData source) return CGEventCreateFromData (IntPtr.Zero, source.Handle); } - public CGEvent (NSData source) + public CGEvent (NSData source) : base (Create (source), true) { } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventCreate (IntPtr eventSourceHandle); - + public CGEvent (CGEventSource? eventSource) : base (CGEventCreate (eventSource.GetHandle ()), true) { @@ -220,8 +220,8 @@ internal CGEvent (NativeHandle handle, bool owns) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - extern static IntPtr CGEventCreateMouseEvent(IntPtr source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton); - + extern static IntPtr CGEventCreateMouseEvent (IntPtr source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton); + public CGEvent (CGEventSource? source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton) : base (CGEventCreateMouseEvent (source.GetHandle (), mouseType, mouseCursorPosition, mouseButton), true) { @@ -297,8 +297,8 @@ public CGEvent Copy () return null; return new CGEventSource (esh, true); } - - + + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGPoint CGEventGetLocation (IntPtr handle); @@ -325,7 +325,7 @@ public CGPoint UnflippedLocation { // Keep this public, as we want to avoid creating instances of the object // just to peek at the flags - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetFlags")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetFlags")] public extern static CGEventFlags GetFlags (IntPtr eventHandle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] @@ -340,16 +340,16 @@ public CGEventFlags Flags { } } - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetIntegerValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetIntegerValueField")] extern static long GetLong (IntPtr eventHandle, CGEventField eventField); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSetIntegerValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSetIntegerValueField")] extern static void SetLong (IntPtr eventHandle, CGEventField eventField, long value); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventGetDoubleValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventGetDoubleValueField")] extern static double GetDouble (IntPtr eventHandle, CGEventField eventField); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSetDoubleValueField")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSetDoubleValueField")] extern static void SetDouble (IntPtr eventHandle, CGEventField eventField, double value); /// Get the 64-bit integer value of the specified event field. @@ -468,7 +468,7 @@ public long MouseEventSubtype { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventSetSource (IntPtr handle, IntPtr source); - + public void SetEventSource (CGEventSource eventSource) { if (eventSource is null) @@ -477,11 +477,11 @@ public void SetEventSource (CGEventSource eventSource) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - extern static CGEventType CGEventGetType (IntPtr handle); + extern static CGEventType CGEventGetType (IntPtr handle); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSetType (IntPtr handle, CGEventType evtType); - + public CGEventType EventType { get { return CGEventGetType (Handle); @@ -497,7 +497,7 @@ public CGEventType EventType { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSetTimestamp (IntPtr handle, ulong timeStampp); - + #if !NET [Obsolete ("Use 'Timestamp' instead.")] public ulong Timestampe { @@ -547,15 +547,15 @@ public static bool IsTapEnabled (CFMachPort machPort) } [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] - unsafe extern static void CGEventKeyboardGetUnicodeString (IntPtr handle, nuint maxLen, nuint* actualLen, ushort *buffer); + unsafe extern static void CGEventKeyboardGetUnicodeString (IntPtr handle, nuint maxLen, nuint* actualLen, ushort* buffer); public unsafe string GetUnicodeString () { const int bufferLength = 40; - ushort *buffer = stackalloc ushort [bufferLength]; + ushort* buffer = stackalloc ushort [bufferLength]; nuint actual = 0; CGEventKeyboardGetUnicodeString (Handle, bufferLength, &actual, buffer); - return new String ((char *) buffer, 0, (int) actual); + return new String ((char*) buffer, 0, (int) actual); } #if NET @@ -585,10 +585,10 @@ public static void TapPostEven (IntPtr tapProxyEvent, CGEvent evt) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventTapPostEvent (tapProxyEvent, evt.Handle); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventPost (CGEventTapLocation location, IntPtr handle); @@ -596,7 +596,7 @@ public static void Post (CGEvent evt, CGEventTapLocation location) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventPost (location, evt.Handle); } @@ -609,7 +609,7 @@ public static void PostToPSN (CGEvent evt, IntPtr processSerialNumber) { if (evt is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (evt)); - + CGEventPostToPSN (processSerialNumber, evt.Handle); } @@ -637,11 +637,11 @@ public void PostToPid (int pid) { PostToPid (this, pid); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] unsafe extern static int /* CGError = int32_t */ CGGetEventTapList ( uint /* uint32_t */ maxNumberOfTaps, - CGEventTapInformation *tapList, + CGEventTapInformation* tapList, uint* /* uint32_t* */ eventTapCount); public unsafe CGEventTapInformation []? GetEventTapList () @@ -650,7 +650,7 @@ public void PostToPid (int pid) if (CGGetEventTapList (0, null, &count) != 0) return null; var result = new CGEventTapInformation [count]; - fixed (CGEventTapInformation *p = result){ + fixed (CGEventTapInformation* p = result) { if (CGGetEventTapList (count, p, &count) != 0) return null; } @@ -674,7 +674,7 @@ public void PostToPid (int pid) [SupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] #endif - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGRequestListenEventAccess")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGRequestListenEventAccess")] static extern byte CGRequestListenEventAccess (); #if NET diff --git a/src/CoreGraphics/CGEventSource.cs b/src/CoreGraphics/CGEventSource.cs index 44e47bbcb81f..e0e6f0e35fcf 100644 --- a/src/CoreGraphics/CGEventSource.cs +++ b/src/CoreGraphics/CGEventSource.cs @@ -50,7 +50,7 @@ public CGEventSource (NativeHandle handle, bool owns) [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static IntPtr CGEventSourceCreate (CGEventSourceStateID stateID); - + public CGEventSource (CGEventSourceStateID stateID) : base (CGEventSourceCreate (stateID), true) { @@ -62,7 +62,7 @@ public CGEventSource (CGEventSourceStateID stateID) [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetKeyboardType (IntPtr handle, int /* CGEventSourceKeyboardType = uint32_t */ keyboardType); - public int KeyboardType { + public int KeyboardType { get { return CGEventSourceGetKeyboardType (Handle); } @@ -73,7 +73,7 @@ public int KeyboardType { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventSourceStateID CGEventSourceGetSourceStateID (IntPtr handle); - + public CGEventSourceStateID StateID { get { return CGEventSourceGetSourceStateID (Handle); @@ -86,7 +86,7 @@ public CGEventSourceStateID StateID { [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetPixelsPerLine (IntPtr handle, double value); - + public double PixelsPerLine { get { return CGEventSourceGetPixelsPerLine (Handle); @@ -108,13 +108,13 @@ public static bool GetButtonState (CGEventSourceStateID stateID, CGMouseButton b public static bool GetKeyState (CGEventSourceStateID stateID, ushort keycode) => CGEventSourceKeyState (stateID, keycode) != 0; - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceFlagsState")] - public extern static CGEventFlags GetFlagsState (CGEventSourceStateID stateID); + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceFlagsState")] + public extern static CGEventFlags GetFlagsState (CGEventSourceStateID stateID); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceSecondsSinceLastEventType")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceSecondsSinceLastEventType")] public extern static double GetSecondsSinceLastEventType (CGEventSourceStateID stateID, CGEventType eventType); - [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint="CGEventSourceCounterForEventType")] + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary, EntryPoint = "CGEventSourceCounterForEventType")] public extern static uint /* uint32_t */ GetCounterForEventType (CGEventSourceStateID stateID, CGEventType eventType); [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] @@ -140,7 +140,7 @@ public void SetLocalEventsFilterDuringSupressionState (CGEventFilterMask filter, { CGEventSourceSetLocalEventsFilterDuringSuppressionState (Handle, filter, state); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static CGEventFilterMask CGEventSourceGetLocalEventsFilterDuringSuppressionState (IntPtr handle, CGEventSuppressionState state); @@ -148,7 +148,7 @@ public CGEventFilterMask GetLocalEventsFilterDuringSupressionState (CGEventSuppr { return CGEventSourceGetLocalEventsFilterDuringSuppressionState (Handle, state); } - + [DllImport (Constants.ApplicationServicesCoreGraphicsLibrary)] extern static void CGEventSourceSetLocalEventsSuppressionInterval (IntPtr handle, double seconds); @@ -163,7 +163,7 @@ public double LocalEventsSupressionInterval { CGEventSourceSetLocalEventsSuppressionInterval (Handle, value); } } - + } } diff --git a/src/CoreGraphics/CGEventTypes.cs b/src/CoreGraphics/CGEventTypes.cs index 0dfe9dccc45e..2ccc52411296 100644 --- a/src/CoreGraphics/CGEventTypes.cs +++ b/src/CoreGraphics/CGEventTypes.cs @@ -56,7 +56,7 @@ public enum CGEventTapPlacement : uint { [MacCatalyst (13,1)] #endif public enum CGEventTapOptions : uint { - Default, + Default, ListenOnly, } @@ -94,22 +94,22 @@ public enum CGScrollEventUnit : uint { #endif [Flags] public enum CGEventMask : ulong { - Null = 0x00000001, - LeftMouseDown = 0x00000002, - LeftMouseUp = 0x00000004, - RightMouseDown = 0x00000008, - RightMouseUp = 0x00000010, - MouseMoved = 0x00000020, - LeftMouseDragged = 0x00000040, + Null = 0x00000001, + LeftMouseDown = 0x00000002, + LeftMouseUp = 0x00000004, + RightMouseDown = 0x00000008, + RightMouseUp = 0x00000010, + MouseMoved = 0x00000020, + LeftMouseDragged = 0x00000040, RightMouseDragged = 0x00000080, - KeyDown = 0x00000400, - KeyUp = 0x00000800, - FlagsChanged = 0x00001000, - ScrollWheel = 0x00400000, - TabletPointer = 0x00800000, - TabletProximity = 0x01000000, - OtherMouseDown = 0x02000000, - OtherMouseUp = 0x04000000, + KeyDown = 0x00000400, + KeyUp = 0x00000800, + FlagsChanged = 0x00001000, + ScrollWheel = 0x00400000, + TabletPointer = 0x00800000, + TabletProximity = 0x01000000, + OtherMouseDown = 0x02000000, + OtherMouseUp = 0x04000000, OtherMouseDragged = 0x08000000, } @@ -123,14 +123,14 @@ public enum CGEventMask : ulong { [Flags] public enum CGEventFlags : ulong { NonCoalesced = 0x00000100, - AlphaShift = 0x00010000, - Shift = 0x00020000, - Control = 0x00040000, - Alternate = 0x00080000, - Command = 0x00100000, - NumericPad = 0x00200000, - Help = 0x00400000, - SecondaryFn = 0x00800000, + AlphaShift = 0x00010000, + Shift = 0x00020000, + Control = 0x00040000, + Alternate = 0x00080000, + Command = 0x00100000, + NumericPad = 0x00200000, + Help = 0x00400000, + SecondaryFn = 0x00800000, } // CGEventTypes.h:typedef uint32_t CGEventField; @@ -482,7 +482,7 @@ public enum CGEventSuppressionState : int { RemoteMouseDrag, NumberOfEventSuppressionStates, } - + } #endif // MONOMAC diff --git a/src/CoreGraphics/CGImage.cs b/src/CoreGraphics/CGImage.cs index bb995d9cf6b3..6e7f35171f65 100644 --- a/src/CoreGraphics/CGImage.cs +++ b/src/CoreGraphics/CGImage.cs @@ -51,12 +51,12 @@ namespace CoreGraphics { #endif [Flags] public enum CGWindowImageOption : uint { - Default = 0, + Default = 0, BoundsIgnoreFraming = (1 << 0), - ShouldBeOpaque = (1 << 1), - OnlyShadows = (1 << 2), - BestResolution = (1 << 3), - NominalResolution = (1 << 4), + ShouldBeOpaque = (1 << 1), + OnlyShadows = (1 << 2), + BestResolution = (1 << 3), + NominalResolution = (1 << 4), } // uint32_t -> CGWindow.h (OSX SDK only) @@ -68,12 +68,12 @@ public enum CGWindowImageOption : uint { #endif [Flags] public enum CGWindowListOption : uint { - All = 0, - OnScreenOnly = (1 << 0), + All = 0, + OnScreenOnly = (1 << 0), OnScreenAboveWindow = (1 << 1), OnScreenBelowWindow = (1 << 2), - IncludingWindow = (1 << 3), - ExcludeDesktopElements = (1 << 4) + IncludingWindow = (1 << 3), + ExcludeDesktopElements = (1 << 4) } #endif @@ -264,8 +264,8 @@ public CGImage (int width, int height, int bitsPerComponent, int bitsPerPixel, i [Deprecated (PlatformName.MacOSX, 14, 0, message: "Use ScreenCaptureKit instead.")] #endif [DllImport (Constants.CoreGraphicsLibrary)] - static extern IntPtr CGWindowListCreateImage(CGRect screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption); - + static extern IntPtr CGWindowListCreateImage (CGRect screenBounds, CGWindowListOption windowOption, uint windowID, CGWindowImageOption imageOption); + #if NET [SupportedOSPlatform ("maccatalyst")] [ObsoletedOSPlatform ("maccatalyst18.0", "Use ScreenCaptureKit instead.")] diff --git a/src/CoreGraphics/CGPattern.cs b/src/CoreGraphics/CGPattern.cs index 791131f63a40..07a187fd53f3 100644 --- a/src/CoreGraphics/CGPattern.cs +++ b/src/CoreGraphics/CGPattern.cs @@ -102,7 +102,8 @@ unsafe extern static IntPtr CGPatternCreate (/* void* */ IntPtr info, CGRect bou #if NET static CGPatternCallbacks callbacks; - static CGPattern () { + static CGPattern () + { unsafe { callbacks = new CGPatternCallbacks () { version = 0, diff --git a/src/CoreGraphics/CGVector.cs b/src/CoreGraphics/CGVector.cs index 4972a0fcee7b..45ec779f1ca1 100644 --- a/src/CoreGraphics/CGVector.cs +++ b/src/CoreGraphics/CGVector.cs @@ -93,7 +93,7 @@ public override bool Equals (object? other) #endif [DllImport (Constants.UIKitLibrary)] extern static IntPtr NSStringFromCGVector (CGVector vector); - + #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] @@ -113,7 +113,7 @@ public override bool Equals (object? other) #endif [DllImport (Constants.UIKitLibrary)] extern static CGVector CGVectorFromString (IntPtr str); - + #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] diff --git a/src/CoreImage/Enums.cs b/src/CoreImage/Enums.cs index 60941bb22369..4b5ab1a56943 100644 --- a/src/CoreImage/Enums.cs +++ b/src/CoreImage/Enums.cs @@ -53,7 +53,7 @@ public enum CIFormat { #if MONOMAC RGBA16 = 2, [Obsolete ("This value can not be shared across Mac/iOS binaries, future proof with kRGBAf instead.")] - RGBAf = 3, + RGBAf = 3, // Please, do not add values into MonoMac/iOS without adding an explicit value #endif diff --git a/src/CoreLocation/CLLocationManager.cs b/src/CoreLocation/CLLocationManager.cs index e3e39e3ff36a..930268432daa 100644 --- a/src/CoreLocation/CLLocationManager.cs +++ b/src/CoreLocation/CLLocationManager.cs @@ -45,7 +45,7 @@ public partial class CLLocationManager : NSObject { #if IOS public static bool IsMonitoringAvailable (Type t) { - if (SystemVersion.CheckiOS (7,0)) + if (SystemVersion.CheckiOS (7, 0)) return IsMonitoringAvailable (new Class (t)); return false; } diff --git a/src/CoreMidi/MidiBluetoothDriver.cs b/src/CoreMidi/MidiBluetoothDriver.cs index f74cc15aa2b7..3bc6de0f656d 100644 --- a/src/CoreMidi/MidiBluetoothDriver.cs +++ b/src/CoreMidi/MidiBluetoothDriver.cs @@ -23,10 +23,10 @@ namespace CoreMidi { #if NET - [SupportedOSPlatform ("ios16.0")] - [SupportedOSPlatform ("maccatalyst16.0")] - [SupportedOSPlatform ("tvos16.0")] - [SupportedOSPlatform ("macos13.0")] + [SupportedOSPlatform ("ios16.0")] + [SupportedOSPlatform ("maccatalyst16.0")] + [SupportedOSPlatform ("tvos16.0")] + [SupportedOSPlatform ("macos13.0")] #else [iOS (16, 0), Mac (13, 0), TV (16, 0), MacCatalyst (16, 0)] #endif // NET diff --git a/src/CoreServices/FSEvents.cs b/src/CoreServices/FSEvents.cs index aed8dc85b289..e0a55724352d 100644 --- a/src/CoreServices/FSEvents.cs +++ b/src/CoreServices/FSEvents.cs @@ -18,12 +18,11 @@ using CoreFoundation; using Foundation; -namespace CoreServices -{ +namespace CoreServices { // FSEvents.h: typedef UInt32 FSEventStreamCreateFlags; [Flags] public enum FSEventStreamCreateFlags : uint { - None = 0x00000000, + None = 0x00000000, /*UseCFTypes = 0x00000001,*/ NoDefer = 0x00000002, WatchRoot = 0x00000004, @@ -66,7 +65,7 @@ public enum FSEventStreamEventFlags : uint { ItemIsFile = 0x00010000, ItemIsDir = 0x00020000, ItemIsSymlink = 0x00040000, - OwnEvent = 0x00080000, + OwnEvent = 0x00080000, ItemIsHardlink = 0x00100000, ItemIsLastHardlink = 0x00200000, #if NET @@ -78,8 +77,7 @@ public enum FSEventStreamEventFlags : uint { #if NET [SupportedOSPlatform ("macos")] #endif - public struct FSEvent - { + public struct FSEvent { public ulong Id { get; internal set; } public string? Path { get; internal set; } public FSEventStreamEventFlags Flags { get; internal set; } @@ -151,8 +149,7 @@ struct FSEventStreamContext { #if NET [SupportedOSPlatform ("macos")] #endif - public sealed class FSEventStreamEventsArgs : EventArgs - { + public sealed class FSEventStreamEventsArgs : EventArgs { public FSEvent [] Events { get; private set; } internal FSEventStreamEventsArgs (FSEvent [] events) @@ -167,8 +164,7 @@ internal FSEventStreamEventsArgs (FSEvent [] events) #if NET [SupportedOSPlatform ("macos")] #endif - public sealed class FSEventStreamCreateOptions - { + public sealed class FSEventStreamCreateOptions { /// /// The allocator to use to allocate memory for the stream. If null, the default /// allocator will be used. @@ -243,8 +239,7 @@ public FSEventStreamCreateOptions (FSEventStreamCreateFlags flags, TimeSpan late #if NET [SupportedOSPlatform ("macos")] #endif - public class FSEventStream : NativeObject - { + public class FSEventStream : NativeObject { [DllImport (Constants.CoreServicesLibrary)] static extern void FSEventStreamRetain (IntPtr handle); @@ -317,7 +312,7 @@ public FSEventStream (FSEventStreamCreateOptions options) var allocator = options.Allocator.GetHandle (); var sinceWhenId = options.SinceWhenId ?? FSEvent.SinceNowId; var latency = options.Latency.TotalSeconds; - var flags = options.Flags |= (FSEventStreamCreateFlags)0x1 /* UseCFTypes */; + var flags = options.Flags |= (FSEventStreamCreateFlags) 0x1 /* UseCFTypes */; IntPtr handle; unsafe { @@ -403,7 +398,7 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, return; } - var events = new FSEvent[numEvents]; + var events = new FSEvent [numEvents]; for (int i = 0; i < events.Length; i++) { string? path = null; @@ -415,7 +410,7 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, if (eventDataType == CFStringTypeID) { path = CFString.FromHandle (eventDataHandle); } else if (eventDataType == CFDictionaryTypeID) { - path = CFString.FromHandle (CFDictionary.GetValue ( + path = CFString.FromHandle (CFDictionary.GetValue ( eventDataHandle, kFSEventStreamEventExtendedDataPathKey.Handle)); @@ -429,12 +424,11 @@ static void EventsCallback (IntPtr handle, IntPtr userData, nint numEvents, } } - events[i] = new FSEvent - { - Id = (ulong)Marshal.ReadInt64 (eventIds, i * 8), + events [i] = new FSEvent { + Id = (ulong) Marshal.ReadInt64 (eventIds, i * 8), Path = path, - Flags = (FSEventStreamEventFlags)(uint)Marshal.ReadInt32 (eventFlags, i * 4), - FileId = (ulong)fileId, + Flags = (FSEventStreamEventFlags) (uint) Marshal.ReadInt32 (eventFlags, i * 4), + FileId = (ulong) fileId, }; } diff --git a/src/CoreServices/LaunchServices.cs b/src/CoreServices/LaunchServices.cs index 8bc434315164..d19a890f7423 100644 --- a/src/CoreServices/LaunchServices.cs +++ b/src/CoreServices/LaunchServices.cs @@ -30,8 +30,7 @@ using Foundation; using ObjCRuntime; -namespace CoreServices -{ +namespace CoreServices { [Flags] public enum LSRoles/*Mask*/ : uint /* always 32-bit uint */ { @@ -49,8 +48,7 @@ public enum LSAcceptanceFlags : uint /* always 32-bit uint */ AllowLoginUI = 2 } - public enum LSResult - { + public enum LSResult { Success = 0, #if NET [SupportedOSPlatform ("macos13.0")] @@ -89,9 +87,8 @@ public enum LSResult #if NET [SupportedOSPlatform ("macos")] #endif - public static class LaunchServices - { -#region Locating an Application + public static class LaunchServices { + #region Locating an Application #if NET [SupportedOSPlatform ("macos")] @@ -221,19 +218,19 @@ public static NSUrl [] GetApplicationUrlsForBundleIdentifier (string bundleIdent ); } -#endregion + #endregion -#region Opening Items + #region Opening Items [DllImport (Constants.CoreServicesLibrary)] - unsafe static extern LSResult LSOpenCFURLRef (IntPtr inUrl, void **outLaunchedUrl); + unsafe static extern LSResult LSOpenCFURLRef (IntPtr inUrl, void** outLaunchedUrl); public unsafe static LSResult Open (NSUrl url) { if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - return LSOpenCFURLRef (url.Handle, (void **)0); + return LSOpenCFURLRef (url.Handle, (void**) 0); } public unsafe static LSResult Open (NSUrl url, out NSUrl? launchedUrl) @@ -241,15 +238,15 @@ public unsafe static LSResult Open (NSUrl url, out NSUrl? launchedUrl) if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - void *launchedUrlHandle; + void* launchedUrlHandle; var result = LSOpenCFURLRef (url.Handle, &launchedUrlHandle); launchedUrl = Runtime.GetNSObject (new IntPtr (launchedUrlHandle)); return result; } -#endregion + #endregion -#region Registering an Application + #region Registering an Application [DllImport (Constants.CoreServicesLibrary)] static extern LSResult LSRegisterURL (IntPtr inUrl, byte inUpdate); @@ -259,12 +256,12 @@ public static LSResult Register (NSUrl url, bool update) if (url is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (url)); - return LSRegisterURL (url.Handle, (byte)(update ? 1 : 0)); + return LSRegisterURL (url.Handle, (byte) (update ? 1 : 0)); } -#endregion + #endregion -#region Working with Role Handlers + #region Working with Role Handlers #if NET [SupportedOSPlatform ("macos")] @@ -281,7 +278,7 @@ public static LSResult Register (NSUrl url, bool update) #else [Deprecated (PlatformName.MacOSX, 14, 0)] #endif - public static string?[]? GetAllRoleHandlersForContentType (string contentType, LSRoles roles = LSRoles.All) + public static string? []? GetAllRoleHandlersForContentType (string contentType, LSRoles roles = LSRoles.All) { if (contentType is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (contentType)); @@ -311,7 +308,7 @@ public static string GetDefaultRoleHandlerForContentType (string contentType, LS if (contentType is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (contentType)); - return (string)Runtime.GetNSObject ( + return (string) Runtime.GetNSObject ( LSCopyDefaultRoleHandlerForContentType (new NSString (contentType).Handle, roles) ); } @@ -363,7 +360,7 @@ public static LSResult SetDefaultRoleHandlerForContentType (string contentType, #else [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'GetApplicationUrlsForUrl' instead.")] #endif - public static string?[]? GetAllHandlersForUrlScheme (string urlScheme) + public static string? []? GetAllHandlersForUrlScheme (string urlScheme) { if (urlScheme is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (urlScheme)); @@ -393,7 +390,7 @@ public static string GetDefaultHandlerForUrlScheme (string urlScheme) if (urlScheme is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (urlScheme)); - return (string)Runtime.GetNSObject ( + return (string) Runtime.GetNSObject ( LSCopyDefaultHandlerForURLScheme (new NSString (urlScheme).Handle) ); } @@ -426,7 +423,7 @@ public static LSResult SetDefaultHandlerForUrlScheme (string urlScheme, string h ); } -#endregion + #endregion } } diff --git a/src/CoreSpotlight/CSSearchableIndex.cs b/src/CoreSpotlight/CSSearchableIndex.cs index 3886817384de..0b0a04696d38 100644 --- a/src/CoreSpotlight/CSSearchableIndex.cs +++ b/src/CoreSpotlight/CSSearchableIndex.cs @@ -21,7 +21,7 @@ public partial class CSSearchableIndex { // Strongly typed version of initWithName:protectionClass: public CSSearchableIndex (string name, CSFileProtection protectionOption = CSFileProtection.None) : this (name, Translate (protectionOption)) - {} + { } static NSString? Translate (CSFileProtection protectionOption) { diff --git a/src/CoreSpotlight/CSSearchableItemAttributeSet.cs b/src/CoreSpotlight/CSSearchableItemAttributeSet.cs index 44fc02577858..5efd455a0e95 100644 --- a/src/CoreSpotlight/CSSearchableItemAttributeSet.cs +++ b/src/CoreSpotlight/CSSearchableItemAttributeSet.cs @@ -28,10 +28,11 @@ public INSSecureCoding? this [CSCustomAttributeKey key] { [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] #endif - public bool? IsUserCreated { + public bool? IsUserCreated { get { return _IsUserCreated?.BoolValue; - } set { + } + set { _IsUserCreated = value.HasValue ? new NSNumber (value.Value) : null; } } @@ -45,7 +46,8 @@ public bool? IsUserCreated { public bool? IsUserOwned { get { return _IsUserOwned?.BoolValue; - } set { + } + set { _IsUserOwned = value.HasValue ? new NSNumber (value.Value) : null; } } @@ -56,10 +58,11 @@ public bool? IsUserOwned { [SupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] #endif - public bool? IsUserCurated { + public bool? IsUserCurated { get { return _IsUserCurated?.BoolValue; - } set { + } + set { _IsUserCurated = value.HasValue ? new NSNumber (value.Value) : null; } } diff --git a/src/CoreText/CTFontCollection.cs b/src/CoreText/CTFontCollection.cs index 89154017f8f4..c3e5dfec1c72 100644 --- a/src/CoreText/CTFontCollection.cs +++ b/src/CoreText/CTFontCollection.cs @@ -191,7 +191,7 @@ public CTFontDescriptor [] GetMatchingFontDescriptors (CTFontCollectionOptions? #if NET [DllImport (Constants.CoreTextLibrary)] static unsafe extern IntPtr CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback ( - IntPtr collection, delegate* unmanaged sortCallback, + IntPtr collection, delegate* unmanaged sortCallback, IntPtr refCon); #else [DllImport (Constants.CoreTextLibrary)] diff --git a/src/CoreText/CTFontManager.cs b/src/CoreText/CTFontManager.cs index e9150b2970d3..7fc1b47f49db 100644 --- a/src/CoreText/CTFontManager.cs +++ b/src/CoreText/CTFontManager.cs @@ -666,7 +666,7 @@ public unsafe static void UnregisterFontDescriptors (CTFontDescriptor [] fontDes [NoTV] [NoMac] #endif - public static CTFontDescriptor[]? GetRegisteredFontDescriptors (CTFontManagerScope scope, bool enabled) + public static CTFontDescriptor []? GetRegisteredFontDescriptors (CTFontManagerScope scope, bool enabled) { var p = CTFontManagerCopyRegisteredFontDescriptors (scope, enabled.AsByte ()); // Copy/Create rule - we must release the CFArrayRef @@ -746,7 +746,7 @@ public unsafe static void UnregisterFontDescriptors (CTFontDescriptor [] fontDes [iOS (13,0)] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public unsafe static void RegisterFonts (string[] assetNames, CFBundle bundle, CTFontManagerScope scope, bool enabled, CTFontRegistrationHandler registrationHandler) + public unsafe static void RegisterFonts (string [] assetNames, CFBundle bundle, CTFontManagerScope scope, bool enabled, CTFontRegistrationHandler registrationHandler) { using (var arr = EnsureNonNullArray (assetNames, nameof (assetNames))) { if (registrationHandler is null) { @@ -774,7 +774,7 @@ public unsafe static void RegisterFonts (string[] assetNames, CFBundle bundle, C [NoMac] [iOS (13,0)] #endif - public delegate void CTFontManagerRequestFontsHandler (CTFontDescriptor[] unresolvedFontDescriptors); + public delegate void CTFontManagerRequestFontsHandler (CTFontDescriptor [] unresolvedFontDescriptors); #if NET [SupportedOSPlatform ("ios13.0")] @@ -817,7 +817,7 @@ static unsafe void TrampolineRequestFonts (IntPtr block, /* CFArray */ IntPtr fo [iOS (13,0)] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public static void RequestFonts (CTFontDescriptor[] fontDescriptors, CTFontManagerRequestFontsHandler completionHandler) + public static void RequestFonts (CTFontDescriptor [] fontDescriptors, CTFontManagerRequestFontsHandler completionHandler) { if (completionHandler is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (completionHandler)); diff --git a/src/CoreVideo/CVDisplayLink.cs b/src/CoreVideo/CVDisplayLink.cs index 587461ba75eb..f2015af03d77 100644 --- a/src/CoreVideo/CVDisplayLink.cs +++ b/src/CoreVideo/CVDisplayLink.cs @@ -42,7 +42,7 @@ namespace CoreVideo { public class CVDisplayLink : NativeObject { GCHandle callbackHandle; - [Preserve (Conditional=true)] + [Preserve (Conditional = true)] internal CVDisplayLink (NativeHandle handle, bool owns) : base (handle, owns) { @@ -93,7 +93,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] - public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds, out CVReturn error) + public static CVDisplayLink? CreateFromDisplayIds (uint [] displayIds, out CVReturn error) { if (displayIds is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (displayIds)); @@ -115,7 +115,7 @@ internal CVDisplayLink (NativeHandle handle, bool owns) [UnsupportedOSPlatform ("ios")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("maccatalyst")] - public static CVDisplayLink? CreateFromDisplayIds (uint[] displayIds) + public static CVDisplayLink? CreateFromDisplayIds (uint [] displayIds) => CreateFromDisplayIds (displayIds, out var _); [SupportedOSPlatform ("macos")] @@ -153,12 +153,12 @@ internal CVDisplayLink (NativeHandle handle, bool owns) [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRetain (IntPtr handle); - + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] extern static void CVDisplayLinkRelease (IntPtr handle); - + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] protected internal override void Retain () @@ -176,7 +176,7 @@ protected internal override void Release () protected override void Dispose (bool disposing) { if (callbackHandle.IsAllocated) { - callbackHandle.Free(); + callbackHandle.Free (); } base.Dispose (disposing); @@ -209,7 +209,7 @@ static IntPtr Create () public CVDisplayLink () : base (Create (), true) { - } + } [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -221,8 +221,8 @@ public CVDisplayLink () public CVReturn SetCurrentDisplay (int displayId) { return CVDisplayLinkSetCurrentCGDisplay (Handle, displayId); - } - + } + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] @@ -233,7 +233,7 @@ public CVReturn SetCurrentDisplay (int displayId) public CVReturn SetCurrentDisplay (CGLContext cglContext, CGLPixelFormat cglPixelFormat) { return CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext (Handle, cglContext.Handle, cglPixelFormat.Handle); - } + } [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -246,7 +246,7 @@ public int GetCurrentDisplay () { return CVDisplayLinkGetCurrentCGDisplay (Handle); } - + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] @@ -257,8 +257,8 @@ public int GetCurrentDisplay () public CVReturn Start () { return CVDisplayLinkStart (Handle); - } - + } + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] @@ -269,8 +269,8 @@ public CVReturn Start () public CVReturn Stop () { return CVDisplayLinkStop (Handle); - } - + } + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] @@ -309,7 +309,7 @@ public double ActualOutputVideoRefreshPeriod { return CVDisplayLinkGetActualOutputVideoRefreshPeriod (Handle); } } - + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] @@ -322,7 +322,7 @@ public bool IsRunning { return CVDisplayLinkIsRunning (Handle) != 0; } } - + [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] @@ -335,21 +335,21 @@ public CVReturn GetCurrentTime (out CVTimeStamp outTime) CVReturn ret; outTime = default; unsafe { - ret = CVDisplayLinkGetCurrentTime (this.Handle, (CVTimeStamp *) Unsafe.AsPointer (ref outTime)); + ret = CVDisplayLinkGetCurrentTime (this.Handle, (CVTimeStamp*) Unsafe.AsPointer (ref outTime)); } - + return ret; } - - public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut); - delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext); - + + public delegate CVReturn DisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut); + delegate CVReturn CVDisplayLinkOutputCallback (IntPtr displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut, IntPtr displayLinkContext); + [UnmanagedCallersOnly] static unsafe CVReturn OutputCallback (IntPtr displayLink, CVTimeStamp* inNow, CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, IntPtr displayLinkContext) { GCHandle callbackHandle = GCHandle.FromIntPtr (displayLinkContext); DisplayLinkOutputCallback func = (DisplayLinkOutputCallback) callbackHandle.Target!; - CVDisplayLink delegateDisplayLink = new CVDisplayLink(displayLink, false); + CVDisplayLink delegateDisplayLink = new CVDisplayLink (displayLink, false); return func (delegateDisplayLink, ref System.Runtime.CompilerServices.Unsafe.AsRef (inNow), ref System.Runtime.CompilerServices.Unsafe.AsRef (inOutputTime), @@ -359,7 +359,7 @@ ref System.Runtime.CompilerServices.Unsafe.AsRef (inOutputTime), [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] [DllImport (Constants.CoreVideoLibrary)] - extern static unsafe CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, delegate* unmanaged function, IntPtr userInfo); + extern static unsafe CVReturn CVDisplayLinkSetOutputCallback (IntPtr displayLink, delegate* unmanaged function, IntPtr userInfo); [ObsoletedOSPlatform ("macos15.0", "Use 'NSView.GetDisplayLink', 'NSWindow.GetDisplayLink' or 'NSScreen.GetDisplayLink' instead.")] [SupportedOSPlatform ("macos")] @@ -404,7 +404,7 @@ public static nuint GetTypeId () public bool TryTranslateTime (CVTimeStamp inTime, ref CVTimeStamp outTime) { unsafe { - return CVDisplayLinkTranslateTime (this.Handle, inTime, (CVTimeStamp *) Unsafe.AsPointer (ref outTime)) == 0; + return CVDisplayLinkTranslateTime (this.Handle, inTime, (CVTimeStamp*) Unsafe.AsPointer (ref outTime)) == 0; } } } diff --git a/src/CoreVideo/CVImageBuffer.cs b/src/CoreVideo/CVImageBuffer.cs index bf4ed0fa31f2..c5a905d596fc 100644 --- a/src/CoreVideo/CVImageBuffer.cs +++ b/src/CoreVideo/CVImageBuffer.cs @@ -89,7 +89,7 @@ public bool IsFlipped { #if MONOMAC [DllImport (Constants.CoreVideoLibrary)] extern static /* CGColorSpaceRef */ IntPtr CVImageBufferGetColorSpace (/* CVImageBufferRef */ IntPtr imageBuffer); - + [UnsupportedOSPlatform ("maccatalyst")] [UnsupportedOSPlatform ("tvos")] [UnsupportedOSPlatform ("ios")] diff --git a/src/Darwin/KernelNotification.cs b/src/Darwin/KernelNotification.cs index 74234fedb2c9..96ebcc87bc17 100644 --- a/src/Darwin/KernelNotification.cs +++ b/src/Darwin/KernelNotification.cs @@ -57,24 +57,24 @@ public struct KernelEvent { [Flags] public enum EventFlags : ushort { - Add = 0x0001, - Delete = 0x0002, - Enable = 0x0004, - Disable = 0x0008, - OneShot = 0x0010, - Clear = 0x0020, - Receipt = 0x0040, - Dispatch = 0x0080, - - Flag0 = 0x1000, - Flag1 = 0x2000, - SystemFlags = unchecked (0xf000), - + Add = 0x0001, + Delete = 0x0002, + Enable = 0x0004, + Disable = 0x0008, + OneShot = 0x0010, + Clear = 0x0020, + Receipt = 0x0040, + Dispatch = 0x0080, + + Flag0 = 0x1000, + Flag1 = 0x2000, + SystemFlags = unchecked(0xf000), + // Return values. - EOF = 0x8000, - Error = 0x4000, + EOF = 0x8000, + Error = 0x4000, } - + public enum EventFilter : short { Read = -1, Write = -2, @@ -88,60 +88,60 @@ public enum EventFilter : short { User = -10, VM = -11 } - + [Flags] public enum FilterFlags : uint { - ReadPoll = EventFlags.Flag0, - ReadOutOfBand = EventFlags.Flag1, - ReadLowWaterMark = 0x00000001, + ReadPoll = EventFlags.Flag0, + ReadOutOfBand = EventFlags.Flag1, + ReadLowWaterMark = 0x00000001, WriteLowWaterMark = ReadLowWaterMark, - NoteTrigger = 0x01000000, - NoteFFNop = 0x00000000, - NoteFFAnd = 0x40000000, - NoteFFOr = 0x80000000, - NoteFFCopy = 0xc0000000, - NoteFFCtrlMask = 0xc0000000, - NoteFFlagsMask = 0x00ffffff, - - VNodeDelete = 0x00000001, - VNodeWrite = 0x00000002, - VNodeExtend = 0x00000004, - VNodeAttrib = 0x00000008, - VNodeLink = 0x00000010, - VNodeRename = 0x00000020, - VNodeRevoke = 0x00000040, - VNodeNone = 0x00000080, - - ProcExit = 0x80000000, - ProcFork = 0x40000000, - ProcExec = 0x20000000, - ProcReap = 0x10000000, - ProcSignal = 0x08000000, - ProcExitStatus = 0x04000000, - ProcResourceEnd = 0x02000000, + NoteTrigger = 0x01000000, + NoteFFNop = 0x00000000, + NoteFFAnd = 0x40000000, + NoteFFOr = 0x80000000, + NoteFFCopy = 0xc0000000, + NoteFFCtrlMask = 0xc0000000, + NoteFFlagsMask = 0x00ffffff, + + VNodeDelete = 0x00000001, + VNodeWrite = 0x00000002, + VNodeExtend = 0x00000004, + VNodeAttrib = 0x00000008, + VNodeLink = 0x00000010, + VNodeRename = 0x00000020, + VNodeRevoke = 0x00000040, + VNodeNone = 0x00000080, + + ProcExit = 0x80000000, + ProcFork = 0x40000000, + ProcExec = 0x20000000, + ProcReap = 0x10000000, + ProcSignal = 0x08000000, + ProcExitStatus = 0x04000000, + ProcResourceEnd = 0x02000000, // iOS only - ProcAppactive = 0x00800000, + ProcAppactive = 0x00800000, ProcAppBackground = 0x00400000, - ProcAppNonUI = 0x00200000, - ProcAppInactive = 0x00100000, - ProcAppAllStates = 0x00f00000, + ProcAppNonUI = 0x00200000, + ProcAppInactive = 0x00100000, + ProcAppAllStates = 0x00f00000, // Masks - ProcPDataMask = 0x000fffff, - ProcControlMask = 0xfff00000, + ProcPDataMask = 0x000fffff, + ProcControlMask = 0xfff00000, - VMPressure = 0x80000000, + VMPressure = 0x80000000, VMPressureTerminate = 0x40000000, VMPressureSuddenTerminate = 0x20000000, - VMError = 0x10000000, + VMError = 0x10000000, - TimerSeconds = 0x00000001, - TimerMicroSeconds = 0x00000002, - TimerNanoSeconds = 0x00000004, - TimerAbsolute = 0x00000008, + TimerSeconds = 0x00000001, + TimerMicroSeconds = 0x00000002, + TimerNanoSeconds = 0x00000004, + TimerAbsolute = 0x00000008, } public class KernelQueue : IDisposable, INativeObject { @@ -167,19 +167,19 @@ public void Dispose () { Dispose (false); } - + protected virtual void Dispose (bool disposing) { - if (handle != -1){ + if (handle != -1) { DispatchSource.VnodeMonitor.close (handle); handle = -1; } } [DllImport (Constants.SystemLibrary)] - unsafe extern static int /* int */ kevent (int kq, KernelEvent *changeList, int /* int */ nChanges, KernelEvent *eventList, int /* int */ nEvents, TimeSpec* timeout); + unsafe extern static int /* int */ kevent (int kq, KernelEvent* changeList, int /* int */ nChanges, KernelEvent* eventList, int /* int */ nEvents, TimeSpec* timeout); - public int KEvent (KernelEvent[] changeList, KernelEvent[] eventList, TimeSpan? timeout = null) + public int KEvent (KernelEvent [] changeList, KernelEvent [] eventList, TimeSpan? timeout = null) { if (changeList is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (changeList)); @@ -196,7 +196,7 @@ public int KEvent (KernelEvent[] changeList, KernelEvent[] eventList, TimeSpan? return KEvent (changeList, changeList.Length, eventList, eventList.Length, ToTimespec (timeout)); } - public unsafe int KEvent (KernelEvent[] changeList, int nChanges, KernelEvent[] eventList, int nEvents, TimeSpec? timeout = null) + public unsafe int KEvent (KernelEvent [] changeList, int nChanges, KernelEvent [] eventList, int nEvents, TimeSpec? timeout = null) { if (changeList is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (changeList)); @@ -217,15 +217,15 @@ public unsafe int KEvent (KernelEvent[] changeList, int nChanges, KernelEvent[] throw new ArgumentOutOfRangeException ("nEvents is larger than the number of elements in eventList", nameof (nEvents)); unsafe { - fixed (KernelEvent *cp = changeList) - fixed (KernelEvent *ep = eventList) { - if (timeout is null) { - return kevent (handle, cp, nChanges, ep, nEvents, null); - } else { - TimeSpec ts = timeout.Value; - return kevent (handle, cp, nChanges, ep, nEvents, &ts); - } + fixed (KernelEvent* cp = changeList) + fixed (KernelEvent* ep = eventList) { + if (timeout is null) { + return kevent (handle, cp, nChanges, ep, nEvents, null); + } else { + TimeSpec ts = timeout.Value; + return kevent (handle, cp, nChanges, ep, nEvents, &ts); } + } } } @@ -240,7 +240,7 @@ public unsafe int KEvent (KernelEvent[] changeList, int nChanges, KernelEvent[] return rv; } -// Don't worry about nullability for !NET + // Don't worry about nullability for !NET #nullable disable #if !NET [Obsolete ("Use any of the overloads that return an int to get how many events were returned from kevent.")] @@ -295,10 +295,10 @@ public bool KEvent (KernelEvent [] changeList, KernelEvent [] eventList) #endif { unsafe { - fixed (KernelEvent *cp = changeList) - fixed (KernelEvent *ep = eventList) + fixed (KernelEvent* cp = changeList) + fixed (KernelEvent* ep = eventList) #if NET - return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null); + return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null); #else return kevent (handle, cp, changeList?.Length ?? 0, ep, eventList?.Length ?? 0, null) != -1; #endif diff --git a/src/Darwin/SystemLog.cs b/src/Darwin/SystemLog.cs index 02dcc77443e1..b470534c75d7 100644 --- a/src/Darwin/SystemLog.cs +++ b/src/Darwin/SystemLog.cs @@ -43,7 +43,7 @@ namespace Darwin { public class SystemLog : DisposableObject { static SystemLog? _default; - + public static SystemLog Default { get { if (_default is null) @@ -51,7 +51,7 @@ public static SystemLog Default { return _default!; } } - + [Flags] public enum Option { Stderr, @@ -65,10 +65,10 @@ protected override void Dispose (bool disposing) asl_close (Handle); base.Dispose (disposing); } - + [DllImport (Constants.SystemLibrary)] extern static void asl_close (IntPtr handle); - + [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_open (IntPtr ident, IntPtr facility, Option /* uint32_t */ options); @@ -89,7 +89,7 @@ static IntPtr asl_open (string ident, string facility, Option options) : base (handle, owns) { } - + public SystemLog (string ident, string facility, Option options = 0) : base ( asl_open ( @@ -110,7 +110,7 @@ static IntPtr asl_open_from_file (int /* int */ fd, string ident, string facilit using var facilityStr = new TransientString (facility); return asl_open_from_file (fd, identStr, facilityStr); } - + public SystemLog (int fileDescriptor, string ident, string facility) : base ( asl_open_from_file ( @@ -127,7 +127,7 @@ public SystemLog (int fileDescriptor, string ident, string facility) [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_remove_log_file (IntPtr handle, int /* int */ fd); - + public void AddLogFile (int descriptor) { asl_add_log_file (Handle, descriptor); @@ -159,24 +159,24 @@ public int Log (string text) { if (text is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (text)); - + return asl_log (Handle, IntPtr.Zero, text); } - + [DllImport (Constants.SystemLibrary)] extern static int asl_send (IntPtr handle, IntPtr msgHandle); - + public int Log (Message msg) { if (msg is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (msg)); - + return asl_send (Handle, msg.Handle); } [DllImport (Constants.SystemLibrary)] extern static int asl_set_filter (IntPtr handle, int /* int */ f); - + public int SetFilter (int level) { return asl_set_filter (Handle, level); @@ -187,17 +187,17 @@ public int SetFilter (int level) [DllImport (Constants.SystemLibrary)] extern static IntPtr aslresponse_next (IntPtr handle); - + [DllImport (Constants.SystemLibrary)] extern static void aslresponse_free (IntPtr handle); - + public IEnumerable Search (Message msg) { if (msg is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (msg)); var search = asl_search (Handle, msg.Handle); IntPtr mh; - + while ((mh = aslresponse_next (search)) != IntPtr.Zero) yield return new Message (mh, true); @@ -218,7 +218,7 @@ public enum Op { Suffix = 0x40, Substring = 0x60, Numeric = 0x80, - Regex = 0x100, + Regex = 0x100, Equal = 1, Greater = 2, GreaterEqual = 3, @@ -233,7 +233,7 @@ internal Message (NativeHandle handle, bool owns) : base (handle, owns) { } - + public Message (Kind kind) : base (asl_new (kind), true) { @@ -254,7 +254,7 @@ protected override void Dispose (bool disposing) [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_get (IntPtr handle, IntPtr key); - + [DllImport (Constants.SystemLibrary)] extern static int asl_set (IntPtr handle, IntPtr key, IntPtr value); @@ -276,7 +276,7 @@ public string this [string key] { [DllImport (Constants.SystemLibrary)] extern static int asl_unset (IntPtr handle, IntPtr key); - + public void Remove (string key) { if (key is null) @@ -284,7 +284,7 @@ public void Remove (string key) using var keyStr = new TransientString (key); asl_unset (Handle, keyStr); } - + #if NET [DllImport (Constants.SystemLibrary)] extern static IntPtr asl_key (IntPtr handle, int /* uint32_t */ key); @@ -292,8 +292,8 @@ public void Remove (string key) [DllImport (Constants.SystemLibrary)] extern static string asl_key (IntPtr handle, int /* uint32_t */ key); #endif - - public string this [int key]{ + + public string this [int key] { get { #if NET return Marshal.PtrToStringAuto (asl_key (Handle, key))!; @@ -312,37 +312,37 @@ public string Host { get { return this ["Host"]; } set { this ["Host"] = value; } } - + public string Sender { get { return this ["Sender"]; } set { this ["Sender"] = value; } } - + public string Facility { get { return this ["Facility"]; } set { this ["Facility"] = value; } } - + public string PID { get { return this ["PID"]; } set { this ["PID"] = value; } } - + public string UID { get { return this ["UID"]; } set { this ["UID"] = value; } } - + public string GID { get { return this ["GID"]; } set { this ["GID"] = value; } } - + public string Level { get { return this ["Level"]; } set { this ["Level"] = value; } } - + public string Msg { get { return this ["Message"]; } set { this ["Message"] = value; } @@ -350,7 +350,7 @@ public string Msg { [DllImport (Constants.SystemLibrary)] extern static int asl_set_query (IntPtr handle, IntPtr key, IntPtr value, int /* uint32_t */ op); - + public bool SetQuery (string key, Op op, string value) { using var keyStr = new TransientString (key); diff --git a/src/FileProvider/Structs.cs b/src/FileProvider/Structs.cs index 8fd2a4fa59f2..4a4440fe3f72 100644 --- a/src/FileProvider/Structs.cs +++ b/src/FileProvider/Structs.cs @@ -23,8 +23,7 @@ namespace FileProvider { [NoMacCatalyst] #endif [StructLayout (LayoutKind.Sequential)] - public struct NSFileProviderTypeAndCreator - { + public struct NSFileProviderTypeAndCreator { public uint Type; public uint Creator; @@ -32,7 +31,7 @@ public struct NSFileProviderTypeAndCreator public string GetTypeAsFourCC () => Runtime.ToFourCCString (Type); - public string GetCreatorAsFourCC() + public string GetCreatorAsFourCC () => Runtime.ToFourCCString (Creator); #endif } diff --git a/src/Foundation/Enum.cs b/src/Foundation/Enum.cs index 1132c4afd283..71d41f2d3fea 100644 --- a/src/Foundation/Enum.cs +++ b/src/Foundation/Enum.cs @@ -78,7 +78,9 @@ public enum NSUrlCredentialPersistence : ulong { #if MONOMAC /// The bundle's architecture. - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] public enum NSBundleExecutableArchitecture { I386 = 0x00000007, PPC = 0x00000012, diff --git a/src/Foundation/NSAppleEventDescriptor.cs b/src/Foundation/NSAppleEventDescriptor.cs index a4d5a8777b23..1943142b53b7 100644 --- a/src/Foundation/NSAppleEventDescriptor.cs +++ b/src/Foundation/NSAppleEventDescriptor.cs @@ -9,15 +9,13 @@ using AppKit; -namespace Foundation -{ +namespace Foundation { public enum NSAppleEventDescriptorType { Record, List, } - public partial class NSAppleEventDescriptor - { + public partial class NSAppleEventDescriptor { public NSAppleEventDescriptor (NSAppleEventDescriptorType type) { switch (type) { diff --git a/src/Foundation/NSAttributedString.cs b/src/Foundation/NSAttributedString.cs index f6a40823c386..ab50adf175f8 100644 --- a/src/Foundation/NSAttributedString.cs +++ b/src/Foundation/NSAttributedString.cs @@ -181,22 +181,22 @@ public partial class NSAttributedString { [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSUrl url, NSAttributedStringDocumentAttributes documentAttributes, out NSError error) - : this (url, documentAttributes, out var _, out error) {} + : this (url, documentAttributes, out var _, out error) { } [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSData data, NSAttributedStringDocumentAttributes documentAttributes, out NSError error) - : this (data, documentAttributes, out var _, out error) {} + : this (data, documentAttributes, out var _, out error) { } [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSUrl url, out NSError error) - : this (url, new NSDictionary (), out var _, out error) {} + : this (url, new NSDictionary (), out var _, out error) { } [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] public NSAttributedString (NSData data, out NSError error) - : this (data, new NSDictionary (), out var _, out error) {} + : this (data, new NSDictionary (), out var _, out error) { } #else [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("Use the 'Create' method instead, because there's no way to return an error from a constructor.")] diff --git a/src/Foundation/NSAttributedString.mac.cs b/src/Foundation/NSAttributedString.mac.cs index 078f350d5ca5..74abe3b76959 100644 --- a/src/Foundation/NSAttributedString.mac.cs +++ b/src/Foundation/NSAttributedString.mac.cs @@ -16,10 +16,8 @@ using WebKit; //using CoreText; -namespace Foundation -{ - public partial class NSAttributedString - { +namespace Foundation { + public partial class NSAttributedString { public NSAttributedString (string str, NSFont? font = null, NSColor? foregroundColor = null, @@ -97,11 +95,11 @@ internal NSAttributedString (NSData data, NSAttributedStringDataType type, out N Handle = InitWithRtfd (data, out resultDocumentAttributes); break; default: - throw new ArgumentException("Error creating NSAttributedString."); + throw new ArgumentException ("Error creating NSAttributedString."); } if (Handle == IntPtr.Zero) - throw new ArgumentException("Error creating NSAttributedString."); + throw new ArgumentException ("Error creating NSAttributedString."); } public static NSAttributedString CreateWithRTF (NSData rtfData, out NSDictionary resultDocumentAttributes) diff --git a/src/Foundation/NSConnection.cs b/src/Foundation/NSConnection.cs index 6b2c233a2606..e8cc3a5cc2fc 100644 --- a/src/Foundation/NSConnection.cs +++ b/src/Foundation/NSConnection.cs @@ -36,10 +36,8 @@ // Disable until we get around to enable + fix any issues. #nullable disable -namespace Foundation -{ - public partial class NSConnection - { +namespace Foundation { + public partial class NSConnection { public TProxy GetRootProxy () where TProxy : NSObject { @@ -65,7 +63,7 @@ static TProxy GetRootProxy (IntPtr handle) where TProxy : NSObject var result = Runtime.TryGetNSObject (handle) as TProxy; if (result is null) - result = (TProxy)Activator.CreateInstance (typeof (TProxy), new object[] { handle }); + result = (TProxy) Activator.CreateInstance (typeof (TProxy), new object [] { handle }); return result; } diff --git a/src/Foundation/NSHost.cs b/src/Foundation/NSHost.cs index b410c6000d9b..879e2fbf496b 100644 --- a/src/Foundation/NSHost.cs +++ b/src/Foundation/NSHost.cs @@ -17,10 +17,8 @@ using System.Collections; using System.Collections.Generic; -namespace Foundation -{ - public partial class NSHost : IEquatable, IEnumerable - { +namespace Foundation { + public partial class NSHost : IEquatable, IEnumerable { static NSHost? CheckNull (NSHost? host) { if (host is null) @@ -143,7 +141,7 @@ public IPAddress [] Addresses { public override int GetHashCode () { - return (int)_Hash; + return (int) _Hash; } public override bool Equals (object? obj) diff --git a/src/Foundation/NSIndexSet.cs b/src/Foundation/NSIndexSet.cs index b50df0a7b8e5..27f82b5484d5 100644 --- a/src/Foundation/NSIndexSet.cs +++ b/src/Foundation/NSIndexSet.cs @@ -33,7 +33,7 @@ using ObjCRuntime; namespace Foundation { - + public partial class NSIndexSet : IEnumerable, IEnumerable { IEnumerator IEnumerable.GetEnumerator () @@ -59,8 +59,8 @@ public IEnumerator GetEnumerator () i = this.IndexGreaterThan (i); } } - - public nuint[] ToArray () + + public nuint [] ToArray () { nuint [] indexes = new nuint [Count]; @@ -75,54 +75,54 @@ public nuint[] ToArray () return indexes; } - public static NSIndexSet FromArray (nuint[] items) + public static NSIndexSet FromArray (nuint [] items) { if (items is null) return new NSIndexSet (); - - var indexSet = new NSMutableIndexSet(); - foreach (var index in items) - indexSet.Add (index); + + var indexSet = new NSMutableIndexSet (); + foreach (var index in items) + indexSet.Add (index); return indexSet; } - public static NSIndexSet FromArray (uint[] items) + public static NSIndexSet FromArray (uint [] items) { if (items is null) return new NSIndexSet (); - var indexSet = new NSMutableIndexSet(); + var indexSet = new NSMutableIndexSet (); foreach (var index in items) - indexSet.Add ((nuint)index); + indexSet.Add ((nuint) index); return indexSet; } - public static NSIndexSet FromArray (int[] items) + public static NSIndexSet FromArray (int [] items) { if (items is null) return new NSIndexSet (); - - var indexSet = new NSMutableIndexSet(); - foreach (var index in items){ + + var indexSet = new NSMutableIndexSet (); + foreach (var index in items) { if (index < 0) throw new ArgumentException ("One of the items values is negative"); - indexSet.Add ((nuint)(uint) index); + indexSet.Add ((nuint) (uint) index); } return indexSet; } - public NSIndexSet (uint value) : this ((nuint)value) + public NSIndexSet (uint value) : this ((nuint) value) { } - public NSIndexSet (nint value) : this ((nuint)value) + public NSIndexSet (nint value) : this ((nuint) value) { if (value < 0) throw new ArgumentException ("value must be positive"); // init done by the base ctor } - public NSIndexSet (int value) : this ((nuint)(uint)value) + public NSIndexSet (int value) : this ((nuint) (uint) value) { if (value < 0) throw new ArgumentException ("value must be positive"); diff --git a/src/Foundation/NSNumber.mac.cs b/src/Foundation/NSNumber.mac.cs index 1e5f80b1e701..4f22543ec637 100644 --- a/src/Foundation/NSNumber.mac.cs +++ b/src/Foundation/NSNumber.mac.cs @@ -14,35 +14,33 @@ // Disable until we get around to enable + fix any issues. #nullable disable -namespace Foundation -{ - public partial class NSNumber - { +namespace Foundation { + public partial class NSNumber { #if !COREBUILD public static NSNumber FromObject (object value) { if (value is float) { - return FromFloat ((float)value); + return FromFloat ((float) value); } else if (value is double) { - return FromDouble ((double)value); + return FromDouble ((double) value); } else if (value is sbyte) { - return FromSByte ((sbyte)value); + return FromSByte ((sbyte) value); } else if (value is byte) { - return FromByte ((byte)value); + return FromByte ((byte) value); } else if (value is short) { - return FromInt16 ((short)value); + return FromInt16 ((short) value); } else if (value is ushort) { - return FromUInt16 ((ushort)value); + return FromUInt16 ((ushort) value); } else if (value is int) { - return FromInt32 ((int)value); + return FromInt32 ((int) value); } else if (value is uint) { - return FromUInt32 ((uint)value); + return FromUInt32 ((uint) value); } else if (value is long) { - return FromInt64 ((long)value); + return FromInt64 ((long) value); } else if (value is ulong) { - return FromUInt64 ((ulong)value); + return FromUInt64 ((ulong) value); } else if (value is bool) { - return FromBoolean ((bool)value); + return FromBoolean ((bool) value); } else if (value is nint) { return FromNInt ((nint) value); } else if (value is nuint) { diff --git a/src/Foundation/NSObject.mac.cs b/src/Foundation/NSObject.mac.cs index 0f92d00a4f34..0b1fb0266514 100644 --- a/src/Foundation/NSObject.mac.cs +++ b/src/Foundation/NSObject.mac.cs @@ -100,7 +100,7 @@ public partial class NSObject { static IntPtr nl = Dlfcn.dlopen (Constants.NaturalLanguageLibrary, 1); static IntPtr vs = Dlfcn.dlopen (Constants.VideoSubscriberAccountLibrary, 1); static IntPtr un = Dlfcn.dlopen (Constants.UserNotificationsLibrary, 1); - static IntPtr il = Dlfcn.dlopen (Constants.iTunesLibraryLibrary, 1); + static IntPtr il = Dlfcn.dlopen (Constants.iTunesLibraryLibrary, 1); static IntPtr exl = Dlfcn.dlopen (Constants.ExtensionKitLibrary, 1); static IntPtr sw = Dlfcn.dlopen (Constants.SharedWithYouLibrary, 1); static IntPtr swc = Dlfcn.dlopen (Constants.SharedWithYouCoreLibrary, 1); diff --git a/src/Foundation/NSPropertyListSerialization.cs b/src/Foundation/NSPropertyListSerialization.cs index 6b56f3612348..aeb80700fdc3 100644 --- a/src/Foundation/NSPropertyListSerialization.cs +++ b/src/Foundation/NSPropertyListSerialization.cs @@ -30,10 +30,8 @@ using System; -namespace Foundation -{ - public partial class NSPropertyListSerialization - { +namespace Foundation { + public partial class NSPropertyListSerialization { public static NSData DataWithPropertyList (NSObject plist, NSPropertyListFormat format, out NSError error) { return DataWithPropertyList (plist, format, NSPropertyListWriteOptions.Immutable, out error); diff --git a/src/Foundation/NSScriptCommandArgumentDescription.cs b/src/Foundation/NSScriptCommandArgumentDescription.cs index e60a43b7231d..4524945bae73 100644 --- a/src/Foundation/NSScriptCommandArgumentDescription.cs +++ b/src/Foundation/NSScriptCommandArgumentDescription.cs @@ -30,16 +30,16 @@ public static NSString OptionalKey { public partial class NSScriptCommandArgumentDescription { public string Name { get; set; } - public bool IsOptional { + public bool IsOptional { get { return Optional is not null && Optional == "Yes"; } - set { + set { Optional = (value) ? "Yes" : "No"; } } - public NSScriptCommandArgumentDescription (string name, string eventCode, string type, bool isOptional=false) + public NSScriptCommandArgumentDescription (string name, string eventCode, string type, bool isOptional = false) { if (String.IsNullOrEmpty (name)) throw new ArgumentException ("name cannot be null or empty."); @@ -58,7 +58,7 @@ public NSScriptCommandArgumentDescription (string name, string eventCode, string } } - + #endif } diff --git a/src/Foundation/NSScriptCommandDescription.cs b/src/Foundation/NSScriptCommandDescription.cs index 04aaf384c62b..afa41557f905 100644 --- a/src/Foundation/NSScriptCommandDescription.cs +++ b/src/Foundation/NSScriptCommandDescription.cs @@ -14,11 +14,11 @@ namespace Foundation { // The kyes are not found in any of the public headers from apple. That is the reason // to use this technique. static class NSScriptCommonKeys { - private static NSString appEventCode = new NSString ("AppleEventCode"); + private static NSString appEventCode = new NSString ("AppleEventCode"); public static NSString AppleEventCodeKey { get { return appEventCode; } } - + private static NSString typeKey = new NSString ("Type"); public static NSString TypeKey { get { return typeKey; } @@ -36,7 +36,7 @@ static int ToIntValue (string fourCC) int ret = 0; for (int i = 0; i < 4; i++) { ret <<= 8; - ret |= fourCC[i]; + ret |= fourCC [i]; } return ret; } @@ -63,7 +63,7 @@ public static NSScriptCommandDescription Create (string suiteName, string comman throw new ArgumentException ("eventClass must be a four characters string."); if (commandDeclaration.ResultAppleEventCode is not null && commandDeclaration.ResultAppleEventCode.Length != 4) throw new ArgumentException ("resultAppleEvent must be a four characters string."); - + using (var nsSuitName = new NSString (suiteName)) using (var nsCommandName = new NSString (commandName)) { try { @@ -96,8 +96,8 @@ public string GetTypeForArgument (string name) { if (name is null) throw new ArgumentNullException ("name"); - - using (var nsName = new NSString(name)) + + using (var nsName = new NSString (name)) using (var nsType = GetNSTypeForArgument (nsName)) { return nsType?.ToString (); } @@ -112,8 +112,8 @@ public string GetAppleEventCodeForArgument (string name) return Runtime.ToFourCCString (FCCAppleEventCodeForArgument (nsName)); } } - - public bool IsOptionalArgument (string name) + + public bool IsOptionalArgument (string name) { using (var nsName = new NSString (name)) { return NSIsOptionalArgument (nsName); diff --git a/src/Foundation/NSScriptCommandDescriptionDictionary.cs b/src/Foundation/NSScriptCommandDescriptionDictionary.cs index 4f140e4d110c..55c42fd4abfc 100644 --- a/src/Foundation/NSScriptCommandDescriptionDictionary.cs +++ b/src/Foundation/NSScriptCommandDescriptionDictionary.cs @@ -9,28 +9,28 @@ namespace Foundation { public static class NSScriptCommandDescriptionDictionaryKeys { private static NSString cmdClass = new NSString ("CommandClass"); - public static NSString CommandClassKey { + public static NSString CommandClassKey { get { return cmdClass; } } - - public static NSString AppleEventCodeKey { + + public static NSString AppleEventCodeKey { get { return NSScriptCommonKeys.AppleEventCodeKey; } } - + private static NSString codeClass = new NSString ("AppleEventClassCode"); - public static NSString AppleEventClassCodeKey { + public static NSString AppleEventClassCodeKey { get { return codeClass; } } - + public static NSString TypeKey { get { return NSScriptCommonKeys.TypeKey; } } - + private static NSString resultAppEventCode = new NSString ("ResultAppleEventCode"); - public static NSString ResultAppleEventCodeKey { + public static NSString ResultAppleEventCodeKey { get { return resultAppEventCode; } } - + private static NSString args = new NSString ("Arguments"); public static NSString ArgumentsKey { get { return args; } @@ -44,7 +44,7 @@ public void Add (NSScriptCommandArgumentDescription arg) if (arg is null) throw new ArgumentNullException ("arg"); if (Arguments is null) - Arguments = new NSMutableDictionary (); + Arguments = new NSMutableDictionary (); using (var nsName = new NSString (arg.Name)) { Arguments.Add (nsName, arg.Dictionary); } diff --git a/src/Foundation/NSSecureCoding.cs b/src/Foundation/NSSecureCoding.cs index 30c523180085..4d616daff386 100644 --- a/src/Foundation/NSSecureCoding.cs +++ b/src/Foundation/NSSecureCoding.cs @@ -28,8 +28,7 @@ public static bool SupportsSecureCoding (Type type) #if MONOMAC try { return SupportsSecureCoding (new Class (type)); - } - catch (ArgumentException) { + } catch (ArgumentException) { // unlike XI the current registration will throw for protocols // until that's fixed we'll only report correctly properly bound protocol types // the workaround is important since this method is used to validate our bindings diff --git a/src/Foundation/NSString.cs b/src/Foundation/NSString.cs index adde5d390fbf..115081a7e8ae 100644 --- a/src/Foundation/NSString.cs +++ b/src/Foundation/NSString.cs @@ -44,11 +44,11 @@ namespace Foundation { #if COREBUILD [Protocol] - public interface INSCopying {} + public interface INSCopying { } [Protocol] - public interface INSCoding {} + public interface INSCoding { } [Protocol] - public interface INSSecureCoding {} + public interface INSSecureCoding { } #endif public partial class NSString : NSObject diff --git a/src/Foundation/NSThread.mac.cs b/src/Foundation/NSThread.mac.cs index 5bf36a09f0d1..f8b681ccf731 100644 --- a/src/Foundation/NSThread.mac.cs +++ b/src/Foundation/NSThread.mac.cs @@ -10,19 +10,16 @@ using System; -namespace Foundation -{ - public partial class NSThread - { - class ActionThread : NSThread - { +namespace Foundation { + public partial class NSThread { + class ActionThread : NSThread { Action action; - + public ActionThread (Action action) { this.action = action; } - + public override void Main () { action (); diff --git a/src/Foundation/NSUrlDownload.cs b/src/Foundation/NSUrlDownload.cs index 2161b97aa83f..e71e7ebdfcd7 100644 --- a/src/Foundation/NSUrlDownload.cs +++ b/src/Foundation/NSUrlDownload.cs @@ -2,7 +2,7 @@ namespace Foundation { public partial class NSUrlDownload { - + public override string ToString () { return GetType ().ToString (); diff --git a/src/GameKit/GKCompat.cs b/src/GameKit/GKCompat.cs index 0f2cadd8d4be..1a70c5f50231 100644 --- a/src/GameKit/GKCompat.cs +++ b/src/GameKit/GKCompat.cs @@ -48,8 +48,7 @@ public static void DidSaveData (GKGameSession session, GKCloudPlayer player, Fou [Unavailable (PlatformName.MacOSX)] [Unavailable (PlatformName.TvOS)] #endif - public interface IGKPeerPickerControllerDelegate : INativeObject, IDisposable - { + public interface IGKPeerPickerControllerDelegate : INativeObject, IDisposable { } [EditorBrowsable (EditorBrowsableState.Never)] @@ -207,7 +206,7 @@ public virtual NSObject? WeakDelegate { protected override void Dispose (bool disposing) { - throw new PlatformNotSupportedException (Constants.TypeUnavailable); + throw new PlatformNotSupportedException (Constants.TypeUnavailable); } } /* class GKPeerPickerController */ #endif // __IOS__ || __MACCATALYST__ diff --git a/src/ImageIO/CGImageAnimation.cs b/src/ImageIO/CGImageAnimation.cs index 954888f9622c..df3743762c81 100644 --- a/src/ImageIO/CGImageAnimation.cs +++ b/src/ImageIO/CGImageAnimation.cs @@ -19,20 +19,20 @@ namespace ImageIO { #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif public static class CGImageAnimation { public delegate void CGImageSourceAnimationHandler (nint index, CGImage image, out bool stop); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -41,10 +41,10 @@ public static class CGImageAnimation { unsafe static extern /* OSStatus */ CGImageAnimationStatus CGAnimateImageAtURLWithBlock ( /* CFURLRef */ IntPtr url, /* CFDictionaryRef _iio_Nullable */ IntPtr options, /* CGImageSourceAnimationHandler */ BlockLiteral* block); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -53,10 +53,10 @@ public static class CGImageAnimation { unsafe static extern /* OSStatus */ CGImageAnimationStatus CGAnimateImageDataWithBlock ( /* CFDataRef _Nonnull */ IntPtr data, /* CFDictionaryRef _Nullable */ IntPtr options, /* CGImageSourceAnimationHandler _Nonnull */ BlockLiteral* block); #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] @@ -82,10 +82,10 @@ public static CGImageAnimationStatus AnimateImage (NSUrl url, CGImageAnimationOp } #if NET - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("ios13.0")] - [SupportedOSPlatform ("tvos13.0")] - [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("ios13.0")] + [SupportedOSPlatform ("tvos13.0")] + [SupportedOSPlatform ("maccatalyst")] #else [Introduced (PlatformName.iOS, 13, 0, PlatformArchitecture.All)] [Introduced (PlatformName.TvOS, 13, 0, PlatformArchitecture.All)] diff --git a/src/Intents/INSetClimateSettingsInCarIntent.cs b/src/Intents/INSetClimateSettingsInCarIntent.cs index 859a84e79da3..523481cf5234 100644 --- a/src/Intents/INSetClimateSettingsInCarIntent.cs +++ b/src/Intents/INSetClimateSettingsInCarIntent.cs @@ -16,7 +16,7 @@ public partial class INSetClimateSettingsInCarIntent { [UnsupportedOSPlatform ("macos")] [UnsupportedOSPlatform ("tvos")] public INSetClimateSettingsInCarIntent (bool? enableFan, bool? enableAirConditioner, bool? enableClimateControl, bool? enableAutoMode, INCarAirCirculationMode airCirculationMode, NSNumber fanSpeedIndex, NSNumber fanSpeedPercentage, INRelativeSetting relativeFanSpeedSetting, NSMeasurement temperature, INRelativeSetting relativeTemperatureSetting, INCarSeat climateZone) : - this (enableFan.HasValue ? new NSNumber (enableFan.Value) : null, enableAirConditioner.HasValue ? new NSNumber (enableAirConditioner.Value) : null, + this (enableFan.HasValue ? new NSNumber (enableFan.Value) : null, enableAirConditioner.HasValue ? new NSNumber (enableAirConditioner.Value) : null, enableClimateControl.HasValue ? new NSNumber (enableClimateControl.Value) : null, enableAutoMode.HasValue ? new NSNumber (enableAutoMode.Value) : null, airCirculationMode, fanSpeedIndex, fanSpeedPercentage, relativeFanSpeedSetting, temperature, relativeTemperatureSetting, climateZone) { diff --git a/src/MapKit/MapKit.cs b/src/MapKit/MapKit.cs index a5ae570ccccf..a0f966bf0919 100644 --- a/src/MapKit/MapKit.cs +++ b/src/MapKit/MapKit.cs @@ -466,7 +466,7 @@ public static class MKGeometry { } #if COREBUILD - public partial class MKMapLaunchOptions :NSObject { + public partial class MKMapLaunchOptions : NSObject { } #endif } diff --git a/src/MediaExtension/MEByteSource.cs b/src/MediaExtension/MEByteSource.cs index 7db378b6fbc1..3a5f1ef2968e 100644 --- a/src/MediaExtension/MEByteSource.cs +++ b/src/MediaExtension/MEByteSource.cs @@ -12,7 +12,7 @@ public partial class MEByteSource { /// The byte array to write the data into. /// The delegate which is called when the read operation has completed. /// This overload will try to fill the byte array with data. - public void ReadData (long offset, byte[] data, MEByteSourceReadBytesCallback completionHandler) + public void ReadData (long offset, byte [] data, MEByteSourceReadBytesCallback completionHandler) { ReadData ((nuint) data.Length, offset, data, completionHandler); } @@ -22,7 +22,7 @@ public void ReadData (long offset, byte[] data, MEByteSourceReadBytesCallback co /// The offset (relative to the start of the ifle) where to start reading. /// The byte array to write the data into. /// The delegate which is called when the read operation has completed. - public void ReadData (nuint length, long offset, byte[] data, MEByteSourceReadBytesCallback completionHandler) + public void ReadData (nuint length, long offset, byte [] data, MEByteSourceReadBytesCallback completionHandler) { if (data is null) ThrowHelper.ThrowArgumentNullException (nameof (data)); @@ -44,7 +44,7 @@ public void ReadData (nuint length, long offset, byte[] data, MEByteSourceReadBy /// Null if an error occurred, otherwise an instance with information about the error. The error will be if the end was reached. /// True if successful, false otherwise. /// This overload will try to fill the byte array with data. - public bool ReadData (long offset, byte[] data, out nuint bytesRead, out NSError? error) + public bool ReadData (long offset, byte [] data, out nuint bytesRead, out NSError? error) { return ReadData ((nuint) data.Length, offset, data, out bytesRead, out error); } @@ -56,7 +56,7 @@ public bool ReadData (long offset, byte[] data, out nuint bytesRead, out NSError /// Upon return, will contain the number of read bytes. /// Null if an error occurred, otherwise an instance with information about the error. The error will be if the end was reached. /// True if successful, false otherwise. - public bool ReadData (nuint length, long offset, byte[] data, out nuint bytesRead, out NSError? error) + public bool ReadData (nuint length, long offset, byte [] data, out nuint bytesRead, out NSError? error) { if (data is null) ThrowHelper.ThrowArgumentNullException (nameof (data)); diff --git a/src/MediaExtension/MERawProcessingListParameter.cs b/src/MediaExtension/MERawProcessingListParameter.cs index 35aaba9a5026..c5642d5487b8 100644 --- a/src/MediaExtension/MERawProcessingListParameter.cs +++ b/src/MediaExtension/MERawProcessingListParameter.cs @@ -23,7 +23,7 @@ public partial class MERawProcessingListParameter { /// The parameter's initial value. /// The parameter's neutral or camera value. /// Specifies whether is a neutral or a camera value. - public MERawProcessingListParameter (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralOrCameraValue, MERawProcessingListParameterInitializationOption option) + public MERawProcessingListParameter (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralOrCameraValue, MERawProcessingListParameterInitializationOption option) : base (NSObjectFlag.Empty) { switch (option) { diff --git a/src/MediaExtension/MESampleCursor.cs b/src/MediaExtension/MESampleCursor.cs index 340ac8de24fb..2f610ea787a1 100644 --- a/src/MediaExtension/MESampleCursor.cs +++ b/src/MediaExtension/MESampleCursor.cs @@ -14,7 +14,7 @@ public partial interface IMESampleCursor { /// Upon return, the exact location of the sample. /// Upon return, null if successful, otherwise an instance for the error. /// True if successful, false otherwise. - public bool RefineSampleLocation (AVSampleCursorStorageRange estimatedSampleLocation, byte [] refinementData, out AVSampleCursorStorageRange refinedLocation, out NSError? error) + public bool RefineSampleLocation (AVSampleCursorStorageRange estimatedSampleLocation, byte [] refinementData, out AVSampleCursorStorageRange refinedLocation, out NSError? error) { unsafe { fixed (byte* refinementDataPtr = refinementData) { diff --git a/src/MediaToolbox/MTAudioProcessingTap.cs b/src/MediaToolbox/MTAudioProcessingTap.cs index df910cd2e4ac..9bb28c656b6b 100644 --- a/src/MediaToolbox/MTAudioProcessingTap.cs +++ b/src/MediaToolbox/MTAudioProcessingTap.cs @@ -44,19 +44,17 @@ using AudioToolbox; using CoreMedia; -namespace MediaToolbox -{ - public class MTAudioProcessingTap : NativeObject - { +namespace MediaToolbox { + public class MTAudioProcessingTap : NativeObject { #if !COREBUILD delegate void Action_IntPtr (IntPtr arg); // MTAudioProcessingTapCallbacks [StructLayout (LayoutKind.Sequential, Pack = 1)] - unsafe struct Callbacks - { + unsafe struct Callbacks { #pragma warning disable 169 - /* int */ int version; // kMTAudioProcessingTapCallbacksVersion_0 == 0 + /* int */ + int version; // kMTAudioProcessingTapCallbacksVersion_0 == 0 public /* void* */ IntPtr clientInfo; #if NET public /* MTAudioProcessingTapInitCallback */ delegate* unmanaged init; @@ -77,8 +75,8 @@ unsafe struct Callbacks // MTAudioProcessingTapInitCallback unsafe delegate void MTAudioProcessingTapInitCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, /* void* */ IntPtr clientInfo, /* void** */ out void* tapStorageOut); - delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, - IntPtr numberFrames, MTAudioProcessingTapFlags flags, /* AudioBufferList* */ IntPtr bufferListInOut, + delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, + IntPtr numberFrames, MTAudioProcessingTapFlags flags, /* AudioBufferList* */ IntPtr bufferListInOut, out IntPtr numberFramesOut, out MTAudioProcessingTapFlags flagsOut); delegate void MTAudioProcessingTapPrepareCallbackProxy (/* MTAudioProcessingTapRef */ IntPtr tap, IntPtr maxFrames, ref AudioStreamBasicDescription processingFormat); @@ -86,10 +84,10 @@ delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapR static readonly Dictionary handles = new Dictionary (Runtime.IntPtrEqualityComparer); MTAudioProcessingTapCallbacks callbacks; - + internal static MTAudioProcessingTap? FromHandle (IntPtr handle, bool owns) { - lock (handles){ + lock (handles) { if (handles.TryGetValue (handle, out var ret)) return ret; return null; @@ -98,8 +96,8 @@ delegate void MTAudioProcessingTapProcessCallbackProxy (/* MTAudioProcessingTapR [DllImport (Constants.MediaToolboxLibrary)] unsafe extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapCreate ( - /* CFAllocatorRef*/ IntPtr allocator, - /* const MTAudioProcessingTapCallbacks* */ Callbacks* callbacks, + /* CFAllocatorRef*/ IntPtr allocator, + /* const MTAudioProcessingTapCallbacks* */ Callbacks* callbacks, MTAudioProcessingTapCreationFlags flags, /* MTAudioProcessingTapRef* */ IntPtr* tapOut); @@ -144,7 +142,7 @@ public MTAudioProcessingTap (MTAudioProcessingTapCallbacks callbacks, MTAudioPro // and that will call the InitializeProxy. So using this (short-lived) GCHandle allow us to find back the // original managed instance var gch = GCHandle.Alloc (this); - c.clientInfo = (IntPtr)gch; + c.clientInfo = (IntPtr) gch; IntPtr handle; MTAudioProcessingTapError res; @@ -183,7 +181,7 @@ protected override void Dispose (bool disposing) [DllImport (Constants.MediaToolboxLibrary)] unsafe extern static /* OSStatus */ MTAudioProcessingTapError MTAudioProcessingTapGetSourceAudio ( - /* MTAudioProcessingTapRef */ IntPtr tap, IntPtr numberFrames, + /* MTAudioProcessingTapRef */ IntPtr tap, IntPtr numberFrames, /* AudioBufferList* */ IntPtr bufferListInOut, MTAudioProcessingTapFlags* flagsOut, CMTimeRange* timeRangeOut, IntPtr* numberFramesOut); @@ -200,14 +198,14 @@ public MTAudioProcessingTapError GetSourceAudio (nint frames, AudioBuffers buffe r = MTAudioProcessingTapGetSourceAudio (Handle, (IntPtr) frames, (IntPtr) bufferList, - (MTAudioProcessingTapFlags *) Unsafe.AsPointer (ref flags), - (CMTimeRange *) Unsafe.AsPointer (ref timeRange), + (MTAudioProcessingTapFlags*) Unsafe.AsPointer (ref flags), + (CMTimeRange*) Unsafe.AsPointer (ref timeRange), &result); } framesProvided = (nint) result; return r; } - + // // Proxy callbacks @@ -222,7 +220,7 @@ unsafe static void InitializeProxy (IntPtr tap, IntPtr /*void**/ clientInfo, out #endif { #if NET - void *tempTapStorage = null; + void* tempTapStorage = null; *tapStorage = tempTapStorage; #else tapStorage = null; @@ -238,7 +236,7 @@ unsafe static void InitializeProxy (IntPtr tap, IntPtr /*void**/ clientInfo, out apt?.callbacks.Initialize (apt, out tapStorage); #endif } - } + } #if NET [UnmanagedCallersOnly] @@ -328,30 +326,26 @@ static void UnprepareProxy (IntPtr tap) // uint32_t -> MTAudioProcessingTap.h [Flags] - public enum MTAudioProcessingTapCreationFlags : uint - { - PreEffects = (1 << 0), - PostEffects = (1 << 1), + public enum MTAudioProcessingTapCreationFlags : uint { + PreEffects = (1 << 0), + PostEffects = (1 << 1), } // uint32_t -> MTAudioProcessingTap.h [Flags] - public enum MTAudioProcessingTapFlags : uint - { - StartOfStream = (1 << 8), - EndOfStream = (1 << 9), + public enum MTAudioProcessingTapFlags : uint { + StartOfStream = (1 << 8), + EndOfStream = (1 << 9), } // used as OSStatus (4 bytes) // Not documented error codes - public enum MTAudioProcessingTapError - { - None = 0, - InvalidArgument = -12780 + public enum MTAudioProcessingTapError { + None = 0, + InvalidArgument = -12780 } - public class MTAudioProcessingTapCallbacks - { + public class MTAudioProcessingTapCallbacks { public MTAudioProcessingTapCallbacks (MTAudioProcessingTapProcessDelegate process) { if (process is null) @@ -374,7 +368,7 @@ public delegate void MTAudioProcessingTapProcessDelegate (MTAudioProcessingTap t AudioBuffers bufferList, out nint numberFramesOut, out MTAudioProcessingTapFlags flagsOut); #if COREBUILD - public class AudioBufferList {} + public class AudioBufferList { } #endif } #endif // HAS_MEDIATOOLBOX diff --git a/src/Metal/Defs.cs b/src/Metal/Defs.cs index e3dfdfec36aa..4d01f7e01b29 100644 --- a/src/Metal/Defs.cs +++ b/src/Metal/Defs.cs @@ -531,8 +531,7 @@ public partial interface IMTLTexture { [NoiOS] [NoTV] #endif - public struct MTLIndirectCommandBufferExecutionRange - { + public struct MTLIndirectCommandBufferExecutionRange { public uint Location; public uint Length; diff --git a/src/Metal/MTLArgumentEncoder.cs b/src/Metal/MTLArgumentEncoder.cs index 021d89204685..19eedb5c37be 100644 --- a/src/Metal/MTLArgumentEncoder.cs +++ b/src/Metal/MTLArgumentEncoder.cs @@ -10,14 +10,14 @@ namespace Metal { public static partial class MTLArgumentEncoder_Extensions { #if NET - public static void SetBuffers (this IMTLArgumentEncoder encoder, IMTLBuffer[] buffers, nuint[] offsets, NSRange range) + public static void SetBuffers (this IMTLArgumentEncoder encoder, IMTLBuffer [] buffers, nuint [] offsets, NSRange range) { if (buffers is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (buffers)); if (offsets is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (offsets)); - var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr[buffers.Length] : new IntPtr [buffers.Length]; + var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr [buffers.Length] : new IntPtr [buffers.Length]; // get all intptr from the array to pass to the lower level call for (var i = 0; i < buffers.Length; i++) { bufferPtrArray [i] = buffers [i].Handle; diff --git a/src/Metal/MTLArrays.cs b/src/Metal/MTLArrays.cs index 0152d4b7f357..8d073882b350 100644 --- a/src/Metal/MTLArrays.cs +++ b/src/Metal/MTLArrays.cs @@ -94,8 +94,7 @@ public MTLPipelineBufferDescriptor this [nuint index] { #if IOS public partial class MTLTileRenderPipelineColorAttachmentDescriptorArray { - public MTLTileRenderPipelineColorAttachmentDescriptor this [nuint index] - { + public MTLTileRenderPipelineColorAttachmentDescriptor this [nuint index] { get { return GetObject (index); } diff --git a/src/Metal/MTLComputeCommandEncoder.cs b/src/Metal/MTLComputeCommandEncoder.cs index d8d38c414c1e..ac6351703dbb 100644 --- a/src/Metal/MTLComputeCommandEncoder.cs +++ b/src/Metal/MTLComputeCommandEncoder.cs @@ -12,14 +12,14 @@ namespace Metal { // add some extension methods to make the API of the protocol nicer public static class IMTLComputeCommandEncoderExtensions { - public static void SetBuffers (this IMTLComputeCommandEncoder table, IMTLBuffer[] buffers, nuint[] offsets, NSRange range) + public static void SetBuffers (this IMTLComputeCommandEncoder table, IMTLBuffer [] buffers, nuint [] offsets, NSRange range) { if (buffers is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (buffers)); if (offsets is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (offsets)); - var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr[buffers.Length] : new IntPtr [buffers.Length]; + var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr [buffers.Length] : new IntPtr [buffers.Length]; // get all intptr from the array to pass to the lower level call for (var i = 0; i < buffers.Length; i++) { bufferPtrArray [i] = buffers [i].Handle; diff --git a/src/Metal/MTLRasterizationRateLayerDescriptor.cs b/src/Metal/MTLRasterizationRateLayerDescriptor.cs index 1c893a8c2682..ac0fb739b845 100644 --- a/src/Metal/MTLRasterizationRateLayerDescriptor.cs +++ b/src/Metal/MTLRasterizationRateLayerDescriptor.cs @@ -9,8 +9,7 @@ #nullable enable namespace Metal { - public partial class MTLRasterizationRateLayerDescriptor - { + public partial class MTLRasterizationRateLayerDescriptor { #if NET [SupportedOSPlatform ("maccatalyst")] [SupportedOSPlatform ("ios13.0")] @@ -19,10 +18,10 @@ public partial class MTLRasterizationRateLayerDescriptor #else [MacCatalyst (15,0)] #endif - public double[] HorizontalSampleStorage { + public double [] HorizontalSampleStorage { get { - var width = (int)SampleCount.Width; - var floatArray = new double[width]; + var width = (int) SampleCount.Width; + var floatArray = new double [width]; Marshal.Copy (_HorizontalSampleStorage, floatArray, 0, width); return floatArray; } @@ -36,10 +35,10 @@ public double[] HorizontalSampleStorage { #else [MacCatalyst (15,0)] #endif - public double[] VerticalSampleStorage { + public double [] VerticalSampleStorage { get { - var height = (int)SampleCount.Height; - var floatArray = new double[height]; + var height = (int) SampleCount.Height; + var floatArray = new double [height]; Marshal.Copy (_VerticalSampleStorage, floatArray, 0, height); return floatArray; } @@ -53,7 +52,7 @@ public double[] VerticalSampleStorage { #else [MacCatalyst (15,0)] #endif - static public MTLRasterizationRateLayerDescriptor Create (MTLSize sampleCount, float[] horizontal, float[] vertical) + static public MTLRasterizationRateLayerDescriptor Create (MTLSize sampleCount, float [] horizontal, float [] vertical) { if (horizontal is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (horizontal)); diff --git a/src/Metal/MTLResourceStateCommandEncoder.cs b/src/Metal/MTLResourceStateCommandEncoder.cs index 428fc8ba235b..d79726e4ecfa 100644 --- a/src/Metal/MTLResourceStateCommandEncoder.cs +++ b/src/Metal/MTLResourceStateCommandEncoder.cs @@ -32,7 +32,7 @@ public static partial class MTLResourceStateCommandEncoder_Extensions { [NoMac] [NoTV] #endif - public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTexture texture, MTLSparseTextureMappingMode mode, MTLRegion[] regions, nuint[] mipLevels, nuint[] slices) + public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTexture texture, MTLSparseTextureMappingMode mode, MTLRegion [] regions, nuint [] mipLevels, nuint [] slices) { if (texture is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (texture)); @@ -43,14 +43,14 @@ public static void Update (this IMTLResourceStateCommandEncoder This, IMTLTextur if (slices is null) ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (slices)); - var regionsHandle = GCHandle.Alloc (regions, GCHandleType.Pinned); - var mipLevelsHandle = GCHandle.Alloc (mipLevels, GCHandleType.Pinned); - var slicesHandle = GCHandle.Alloc (slices, GCHandleType.Pinned); + var regionsHandle = GCHandle.Alloc (regions, GCHandleType.Pinned); + var mipLevelsHandle = GCHandle.Alloc (mipLevels, GCHandleType.Pinned); + var slicesHandle = GCHandle.Alloc (slices, GCHandleType.Pinned); try { var regionsPtr = regionsHandle.AddrOfPinnedObject (); var mipLevelsPtr = mipLevelsHandle.AddrOfPinnedObject (); var slicesPtr = slicesHandle.AddrOfPinnedObject (); - This.Update (texture, mode, regionsPtr, mipLevelsPtr, slicesPtr, (nuint)regions.Length); + This.Update (texture, mode, regionsPtr, mipLevelsPtr, slicesPtr, (nuint) regions.Length); } finally { regionsHandle.Free (); mipLevelsHandle.Free (); diff --git a/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs b/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs index 03409a877687..a350281ee0c4 100644 --- a/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs +++ b/src/MetalPerformanceShadersGraph/MPSGraphExecutable.cs @@ -12,10 +12,10 @@ namespace MetalPerformanceShadersGraph { /// This enum is used to select how to initialize a new instance of a . #if NET - [SupportedOSPlatform ("ios17.0")] - [SupportedOSPlatform ("maccatalyst17.0")] - [SupportedOSPlatform ("macos14.0")] - [SupportedOSPlatform ("tvos17.0")] + [SupportedOSPlatform ("ios17.0")] + [SupportedOSPlatform ("maccatalyst17.0")] + [SupportedOSPlatform ("macos14.0")] + [SupportedOSPlatform ("tvos17.0")] #else [TV (17, 0), Mac (14, 0), iOS (17, 0), MacCatalyst (17, 0)] #endif diff --git a/src/MetricKit/MXMetaData.cs b/src/MetricKit/MXMetaData.cs index 38ab71eda339..e0df3dcfdecc 100644 --- a/src/MetricKit/MXMetaData.cs +++ b/src/MetricKit/MXMetaData.cs @@ -22,7 +22,7 @@ public partial class MXMetaData { #endif public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14,0)) + if (SystemVersion.CheckiOS (14, 0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/MetricKit/MXMetric.cs b/src/MetricKit/MXMetric.cs index 1aa2230fe4fd..342b2ef0fb04 100644 --- a/src/MetricKit/MXMetric.cs +++ b/src/MetricKit/MXMetric.cs @@ -14,7 +14,7 @@ public partial class MXMetric { public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14,0)) + if (SystemVersion.CheckiOS (14, 0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/MetricKit/MXMetricPayload.cs b/src/MetricKit/MXMetricPayload.cs index 567f5b71f77b..bc4d54a1a0fa 100644 --- a/src/MetricKit/MXMetricPayload.cs +++ b/src/MetricKit/MXMetricPayload.cs @@ -14,7 +14,7 @@ public partial class MXMetricPayload { public virtual NSDictionary DictionaryRepresentation { get { - if (SystemVersion.CheckiOS (14,0)) + if (SystemVersion.CheckiOS (14, 0)) return _DictionaryRepresentation14; else return _DictionaryRepresentation13; diff --git a/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs b/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs index 01d69a593730..a207c9d05efa 100644 --- a/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs +++ b/src/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValues.cs @@ -22,8 +22,7 @@ #endif namespace NearbyInteraction { - public partial class NIAlgorithmConvergenceStatusReasonValues - { + public partial class NIAlgorithmConvergenceStatusReasonValues { #if NET [SupportedOSPlatform ("ios16.0")] [SupportedOSPlatform ("maccatalyst16.0")] diff --git a/src/NearbyInteraction/NINearbyObject.cs b/src/NearbyInteraction/NINearbyObject.cs index 18f691c36940..658e36c83126 100644 --- a/src/NearbyInteraction/NINearbyObject.cs +++ b/src/NearbyInteraction/NINearbyObject.cs @@ -25,22 +25,21 @@ #if __IOS__ namespace NearbyInteraction { - partial class NINearbyObject - { + partial class NINearbyObject { static Vector3? _DirectionNotAvailable; // TODO: https://github.com/xamarin/maccore/issues/2274 // We do not have generator support to trampoline Vector3 -> vector_float3 for Fields - [Field ("NINearbyObjectDirectionNotAvailable", "NearbyInteraction")] + [Field ("NINearbyObjectDirectionNotAvailable", "NearbyInteraction")] public static Vector3 DirectionNotAvailable { get { if (_DirectionNotAvailable is null) { unsafe { - Vector3 *pointer = (Vector3 *) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectDirectionNotAvailable"); + Vector3* pointer = (Vector3*) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectDirectionNotAvailable"); _DirectionNotAvailable = *pointer; } } - return (Vector3)_DirectionNotAvailable; + return (Vector3) _DirectionNotAvailable; } } @@ -55,18 +54,18 @@ public static Vector3 DirectionNotAvailable { [iOS (16,0), MacCatalyst (16,0)] #endif // NET // Following similar strategy found here: https://github.com/xamarin/maccore/issues/2274 - [Field ("NINearbyObjectWorldTransformNotAvailable", "NearbyInteraction")] + [Field ("NINearbyObjectWorldTransformNotAvailable", "NearbyInteraction")] public static MatrixFloat4x4 WorldTransformNotAvailable { get { if (_WorldTransformNotAvailable is null) { unsafe { - MatrixFloat4x4 *pointer = (MatrixFloat4x4 *) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectWorldTransformNotAvailable"); + MatrixFloat4x4* pointer = (MatrixFloat4x4*) Dlfcn.GetIndirect (Libraries.NearbyInteraction.Handle, "NINearbyObjectWorldTransformNotAvailable"); if (pointer is null) throw new PlatformNotSupportedException ("This property is not supported on this version of the OS"); _WorldTransformNotAvailable = *pointer; } } - return (MatrixFloat4x4)_WorldTransformNotAvailable; + return (MatrixFloat4x4) _WorldTransformNotAvailable; } } } diff --git a/src/Network/NWConnection.cs b/src/Network/NWConnection.cs index 5fd4ce6c4ad2..21677dfbdd19 100644 --- a/src/Network/NWConnection.cs +++ b/src/Network/NWConnection.cs @@ -55,7 +55,7 @@ namespace Network { public class NWConnection : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWConnection (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWConnection (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWConnection (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWConnectionGroup.cs b/src/Network/NWConnectionGroup.cs index e2388e91882b..893b191e7af3 100644 --- a/src/Network/NWConnectionGroup.cs +++ b/src/Network/NWConnectionGroup.cs @@ -298,7 +298,7 @@ public void SetStateChangedHandler (NWConnectionGroupStateChangedDelegate handle } #if NET - delegate* unmanaged trampoline= &TrampolineStateChangedHandler; + delegate* unmanaged trampoline = &TrampolineStateChangedHandler; using var block = new BlockLiteral (trampoline, handler, typeof (NWConnectionGroup), nameof (TrampolineStateChangedHandler)); #else using var block = new BlockLiteral (); diff --git a/src/Network/NWEndpoint.cs b/src/Network/NWEndpoint.cs index ccb21c14341a..1f2298edbd08 100644 --- a/src/Network/NWEndpoint.cs +++ b/src/Network/NWEndpoint.cs @@ -35,7 +35,7 @@ namespace Network { public class NWEndpoint : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWEndpoint (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWEstablishmentReport.cs b/src/Network/NWEstablishmentReport.cs index f04b6fcb2a6d..6fa5da127fec 100644 --- a/src/Network/NWEstablishmentReport.cs +++ b/src/Network/NWEstablishmentReport.cs @@ -98,7 +98,7 @@ public void EnumerateResolutions (Action trampoline = &TrampolineResolutionEnumeratorHandler; - using var block = new BlockLiteral (trampoline, handler, typeof (NWEstablishmentReport),nameof (TrampolineResolutionEnumeratorHandler)); + using var block = new BlockLiteral (trampoline, handler, typeof (NWEstablishmentReport), nameof (TrampolineResolutionEnumeratorHandler)); #else using var block = new BlockLiteral (); block.SetupBlockUnsafe (static_ResolutionEnumeratorHandler, handler); diff --git a/src/Network/NWEthernetChannel.cs b/src/Network/NWEthernetChannel.cs index 1011665380b6..c761c8ea0668 100644 --- a/src/Network/NWEthernetChannel.cs +++ b/src/Network/NWEthernetChannel.cs @@ -18,10 +18,10 @@ using Foundation; using CoreFoundation; -using OS_nw_ethernet_channel=System.IntPtr; -using OS_nw_interface=System.IntPtr; -using OS_dispatch_data=System.IntPtr; -using OS_nw_parameters=System.IntPtr; +using OS_nw_ethernet_channel = System.IntPtr; +using OS_nw_interface = System.IntPtr; +using OS_dispatch_data = System.IntPtr; +using OS_nw_parameters = System.IntPtr; #if !NET @@ -48,7 +48,7 @@ namespace Network { public class NWEthernetChannel : NativeObject { [Preserve (Conditional = true)] - internal NWEthernetChannel (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWEthernetChannel (NativeHandle handle, bool owns) : base (handle, owns) { } [DllImport (Constants.NetworkLibrary)] static extern OS_nw_ethernet_channel nw_ethernet_channel_create (ushort ether_type, OS_nw_interface networkInterface); @@ -89,13 +89,13 @@ public NWEthernetChannel (ushort ethernetType, NWInterface networkInterface) [Mac (13,0)] #endif public NWEthernetChannel (ushort ethernetType, NWInterface networkInterface, NWParameters parameters) => - InitializeHandle (nw_ethernet_channel_create_with_parameters (ethernetType, + InitializeHandle (nw_ethernet_channel_create_with_parameters (ethernetType, networkInterface.GetNonNullHandle (nameof (networkInterface)), parameters.GetNonNullHandle (nameof (parameters)))); [DllImport (Constants.NetworkLibrary)] static extern void nw_ethernet_channel_start (OS_nw_ethernet_channel ethernet_channel); - public void Start () => nw_ethernet_channel_start (GetCheckedHandle ()); + public void Start () => nw_ethernet_channel_start (GetCheckedHandle ()); [DllImport (Constants.NetworkLibrary)] static extern void nw_ethernet_channel_cancel (OS_nw_ethernet_channel ethernet_channel); @@ -160,7 +160,7 @@ public void Send (ReadOnlySpan content, ushort vlanTag, string remoteAddre } [DllImport (Constants.NetworkLibrary)] - unsafe static extern void nw_ethernet_channel_set_receive_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral *handler); + unsafe static extern void nw_ethernet_channel_set_receive_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral* handler); #if !NET delegate void nw_ethernet_channel_receive_handler_t (IntPtr block, OS_dispatch_data content, ushort vlan_tag, IntPtr local_address, IntPtr remote_address); @@ -206,7 +206,7 @@ public void SetReceiveHandler (NWEthernetChannelReceiveDelegate handler) } [DllImport (Constants.NetworkLibrary)] - unsafe static extern void nw_ethernet_channel_set_state_changed_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral *handler); + unsafe static extern void nw_ethernet_channel_set_state_changed_handler (OS_nw_ethernet_channel ethernet_channel, /* [NullAllowed] */ BlockLiteral* handler); #if !NET delegate void nw_ethernet_channel_state_changed_handler_t (IntPtr block, NWEthernetChannelState state, IntPtr error); @@ -243,7 +243,7 @@ public void SetStateChangesHandler (Action handler) #endif nw_ethernet_channel_set_state_changed_handler (GetCheckedHandle (), &block); } - } + } #if NET [SupportedOSPlatform ("macos13.0")] @@ -262,7 +262,7 @@ public void SetStateChangesHandler (Action handler) #else [Mac (13,0)] #endif - public uint MaximumPayloadSize => nw_ethernet_channel_get_maximum_payload_size (GetCheckedHandle ()); + public uint MaximumPayloadSize => nw_ethernet_channel_get_maximum_payload_size (GetCheckedHandle ()); } } #endif diff --git a/src/Network/NWInterface.cs b/src/Network/NWInterface.cs index b37d41851a4d..5edce0ce0f53 100644 --- a/src/Network/NWInterface.cs +++ b/src/Network/NWInterface.cs @@ -33,7 +33,7 @@ namespace Network { public class NWInterface : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWInterface (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWInterface (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWInterface (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWParameters.cs b/src/Network/NWParameters.cs index 5e562febdd81..c12df72e7be5 100644 --- a/src/Network/NWParameters.cs +++ b/src/Network/NWParameters.cs @@ -36,7 +36,7 @@ namespace Network { public class NWParameters : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWParameters (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWParameters (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWParameters (NativeHandle handle, bool owns) : base (handle, owns) { } #endif @@ -222,7 +222,7 @@ public unsafe static NWParameters CreateUdp (Action? configur [NoiOS] #endif [DllImport (Constants.NetworkLibrary)] - unsafe static extern IntPtr nw_parameters_create_custom_ip (byte custom_ip_protocol_number, BlockLiteral *configure_ip); + unsafe static extern IntPtr nw_parameters_create_custom_ip (byte custom_ip_protocol_number, BlockLiteral* configure_ip); #if NET [SupportedOSPlatform ("macos")] diff --git a/src/Network/NWPath.cs b/src/Network/NWPath.cs index 84c4e1f5595c..8e8ccd3026b2 100644 --- a/src/Network/NWPath.cs +++ b/src/Network/NWPath.cs @@ -32,7 +32,7 @@ namespace Network { public class NWPath : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWPath (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWPath (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWPath (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWPrivacyContext.cs b/src/Network/NWPrivacyContext.cs index eef58bb15bfb..8a8eb745d2a9 100644 --- a/src/Network/NWPrivacyContext.cs +++ b/src/Network/NWPrivacyContext.cs @@ -31,7 +31,7 @@ public class NWPrivacyContext : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWPrivacyContext (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolDefinition.cs b/src/Network/NWProtocolDefinition.cs index f96c8cccceb6..95816b3cdda1 100644 --- a/src/Network/NWProtocolDefinition.cs +++ b/src/Network/NWProtocolDefinition.cs @@ -33,7 +33,7 @@ namespace Network { public class NWProtocolDefinition : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolDefinition (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolFramerOptions.cs b/src/Network/NWProtocolFramerOptions.cs index 7b49cca2d57d..eacf836029b3 100644 --- a/src/Network/NWProtocolFramerOptions.cs +++ b/src/Network/NWProtocolFramerOptions.cs @@ -22,7 +22,7 @@ using OS_nw_protocol_options = System.IntPtr; using NativeHandle = System.IntPtr; #else -using OS_nw_protocol_options=ObjCRuntime.NativeHandle; +using OS_nw_protocol_options = ObjCRuntime.NativeHandle; #endif namespace Network { diff --git a/src/Network/NWProtocolMetadata.cs b/src/Network/NWProtocolMetadata.cs index 93dbc81c74d4..e36314084129 100644 --- a/src/Network/NWProtocolMetadata.cs +++ b/src/Network/NWProtocolMetadata.cs @@ -58,7 +58,7 @@ public static NWProtocolMetadata CreateUdpMetadata () [Preserve (Conditional = true)] #if NET - internal NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolMetadata (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolOptions.cs b/src/Network/NWProtocolOptions.cs index c3d8267019ca..14c6f2692767 100644 --- a/src/Network/NWProtocolOptions.cs +++ b/src/Network/NWProtocolOptions.cs @@ -34,7 +34,7 @@ namespace Network { public class NWProtocolOptions : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolOptions (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProtocolStack.cs b/src/Network/NWProtocolStack.cs index d43e247558eb..8aaacdab0041 100644 --- a/src/Network/NWProtocolStack.cs +++ b/src/Network/NWProtocolStack.cs @@ -36,7 +36,7 @@ namespace Network { public class NWProtocolStack : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProtocolStack (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWProxyConfig.cs b/src/Network/NWProxyConfig.cs index 86c631dd7b37..57a790831af6 100644 --- a/src/Network/NWProxyConfig.cs +++ b/src/Network/NWProxyConfig.cs @@ -29,7 +29,7 @@ namespace Network { public class NWProxyConfig : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWProxyConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWRelayHop.cs b/src/Network/NWRelayHop.cs index d56f895f324a..c2c4018c9bb2 100644 --- a/src/Network/NWRelayHop.cs +++ b/src/Network/NWRelayHop.cs @@ -28,7 +28,7 @@ namespace Network { public class NWRelayHop : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWRelayHop (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Network/NWResolverConfig.cs b/src/Network/NWResolverConfig.cs index 0f0b69bec429..247554347975 100644 --- a/src/Network/NWResolverConfig.cs +++ b/src/Network/NWResolverConfig.cs @@ -30,7 +30,7 @@ public class NWResolverConfig : NativeObject { [Preserve (Conditional = true)] #if NET - internal NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) {} + internal NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #else public NWResolverConfig (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/ObjCRuntime/BackingField.cs b/src/ObjCRuntime/BackingField.cs index 8f85291feda5..88fcae65964e 100644 --- a/src/ObjCRuntime/BackingField.cs +++ b/src/ObjCRuntime/BackingField.cs @@ -46,8 +46,7 @@ namespace ObjCRuntime { - static class BackingField - { + static class BackingField { public static T Get (ref T value, IntPtr handle, Converter c) where T : class, INativeObject, IDisposable { diff --git a/src/ObjCRuntime/BindAs.cs b/src/ObjCRuntime/BindAs.cs index 2722caa1cd4a..35b10aede41c 100644 --- a/src/ObjCRuntime/BindAs.cs +++ b/src/ObjCRuntime/BindAs.cs @@ -37,7 +37,7 @@ static T Identity (T obj) return obj; } - unsafe static T[]? ConvertNSArrayToManagedArray (IntPtr nsarray, delegate* convert) where T: struct + unsafe static T []? ConvertNSArrayToManagedArray (IntPtr nsarray, delegate* convert) where T : struct { if (nsarray == IntPtr.Zero) return null; @@ -45,7 +45,7 @@ static T Identity (T obj) return ConvertNSArrayToManagedArray2 (nsarray, convert, &Identity); } - unsafe static IntPtr ConvertManagedArrayToNSArray (T[]? array, delegate* convert) where T: struct + unsafe static IntPtr ConvertManagedArrayToNSArray (T []? array, delegate* convert) where T : struct { if (array is null) return IntPtr.Zero; @@ -53,7 +53,7 @@ unsafe static IntPtr ConvertManagedArrayToNSArray (T[]? array, delegate* (array, &Identity, convert); } - unsafe static T[]? ConvertNSArrayToManagedArray2 (IntPtr nsarray, delegate* convert1, delegate* convert2) where T: struct + unsafe static T []? ConvertNSArrayToManagedArray2 (IntPtr nsarray, delegate* convert1, delegate* convert2) where T : struct { if (nsarray == IntPtr.Zero) return null; @@ -61,7 +61,7 @@ unsafe static IntPtr ConvertManagedArrayToNSArray (T[]? array, delegate* (nsarray, (ptr) => convert2 (convert1 (ptr))); } - unsafe static IntPtr ConvertManagedArrayToNSArray2 (T[]? array, delegate* convert1, delegate* convert2) where T: struct + unsafe static IntPtr ConvertManagedArrayToNSArray2 (T []? array, delegate* convert1, delegate* convert2) where T : struct { if (array is null) return IntPtr.Zero; @@ -90,14 +90,14 @@ unsafe static IntPtr ConvertManagedArrayToNSArray2 (T[]? array, delegate* (IntPtr handle, delegate* convert) where T: struct + unsafe static T? CreateNullable (IntPtr handle, delegate* convert) where T : struct { if (handle == IntPtr.Zero) return null; return convert (handle); } - unsafe static T? CreateNullable2 (IntPtr handle, delegate* convert1, delegate* convert2) where T: struct + unsafe static T? CreateNullable2 (IntPtr handle, delegate* convert1, delegate* convert2) where T : struct { if (handle == IntPtr.Zero) return null; diff --git a/src/ObjCRuntime/Blocks.cs b/src/ObjCRuntime/Blocks.cs index cb3b4091fbe3..2c3389e1c9a9 100644 --- a/src/ObjCRuntime/Blocks.cs +++ b/src/ObjCRuntime/Blocks.cs @@ -410,7 +410,7 @@ public object Target { } #if NET - public T GetDelegateForBlock () where T: System.MulticastDelegate + public T GetDelegateForBlock () where T : System.MulticastDelegate #else public T GetDelegateForBlock () where T : class #endif @@ -419,7 +419,7 @@ public T GetDelegateForBlock () where T : class } #if NET - public unsafe static T GetTarget (IntPtr block) where T: System.MulticastDelegate + public unsafe static T GetTarget (IntPtr block) where T : System.MulticastDelegate #else public unsafe static T GetTarget (IntPtr block) where T : class /* /* requires C# 7.3+: System.MulticastDelegate */ #endif @@ -443,9 +443,9 @@ public static bool IsManagedBlock (IntPtr block) // This method doesn't necessarily work with NativeAOT, but this is covered by the exception, because the managed static registrar is required for NativeAOT. // // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.Interfaces' in call to 'System.Type.GetInterfaces()'. The return value of method 'System.Reflection.MemberInfo.DeclaringType.get' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. - [UnconditionalSuppressMessage("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] // IL2062: Value passed to parameter 'interfaceType' of method 'System.Type.GetInterfaceMap(Type)' can not be statically determined and may not meet 'DynamicallyAccessedMembersAttribute' requirements. - [UnconditionalSuppressMessage("", "IL2062", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2062", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif static Type GetDelegateProxyType (MethodInfo minfo, uint token_ref, out MethodInfo baseMethod) { @@ -499,7 +499,7 @@ static Type GetDelegateProxyType (MethodInfo minfo, uint token_ref, out MethodIn [BindingImpl (BindingImplOptions.Optimizable)] unsafe static IntPtr GetBlockForFunctionPointer (MethodInfo delegateInvokeMethod, object @delegate, string signature) { - void* invokeFunctionPointer = (void *) delegateInvokeMethod.MethodHandle.GetFunctionPointer (); + void* invokeFunctionPointer = (void*) delegateInvokeMethod.MethodHandle.GetFunctionPointer (); if (signature is null) { if (!Runtime.DynamicRegistrationSupported) throw ErrorHelper.CreateError (8026, $"BlockLiteral.GetBlockForDelegate with a null signature is not supported when the dynamic registrar has been linked away (delegate type: {@delegate.GetType ().FullName})."); @@ -547,7 +547,7 @@ static IntPtr CreateBlockForDelegate (Delegate @delegate, Delegate delegateProxy // // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicFields' in call to 'System.Type.GetField(String, BindingFlags)'. The return value of method 'ObjCRuntime.BlockLiteral.GetDelegateProxyType(MethodInfo, UInt32, MethodInfo&)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. // IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.NonPublicMethods' in call to 'System.Type.GetMethod(String, BindingFlags)'. The return value of method 'ObjCRuntime.BlockLiteral.GetDelegateProxyType(MethodInfo, UInt32, MethodInfo&)' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to." - [UnconditionalSuppressMessage("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2075", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif internal static IntPtr GetBlockForDelegate (MethodInfo minfo, object @delegate, uint token_ref, string signature) { diff --git a/src/ObjCRuntime/Class.cs b/src/ObjCRuntime/Class.cs index 4135e6d8cb9d..1bfa062aebbb 100644 --- a/src/ObjCRuntime/Class.cs +++ b/src/ObjCRuntime/Class.cs @@ -537,7 +537,7 @@ internal static unsafe int FindMapIndex (Runtime.MTClassMap* array, int lo, int // // IL2026: Using member 'System.Reflection.Module.ResolveMethod(Int32)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Trimming changes metadata tokens. // IL2026: Using member 'System.Reflection.Module.ResolveType(Int32)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. Trimming changes metadata tokens. - [UnconditionalSuppressMessage("", "IL2026", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] + [UnconditionalSuppressMessage ("", "IL2026", Justification = "The APIs this method tries to access are marked by other means, so this is linker-safe.")] #endif static MemberInfo? ResolveTokenNonManagedStatic (Assembly assembly, Module? module, uint token) { diff --git a/src/ObjCRuntime/DelayedRegistrationAttribute.cs b/src/ObjCRuntime/DelayedRegistrationAttribute.cs index 097d486714f2..c1b57b383a01 100644 --- a/src/ObjCRuntime/DelayedRegistrationAttribute.cs +++ b/src/ObjCRuntime/DelayedRegistrationAttribute.cs @@ -29,8 +29,7 @@ namespace ObjCRuntime { [AttributeUsage (AttributeTargets.Assembly)] - public abstract class DelayedRegistrationAttribute : Attribute - { + public abstract class DelayedRegistrationAttribute : Attribute { public abstract bool Delay { get; } } } diff --git a/src/ObjCRuntime/Dlfcn.cs b/src/ObjCRuntime/Dlfcn.cs index a1b10999b496..725be061da61 100644 --- a/src/ObjCRuntime/Dlfcn.cs +++ b/src/ObjCRuntime/Dlfcn.cs @@ -56,8 +56,7 @@ static public class LibC { static public readonly IntPtr Handle = Dlfcn._dlopen (Constants.libcLibrary, 0); } #if HAS_OPENGLES - static public class OpenGLES - { + static public class OpenGLES { static public readonly IntPtr Handle = Dlfcn._dlopen (Constants.OpenGLESLibrary, 0); } #endif diff --git a/src/ObjCRuntime/INativeObject.cs b/src/ObjCRuntime/INativeObject.cs index f464c21fd741..aa4823b9642f 100644 --- a/src/ObjCRuntime/INativeObject.cs +++ b/src/ObjCRuntime/INativeObject.cs @@ -21,7 +21,7 @@ NativeHandle Handle { // The method will be implemented via custom linker step if the managed static registrar is used // for classes which have an (NativeHandle, bool) or (IntPtr, bool) constructor. // This method will be made public when the managed static registrar is used. - [MethodImpl(MethodImplOptions.NoInlining)] + [MethodImpl (MethodImplOptions.NoInlining)] internal static virtual INativeObject? _Xamarin_ConstructINativeObject (NativeHandle handle, bool owns) => null; #endif } diff --git a/src/ObjCRuntime/NativeHandle.cs b/src/ObjCRuntime/NativeHandle.cs index d9f1453b2e1b..9844e9d25e03 100644 --- a/src/ObjCRuntime/NativeHandle.cs +++ b/src/ObjCRuntime/NativeHandle.cs @@ -72,10 +72,10 @@ public static implicit operator NativeHandle (IntPtr value) public unsafe static explicit operator void* (NativeHandle value) { - return (void *) (IntPtr) value; + return (void*) (IntPtr) value; } - public unsafe static explicit operator NativeHandle (void * value) + public unsafe static explicit operator NativeHandle (void* value) { return new NativeHandle ((IntPtr) value); } diff --git a/src/ObjCRuntime/PlatformAvailability.cs b/src/ObjCRuntime/PlatformAvailability.cs index 41887c7773b8..9f455bfdcd26 100644 --- a/src/ObjCRuntime/PlatformAvailability.cs +++ b/src/ObjCRuntime/PlatformAvailability.cs @@ -568,7 +568,7 @@ public MacAttribute (byte major, byte minor, PlatformArchitecture arch) public MacAttribute (byte major, byte minor, byte subminor) #if NET - : base ((Platform)((ulong)major << 48 | (ulong)minor << 40 | (ulong)subminor << 32)) + : base ((Platform) ((ulong) major << 48 | (ulong) minor << 40 | (ulong) subminor << 32)) #else : this (major, minor, subminor, false) #endif diff --git a/src/ObjCRuntime/RegistrarHelper.cs b/src/ObjCRuntime/RegistrarHelper.cs index f5ba5b46b689..c145d6e8f844 100644 --- a/src/ObjCRuntime/RegistrarHelper.cs +++ b/src/ObjCRuntime/RegistrarHelper.cs @@ -69,7 +69,7 @@ internal static void Initialize () wrapper_types = new Dictionary (RuntimeTypeHandleEqualityComparer); } - static NativeHandle CreateCFArray (params string[]? values) + static NativeHandle CreateCFArray (params string []? values) { if (values is null) return NativeHandle.Zero; @@ -252,9 +252,9 @@ static NativeHandle ManagedArrayToNSArray (object array, bool retain) return NativeHandle.Zero; NSObject rv; - if (array is NSObject[] nsobjs) { + if (array is NSObject [] nsobjs) { rv = NSArray.FromNSObjects (nsobjs); - } else if (array is INativeObject[] inativeobjs) { + } else if (array is INativeObject [] inativeobjs) { rv = NSArray.FromNSObjects (inativeobjs); } else { throw new InvalidOperationException ($"Can't convert {array.GetType ()} to an NSArray."); // FIXME: better error @@ -265,7 +265,7 @@ static NativeHandle ManagedArrayToNSArray (object array, bool retain) return Runtime.RetainAndAutoreleaseNSObject (rv); } - unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string[]? value, ref string[]? copy) + unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string []? value, ref string []? copy) { if (ptr is not null) { value = NSArray.StringArrayFromHandle (*ptr); @@ -275,7 +275,7 @@ unsafe static void NSArray_string_native_to_managed (IntPtr* ptr, ref string[]? copy = value; } - unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string[] value, string[] copy, bool isOut) + unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string [] value, string [] copy, bool isOut) { if (ptr is null) return; @@ -301,7 +301,7 @@ unsafe static void NSArray_string_managed_to_native (IntPtr* ptr, string[] value *ptr = rv; } - unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T[]? value, ref T[]? copy) where T: class, INativeObject + unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T []? value, ref T []? copy) where T : class, INativeObject { if (ptr is not null) { value = NSArray.ArrayFromHandle (*ptr); @@ -311,7 +311,7 @@ unsafe static void NSArray_native_to_managed (IntPtr* ptr, ref T[]? value, re copy = value; } - unsafe static void NSArray_managed_to_native (IntPtr* ptr, T[] value, T[] copy, bool isOut) where T: class, INativeObject + unsafe static void NSArray_managed_to_native (IntPtr* ptr, T [] value, T [] copy, bool isOut) where T : class, INativeObject { if (ptr is null) { #if TRACE @@ -340,7 +340,7 @@ unsafe static void NSArray_managed_to_native (IntPtr* ptr, T[] value, T[] cop *ptr = rv; } - unsafe static void NSObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy) where T: NSObject + unsafe static void NSObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy) where T : NSObject { if (ptr is not null) { value = Runtime.GetNSObject (*ptr, owns: false); @@ -371,7 +371,7 @@ unsafe static void NSObject_managed_to_native (IntPtr* ptr, NSObject value, NSOb *ptr = rv; } - unsafe static void string_native_to_managed (NativeHandle *ptr, ref string? value, ref string? copy) + unsafe static void string_native_to_managed (NativeHandle* ptr, ref string? value, ref string? copy) { if (ptr is not null) { value = CFString.FromHandle (*ptr); @@ -381,7 +381,7 @@ unsafe static void string_native_to_managed (NativeHandle *ptr, ref string? valu copy = value; } - unsafe static void string_managed_to_native (NativeHandle *ptr, string value, string copy, bool isOut) + unsafe static void string_managed_to_native (NativeHandle* ptr, string value, string copy, bool isOut) { if (ptr is null) { #if TRACE @@ -402,7 +402,7 @@ unsafe static void string_managed_to_native (NativeHandle *ptr, string value, st *ptr = rv; } - unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy, RuntimeTypeHandle implementationType) where T: class, INativeObject + unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value, ref T? copy, RuntimeTypeHandle implementationType) where T : class, INativeObject { if (ptr is not null) { value = Runtime.GetINativeObject (*ptr, implementation: Type.GetTypeFromHandle (implementationType), forced_type: false, owns: false); @@ -412,7 +412,7 @@ unsafe static void INativeObject_native_to_managed (IntPtr* ptr, ref T? value copy = value; } - unsafe static void INativeObject_managed_to_native (IntPtr *ptr, INativeObject value, INativeObject copy, bool isOut) + unsafe static void INativeObject_managed_to_native (IntPtr* ptr, INativeObject value, INativeObject copy, bool isOut) { if (ptr is null) { #if TRACE diff --git a/src/ObjCRuntime/RequiredFrameworkAttribute.cs b/src/ObjCRuntime/RequiredFrameworkAttribute.cs index afc789075980..ac1b8cc56505 100644 --- a/src/ObjCRuntime/RequiredFrameworkAttribute.cs +++ b/src/ObjCRuntime/RequiredFrameworkAttribute.cs @@ -29,11 +29,10 @@ namespace ObjCRuntime { - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public class RequiredFrameworkAttribute : Attribute - { + [AttributeUsage (AttributeTargets.Assembly, AllowMultiple = true)] + public class RequiredFrameworkAttribute : Attribute { public string Name { get; private set; } - + public RequiredFrameworkAttribute (string name) { Name = name; diff --git a/src/ObjCRuntime/Runtime.CoreCLR.cs b/src/ObjCRuntime/Runtime.CoreCLR.cs index 3de830102738..f7a1f4cdf369 100644 --- a/src/ObjCRuntime/Runtime.CoreCLR.cs +++ b/src/ObjCRuntime/Runtime.CoreCLR.cs @@ -37,7 +37,7 @@ using Xamarin.Bundler; -using MonoObjectPtr=System.IntPtr; +using MonoObjectPtr = System.IntPtr; namespace ObjCRuntime { @@ -98,7 +98,7 @@ static void log_coreclr (string message) // Define VERBOSE_LOG at the top of this file to get all printfs [System.Diagnostics.Conditional ("VERBOSE_LOG")] - static void log_coreclr_render (string message, params object?[] argumentsToRender) + static void log_coreclr_render (string message, params object? [] argumentsToRender) { var args = new string [argumentsToRender.Length]; for (var i = 0; i < args.Length; i++) { @@ -212,7 +212,7 @@ internal static GCHandle CreateTrackingGCHandle (NSObject obj, IntPtr handle) unsafe { TrackedObjectInfo* tracked_info; fixed (void* ptr = info) - tracked_info = (TrackedObjectInfo *) ptr; + tracked_info = (TrackedObjectInfo*) ptr; tracked_info->Handle = handle; tracked_info->Flags = obj.FlagsInternal; obj.tracked_object_info = tracked_info; @@ -264,7 +264,7 @@ internal static void RegisterToggleReferenceCoreCLR (NSObject obj, IntPtr handle } // Returns a retained MonoObject. Caller must release. - [UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "This method is only called to retrieve the assembly where the entry point is, and the entry point is not trimmed away, so this is safe.")] + [UnconditionalSuppressMessage ("AssemblyLoadTrimming", "IL2026:RequiresUnreferencedCode", Justification = "This method is only called to retrieve the assembly where the entry point is, and the entry point is not trimmed away, so this is safe.")] static IntPtr FindAssembly (IntPtr assembly_name) { if (IsNativeAOT) @@ -306,7 +306,7 @@ static unsafe void SetPendingException (MonoObject* exception_obj) ObjectiveCMarshal.SetMessageSendPendingException (exc); } - unsafe static sbyte IsClassOfType (MonoObject *typeobj, TypeLookup match) + unsafe static sbyte IsClassOfType (MonoObject* typeobj, TypeLookup match) { var rv = IsClassOfType ((Type?) GetMonoObjectTarget (typeobj), match); return (sbyte) (rv ? 1 : 0); @@ -459,7 +459,7 @@ static IntPtr GetMonoObjectImpl (object obj) return null; unsafe { - MonoObject *monoobj = (MonoObject *) mobj; + MonoObject* monoobj = (MonoObject*) mobj; return GetGCHandleTarget (monoobj->GCHandle); } } @@ -469,7 +469,7 @@ static IntPtr GetMonoObjectImpl (object obj) static extern void xamarin_bridge_log_monoobject (IntPtr mono_object, string stack_trace); #endif - static IntPtr MarshalStructure (T value) where T: unmanaged + static IntPtr MarshalStructure (T value) where T : unmanaged { var destination = Marshal.AllocHGlobal (Marshal.SizeOf ()); @@ -564,10 +564,10 @@ static byte GetFlagsForNSObject (IntPtr gchandle) return (byte) obj.FlagsInternal; } - static unsafe MonoObject* GetMethodDeclaringType (MonoObject *mobj) + static unsafe MonoObject* GetMethodDeclaringType (MonoObject* mobj) { var method = (MethodBase) GetMonoObjectTarget (mobj)!; - return (MonoObject *) GetMonoObject (method.DeclaringType); + return (MonoObject*) GetMonoObject (method.DeclaringType); } static IntPtr ObjectGetType (MonoObjectPtr mobj) @@ -611,16 +611,16 @@ static unsafe IntPtr GetMethodSignature (MonoObject* methodobj) var parameterCount = parameters.Length; var rv = Marshal.AllocHGlobal (sizeof (MonoMethodSignature) + sizeof (MonoObjectPtr) * parameterCount); - MonoMethodSignature* signature = (MonoMethodSignature *) rv; + MonoMethodSignature* signature = (MonoMethodSignature*) rv; signature->Method = methodobj; xamarin_mono_object_retain (methodobj); signature->ParameterCount = parameterCount; - signature->ReturnType = (MonoObject *) GetMonoObject (GetMethodReturnType (method)); + signature->ReturnType = (MonoObject*) GetMonoObject (GetMethodReturnType (method)); MonoObject** mparams = &signature->Parameters; for (var i = 0; i < parameterCount; i++) { var p = parameters [i]; - mparams [i] = (MonoObject *) GetMonoObject (p.ParameterType); + mparams [i] = (MonoObject*) GetMonoObject (p.ParameterType); } return rv; @@ -638,14 +638,14 @@ static unsafe IntPtr GetMethodSignature (MonoObject* methodobj) return null; } - unsafe static IntPtr ClassGetNamespace (MonoObject *typeobj) + unsafe static IntPtr ClassGetNamespace (MonoObject* typeobj) { var type = (Type?) GetMonoObjectTarget (typeobj); var rv = type?.Namespace; return Marshal.StringToHGlobalAuto (rv); } - unsafe static IntPtr ClassGetName (MonoObject *typeobj) + unsafe static IntPtr ClassGetName (MonoObject* typeobj) { var type = (Type?) GetMonoObjectTarget (typeobj); var rv = type?.Name; @@ -658,7 +658,7 @@ unsafe static IntPtr ClassGetName (MonoObject *typeobj) var type = (Type?) GetMonoObjectTarget (typeobj); if (type?.IsByRef == true) type = type.GetElementType (); - return (MonoObject *) GetMonoObject (type); + return (MonoObject*) GetMonoObject (type); } static unsafe int SizeOf (MonoObject* typeobj) @@ -682,7 +682,7 @@ static int SizeOf (Type type) var method = (MethodBase) GetMonoObjectTarget (methodobj)!; var instance = GetMonoObjectTarget (instanceobj)!; var rv = InvokeMethod (method, instance, native_parameters); - return (MonoObject *) GetMonoObject (rv); + return (MonoObject*) GetMonoObject (rv); } // Return value: NULL or a MonoObject* that must be released with xamarin_mono_object_safe_release. @@ -744,7 +744,7 @@ static int SizeOf (Type type) log_coreclr ($" IsClass/IsInterface/IsNullable IsByRef: {isByRef} IsOut: {p.IsOut} ParameterType: {paramType}"); if (nativeParam != IntPtr.Zero) { unsafe { - MonoObject* mono_obj = (MonoObject *) nativeParam; + MonoObject* mono_obj = (MonoObject*) nativeParam; // dereference if it's a byref type if (isByRef) mono_obj = *(MonoObject**) mono_obj; @@ -788,7 +788,7 @@ static int SizeOf (Type type) try { rv = method.Invoke (instance, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, parameters, null); - } catch (TargetInvocationException tie) { + } catch (TargetInvocationException tie) { var ex = tie.InnerException ?? tie; // This will re-throw the original exception and preserve the stacktrace. ExceptionDispatchInfo.Capture (ex).Throw (); @@ -855,7 +855,7 @@ static unsafe IntPtr StringToUtf8 (MonoObject* obj) static unsafe MonoObject* NewString (IntPtr text) { - return (MonoObject *) GetMonoObject (Marshal.PtrToStringAuto (text)); + return (MonoObject*) GetMonoObject (Marshal.PtrToStringAuto (text)); } static unsafe MonoObject* CreateArray (MonoObject* typeobj, ulong elements) @@ -874,14 +874,14 @@ static unsafe ulong GetArrayLength (MonoObject* obj) return (ulong) array.Length; } - static unsafe void SetArrayObjectValue (MonoObject *arrayobj, ulong index, MonoObject *mobj) + static unsafe void SetArrayObjectValue (MonoObject* arrayobj, ulong index, MonoObject* mobj) { var array = (Array) GetMonoObjectTarget (arrayobj)!; var obj = GetMonoObjectTarget (mobj); array.SetValue (obj, (long) index); } - static unsafe void SetArrayStructValue (MonoObject *arrayobj, ulong index, MonoObject *typeobj, IntPtr valueptr) + static unsafe void SetArrayStructValue (MonoObject* arrayobj, ulong index, MonoObject* typeobj, IntPtr valueptr) { var array = (Array) GetMonoObjectTarget (arrayobj)!; var elementType = (Type) GetMonoObjectTarget (typeobj)!; @@ -893,14 +893,14 @@ static unsafe void SetArrayStructValue (MonoObject *arrayobj, ulong index, MonoO { var array = (Array) GetMonoObjectTarget (arrayobj)!; var obj = array.GetValue ((long) index); - return (MonoObject *) GetMonoObject (obj); + return (MonoObject*) GetMonoObject (obj); } static unsafe MonoObject* Box (MonoObject* typeobj, IntPtr value) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = Box (type, value); - return (MonoObject *) GetMonoObject (rv); + return (MonoObject*) GetMonoObject (rv); } static object? Box (Type type, IntPtr value) @@ -948,21 +948,21 @@ static bool IsNullable (Type type) return false; } - unsafe static sbyte IsByRef (MonoObject *typeobj) + unsafe static sbyte IsByRef (MonoObject* typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsByRef; return (sbyte) (rv ? 1 : 0); } - unsafe static sbyte IsValueType (MonoObject *typeobj) + unsafe static sbyte IsValueType (MonoObject* typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsValueType; return (sbyte) (rv ? 1 : 0); } - unsafe static sbyte IsEnum (MonoObject *typeobj) + unsafe static sbyte IsEnum (MonoObject* typeobj) { var type = (Type) GetMonoObjectTarget (typeobj)!; var rv = type.IsEnum; diff --git a/src/ObjCRuntime/Runtime.cs b/src/ObjCRuntime/Runtime.cs index 66aedf65af84..138e94b76e5a 100644 --- a/src/ObjCRuntime/Runtime.cs +++ b/src/ObjCRuntime/Runtime.cs @@ -177,8 +177,8 @@ internal enum InitializationFlags : int { /* unused = 0x08,*/ IsSimulator = 0x10, #if NET - IsCoreCLR = 0x20, - IsNativeAOT = 0x40, + IsCoreCLR = 0x20, + IsNativeAOT = 0x40, #endif } @@ -226,8 +226,7 @@ public bool IsSimulator { internal static unsafe InitializationOptions* options; #if NET - public static class ClassHandles - { + public static class ClassHandles { static NativeHandle unused; internal static unsafe void InitializeClassHandles (IntPtr* map) { @@ -238,7 +237,7 @@ internal static unsafe void InitializeClassHandles (IntPtr* map) // Rewriter uses those. // In the case of NO class handle rewriting, // this is a no-op - fixed (NativeHandle *ptr = &unused) { + fixed (NativeHandle* ptr = &unused) { SetHandle (-1, ptr, map); } } @@ -248,9 +247,9 @@ internal static unsafe void SetHandle (int index, NativeHandle* handle, IntPtr* { if (index < 0) return; - + var nativeHandle = map [index]; - *handle = (NativeHandle)nativeHandle; + *handle = (NativeHandle) nativeHandle; } } #endif @@ -297,10 +296,10 @@ internal static bool Initialized { [DllImport (Constants.libcLibrary)] unsafe static extern int _NSGetExecutablePath (byte* buf, int* bufsize); - unsafe static int _NSGetExecutablePath (byte[] buf, ref int bufsize) + unsafe static int _NSGetExecutablePath (byte [] buf, ref int bufsize) { fixed (byte* bufptr = buf) - return _NSGetExecutablePath (bufptr, (int *) Unsafe.AsPointer (ref bufsize)); + return _NSGetExecutablePath (bufptr, (int*) Unsafe.AsPointer (ref bufsize)); } #endif @@ -460,8 +459,7 @@ static bool ThreadPoolDispatcher (Func callback) static bool OnAssemblyRegistration (AssemblyName assembly_name) { if (AssemblyRegistration is not null) { - var args = new AssemblyRegistrationEventArgs - { + var args = new AssemblyRegistrationEventArgs { Register = true, AssemblyName = assembly_name }; @@ -786,14 +784,13 @@ public static void RegisterAssembly (Assembly a) var attributes = a.GetCustomAttributes (typeof (RequiredFrameworkAttribute), false); foreach (var attribute in attributes) { - var requiredFramework = (RequiredFrameworkAttribute)attribute; + var requiredFramework = (RequiredFrameworkAttribute) attribute; string libPath; string libName = requiredFramework.Name; if (libName.Contains (".dylib")) { libPath = ResourcesPath!; - } - else { + } else { libPath = FrameworksPath!; libPath = Path.Combine (libPath, libName); libName = libName.Replace (".frameworks", ""); @@ -802,7 +799,7 @@ public static void RegisterAssembly (Assembly a) if (Dlfcn.dlopen (libPath, 0) == IntPtr.Zero) throw new Exception ($"Unable to load required framework: '{requiredFramework.Name}'", - new Exception (Dlfcn.dlerror())); + new Exception (Dlfcn.dlerror ())); } attributes = a.GetCustomAttributes (typeof (DelayedRegistrationAttribute), false); @@ -1607,7 +1604,7 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM // If type is an NSObject, we prefer the NSObject lookup table if (instance is null && type != typeof (NSObject) && type.IsSubclassOf (typeof (NSObject))) { - instance = (T?)(INativeObject?) RegistrarHelper.ConstructNSObject (type, nativeHandle); + instance = (T?) (INativeObject?) RegistrarHelper.ConstructNSObject (type, nativeHandle); if (instance is not null && owns) { Runtime.TryReleaseINativeObject (instance); } @@ -2146,7 +2143,7 @@ static Type LookupINativeObjectImplementation (IntPtr ptr, Type target_type, Typ // For other registrars other than managed-static the generic parameter of ConstructNSObject is used // only to cast the return value so we can safely pass NSObject here to satisfy the constraints of the // generic parameter. - var rv = (T?)(INativeObject?) ConstructNSObject (ptr, implementation, MissingCtorResolution.ThrowConstructor1NotFound, sel, method_handle); + var rv = (T?) (INativeObject?) ConstructNSObject (ptr, implementation, MissingCtorResolution.ThrowConstructor1NotFound, sel, method_handle); if (owns) TryReleaseINativeObject (rv); return rv; diff --git a/src/ObjCRuntime/Runtime.mac.cs b/src/ObjCRuntime/Runtime.mac.cs index d8630d44ee69..56b55d9e03b8 100644 --- a/src/ObjCRuntime/Runtime.mac.cs +++ b/src/ObjCRuntime/Runtime.mac.cs @@ -54,9 +54,9 @@ public static string? FrameworksPath { public static string? ResourcesPath { get; set; } - + delegate void initialize_func (); - unsafe delegate sbyte *get_sbyteptr_func (); + unsafe delegate sbyte* get_sbyteptr_func (); #if !NET // There's a different implementation for other platforms + .NET macOS in Runtime.cs static volatile bool originalWorkingDirectoryIsSet; diff --git a/src/PassKit/PKCompat.cs b/src/PassKit/PKCompat.cs index d8e889f5785b..de76bf7fdb6f 100644 --- a/src/PassKit/PKCompat.cs +++ b/src/PassKit/PKCompat.cs @@ -87,7 +87,7 @@ public unsafe virtual void AuthorizeDisbursement (global::System.Action> AuthorizeDisbursementAsync () + public unsafe virtual Task> AuthorizeDisbursementAsync () { throw new InvalidOperationException (Constants.RemovedFromPassKit); } @@ -125,8 +125,7 @@ protected override void Dispose (bool disposing) #endif // NET [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("This class is removed.")] - public partial interface IPKDisbursementAuthorizationControllerDelegate : INativeObject, IDisposable - { + public partial interface IPKDisbursementAuthorizationControllerDelegate : INativeObject, IDisposable { void DidAuthorize (PKDisbursementAuthorizationController controller, PKDisbursementVoucher disbursementVoucher); void DidFinish (PKDisbursementAuthorizationController controller); } diff --git a/src/PdfKit/Enums.cs b/src/PdfKit/Enums.cs index cd3ff0ac0476..45cba05bb9cf 100644 --- a/src/PdfKit/Enums.cs +++ b/src/PdfKit/Enums.cs @@ -39,37 +39,37 @@ namespace PdfKit { [Native] [TV (18, 2)] public enum PdfActionNamedName : long { - None = 0, - NextPage = 1, + None = 0, + NextPage = 1, PreviousPage = 2, - FirstPage = 3, - LastPage = 4, - GoBack = 5, - GoForward = 6, - GoToPage = 7, - Find = 8, - Print = 9, - ZoomIn = 10, - ZoomOut = 11 + FirstPage = 3, + LastPage = 4, + GoBack = 5, + GoForward = 6, + GoToPage = 7, + Find = 8, + Print = 9, + ZoomIn = 10, + ZoomOut = 11 } [Native] [TV (18, 2)] public enum PdfWidgetControlType : long { - Unknown = -1, - PushButton = 0, + Unknown = -1, + PushButton = 0, RadioButton = 1, - CheckBox = 2 + CheckBox = 2 } [Native] [TV (18, 2)] public enum PdfLineStyle : long { - None = 0, - Square = 1, - Circle = 2, - Diamond = 3, - OpenArrow = 4, + None = 0, + Square = 1, + Circle = 2, + Diamond = 3, + OpenArrow = 4, ClosedArrow = 5 } @@ -79,28 +79,28 @@ public enum PdfMarkupType : long { Highlight = 0, StrikeOut = 1, Underline = 2, - Redact = 3, + Redact = 3, } [Native] [TV (18, 2)] public enum PdfTextAnnotationIconType : long { - Comment = 0, - Key = 1, - Note = 2, - Help = 3, + Comment = 0, + Key = 1, + Note = 2, + Help = 3, NewParagraph = 4, - Paragraph = 5, - Insert = 6 + Paragraph = 5, + Insert = 6 } [Native] [TV (18, 2)] public enum PdfBorderStyle : long { - Solid = 0, - Dashed = 1, - Beveled = 2, - Inset = 3, + Solid = 0, + Dashed = 1, + Beveled = 2, + Inset = 3, Underline = 4 } @@ -110,16 +110,16 @@ public enum PdfBorderStyle : long { [Unavailable (PlatformName.MacCatalyst)] [Native] public enum PdfPrintScalingMode : long { - None = 0, - ToFit = 1, + None = 0, + ToFit = 1, DownToFit = 2 } [Native] [TV (18, 2)] public enum PdfDocumentPermissions : long { - None = 0, - User = 1, + None = 0, + User = 1, Owner = 2 } @@ -127,36 +127,36 @@ public enum PdfDocumentPermissions : long { [TV (18, 2)] public enum PdfDisplayBox : long { Media = 0, - Crop = 1, + Crop = 1, Bleed = 2, - Trim = 3, - Art = 4 + Trim = 3, + Art = 4 } [Native] [TV (18, 2)] public enum PdfDisplayMode : long { - SinglePage = 0, + SinglePage = 0, SinglePageContinuous = 1, - TwoUp = 2, - TwoUpContinuous = 3 + TwoUp = 2, + TwoUpContinuous = 3 } [Flags] [Native] [TV (18, 2)] public enum PdfAreaOfInterest : long { - NoArea = 0, - PageArea = 1 << 0, - TextArea = 1 << 1, + NoArea = 0, + PageArea = 1 << 0, + TextArea = 1 << 1, AnnotationArea = 1 << 2, - LinkArea = 1 << 3, - ControlArea = 1 << 4, - TextFieldArea = 1 << 5, - IconArea = 1 << 6, - PopupArea = 1 << 7, - ImageArea = 1 << 8, - [iOS (15,0), MacCatalyst (15,0)] + LinkArea = 1 << 3, + ControlArea = 1 << 4, + TextFieldArea = 1 << 5, + IconArea = 1 << 6, + PopupArea = 1 << 7, + ImageArea = 1 << 8, + [iOS (15, 0), MacCatalyst (15, 0)] AnyArea = Int64.MaxValue, } diff --git a/src/PhotosUI/PHEnums.cs b/src/PhotosUI/PHEnums.cs index 8753917b1c49..5673e478f07b 100644 --- a/src/PhotosUI/PHEnums.cs +++ b/src/PhotosUI/PHEnums.cs @@ -14,7 +14,9 @@ public enum PHLivePhotoViewPlaybackStyle : long { } #if MONOMAC - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] [Native] public enum PHLivePhotoViewContentMode : long { AspectFit, diff --git a/src/QuickLook/Thumbnail.cs b/src/QuickLook/Thumbnail.cs index fa43d8107ead..8f7f0f0d2c23 100644 --- a/src/QuickLook/Thumbnail.cs +++ b/src/QuickLook/Thumbnail.cs @@ -52,7 +52,7 @@ public static partial class QLThumbnailImage { #else [Deprecated (PlatformName.MacOSX, 15, 0, message: "Use the QuickLookThumbnailing framework instead for creating thumbnails for files.")] #endif - [DllImport(Constants.QuickLookLibrary)] + [DllImport (Constants.QuickLookLibrary)] extern static /* CGImageRef */ IntPtr QLThumbnailImageCreate (/* CFAllocatorRef */ IntPtr allocator, /* CFUrlRef */ IntPtr url, CGSize maxThumbnailSize, /* CFDictionaryRef */ IntPtr options); #if NET @@ -76,12 +76,12 @@ public static partial class QLThumbnailImage { dictionary.LowlevelSetObject ((NSNumber) scaleFactor, OptionScaleFactorKey.Handle); dictionary.LowlevelSetObject (iconMode ? CFBoolean.TrueHandle : CFBoolean.FalseHandle, OptionIconModeKey.Handle); } - + var handle = QLThumbnailImageCreate (IntPtr.Zero, url.Handle, maxThumbnailSize, dictionary.GetHandle ()); GC.KeepAlive (dictionary); if (handle != IntPtr.Zero) return new CGImage (handle, true); - + return null; } } diff --git a/src/SceneKit/Defs.cs b/src/SceneKit/Defs.cs index 8f1d6da893bf..8ebb75bc6fdc 100644 --- a/src/SceneKit/Defs.cs +++ b/src/SceneKit/Defs.cs @@ -276,10 +276,12 @@ public enum SCNAntialiasingMode : ulong { Multisampling2X, Multisampling4X, #if MONOMAC || __MACCATALYST__ - [NoiOS][NoTV] + [NoiOS] + [NoTV] [NoMacCatalyst] Multisampling8X, - [NoiOS][NoTV] + [NoiOS] + [NoTV] [NoMacCatalyst] Multisampling16X, #endif @@ -361,11 +363,17 @@ public enum SCNRenderingApi : ulong { [NoMac] OpenGLES2, #else - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] OpenGLLegacy, - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] OpenGLCore32, - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] OpenGLCore41, #endif } diff --git a/src/SceneKit/SCNMatrix4_dotnet.cs b/src/SceneKit/SCNMatrix4_dotnet.cs index ffb1efc0484d..6f685e707d19 100644 --- a/src/SceneKit/SCNMatrix4_dotnet.cs +++ b/src/SceneKit/SCNMatrix4_dotnet.cs @@ -53,7 +53,7 @@ namespace SceneKit { /// [Serializable] public struct SCNMatrix4 : IEquatable { -#region Fields + #region Fields /* * SCNMatrix4 is defined like this for iOS, tvOS and watchOS: @@ -104,9 +104,9 @@ public struct SCNMatrix4 : IEquatable { /// public readonly static SCNMatrix4 Identity = new SCNMatrix4 (SCNVector4.UnitX, SCNVector4.UnitY, SCNVector4.UnitZ, SCNVector4.UnitW); -#endregion + #endregion -#region Constructors + #region Constructors /// /// Constructs a new instance. @@ -162,11 +162,11 @@ public SCNMatrix4 (CoreAnimation.CATransform3D transform) Column3 = new SCNVector4 ((pfloat) transform.M41, (pfloat) transform.M42, (pfloat) transform.M43, (pfloat) transform.M44); } -#endregion + #endregion -#region Public Members + #region Public Members -#region Properties + #region Properties /// /// The determinant of this matrix @@ -315,11 +315,11 @@ public SCNVector4 Row3 { /// public pfloat M44 { get { return Column3.W; } set { Column3.W = value; } } -#endregion + #endregion -#region Instance + #region Instance -#region public void Invert() + #region public void Invert() /// /// Converts this instance into its inverse. @@ -329,9 +329,9 @@ public void Invert () this = SCNMatrix4.Invert (this); } -#endregion + #endregion -#region public void Transpose() + #region public void Transpose() /// /// Converts this instance into its transpose. @@ -341,13 +341,13 @@ public void Transpose () this = SCNMatrix4.Transpose (this); } -#endregion + #endregion -#endregion + #endregion -#region Static + #region Static -#region CreateFromColumns + #region CreateFromColumns public static SCNMatrix4 CreateFromColumns (SCNVector4 column0, SCNVector4 column1, SCNVector4 column2, SCNVector4 column3) { @@ -368,9 +368,9 @@ public static void CreateFromColumns (SCNVector4 column0, SCNVector4 column1, SC result.Column3 = column3; } -#endregion + #endregion -#region CreateFromAxisAngle + #region CreateFromAxisAngle /// /// Build a rotation matrix from the specified axis/angle rotation. @@ -424,9 +424,9 @@ static void CreateFromAxisAngle (float x, float y, float z, float angle, out SCN var m33 = t * z * z + cos; result = new SCNMatrix4 ( - m11, m21, m31, 0.0f, - m12, m22, m32, 0.0f, - m13, m23, m33, 0.0f, + m11, m21, m31, 0.0f, + m12, m22, m32, 0.0f, + m13, m23, m33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } @@ -455,9 +455,9 @@ static void CreateFromAxisAngle (double x, double y, double z, double angle, out var m33 = (pfloat) (t * z * z + cos); result = new SCNMatrix4 ( - m11, m21, m31, 0.0f, - m12, m22, m32, 0.0f, - m13, m23, m33, 0.0f, + m11, m21, m31, 0.0f, + m12, m22, m32, 0.0f, + m13, m23, m33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } @@ -474,9 +474,9 @@ public static SCNMatrix4 CreateFromAxisAngle (SCNVector3 axis, pfloat angle) return result; } -#endregion + #endregion -#region CreateRotation[XYZ] + #region CreateRotation[XYZ] /// /// Builds a rotation matrix for a rotation around the x-axis. @@ -489,10 +489,10 @@ public static void CreateRotationX (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - 1, 0, 0, 0, - 0, cos, -sin, 0, - 0, sin, cos, 0, - 0, 0, 0, 1); + 1, 0, 0, 0, + 0, cos, -sin, 0, + 0, sin, cos, 0, + 0, 0, 0, 1); } /// @@ -518,10 +518,10 @@ public static void CreateRotationY (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - cos, 0, sin, 0, - 0, 1, 0, 0, - -sin, 0, cos, 0, - 0, 0, 0, 1); + cos, 0, sin, 0, + 0, 1, 0, 0, + -sin, 0, cos, 0, + 0, 0, 0, 1); } /// @@ -547,10 +547,10 @@ public static void CreateRotationZ (pfloat angle, out SCNMatrix4 result) pfloat sin = (pfloat) System.Math.Sin (angle); result = new SCNMatrix4 ( - cos, -sin, 0, 0, - sin, cos, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); + cos, -sin, 0, 0, + sin, cos, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1); } /// @@ -565,9 +565,9 @@ public static SCNMatrix4 CreateRotationZ (pfloat angle) return result; } -#endregion + #endregion -#region CreateTranslation + #region CreateTranslation /// /// Creates a translation matrix. @@ -621,9 +621,9 @@ public static SCNMatrix4 CreateTranslation (SCNVector3 vector) return result; } -#endregion + #endregion -#region CreateOrthographic + #region CreateOrthographic /// /// Creates an orthographic projection matrix. @@ -653,9 +653,9 @@ public static SCNMatrix4 CreateOrthographic (pfloat width, pfloat height, pfloat return result; } -#endregion + #endregion -#region CreateOrthographicOffCenter + #region CreateOrthographicOffCenter /// /// Creates an orthographic projection matrix. @@ -702,9 +702,9 @@ public static SCNMatrix4 CreateOrthographicOffCenter (pfloat left, pfloat right, return result; } -#endregion + #endregion -#region CreatePerspectiveFieldOfView + #region CreatePerspectiveFieldOfView /// /// Creates a perspective projection matrix. @@ -770,9 +770,9 @@ public static SCNMatrix4 CreatePerspectiveFieldOfView (pfloat fovy, pfloat aspec return result; } -#endregion + #endregion -#region CreatePerspectiveOffCenter + #region CreatePerspectiveOffCenter /// /// Creates a perspective projection matrix. @@ -809,10 +809,10 @@ public static void CreatePerspectiveOffCenter (pfloat left, pfloat right, pfloat pfloat d = -(2.0f * zFar * zNear) / (zFar - zNear); result = new SCNMatrix4 ( - x, 0, a, 0, - 0, y, b, 0, - 0, 0, c, d, - 0, 0, -1, 0); + x, 0, a, 0, + 0, y, b, 0, + 0, 0, c, d, + 0, 0, -1, 0); } /// @@ -840,9 +840,9 @@ public static SCNMatrix4 CreatePerspectiveOffCenter (pfloat left, pfloat right, return result; } -#endregion + #endregion -#region Scale Functions + #region Scale Functions /// /// Build a scaling matrix @@ -880,9 +880,9 @@ public static SCNMatrix4 Scale (pfloat x, pfloat y, pfloat z) 0, 0, 0, 1); } -#endregion + #endregion -#region Rotation Functions + #region Rotation Functions /// /// Build a rotation matrix from a quaternion @@ -913,9 +913,9 @@ public static SCNMatrix4 Rotate (Quaterniond q) CreateFromAxisAngle (axis, angle, out result); return result; } -#endregion + #endregion -#region Camera Helper Functions + #region Camera Helper Functions /// /// Build a world space to camera space matrix @@ -931,9 +931,9 @@ public static SCNMatrix4 LookAt (SCNVector3 eye, SCNVector3 target, SCNVector3 u SCNVector3 y = SCNVector3.Normalize (SCNVector3.Cross (z, x)); SCNMatrix4 rot = new SCNMatrix4 ( - x.X, x.Y, x.Z, 0.0f, - y.X, y.Y, y.Z, 0.0f, - z.X, z.Y, z.Z, 0.0f, + x.X, x.Y, x.Z, 0.0f, + y.X, y.Y, y.Z, 0.0f, + z.X, z.Y, z.Z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); SCNMatrix4 trans = SCNMatrix4.CreateTranslation (-eye); @@ -959,9 +959,9 @@ public static SCNMatrix4 LookAt (pfloat eyeX, pfloat eyeY, pfloat eyeZ, pfloat t return LookAt (new SCNVector3 (eyeX, eyeY, eyeZ), new SCNVector3 (targetX, targetY, targetZ), new SCNVector3 (upX, upY, upZ)); } -#endregion + #endregion -#region Multiply Functions + #region Multiply Functions #if XAMCORE_5_0 /// @@ -987,7 +987,7 @@ public static SCNMatrix4 LookAt (pfloat eyeX, pfloat eyeY, pfloat eyeZ, pfloat t #if XAMCORE_5_0 public static SCNMatrix4 Mult (SCNMatrix4 firstTransformation, SCNMatrix4 secondTransformation) #else - public static SCNMatrix4 Mult(SCNMatrix4 left, SCNMatrix4 right) + public static SCNMatrix4 Mult (SCNMatrix4 left, SCNMatrix4 right) #endif { SCNMatrix4 result; @@ -1024,7 +1024,7 @@ public static SCNMatrix4 Mult(SCNMatrix4 left, SCNMatrix4 right) #if XAMCORE_5_0 public static void Mult (ref SCNMatrix4 firstTransformation, ref SCNMatrix4 secondTransformation, out SCNMatrix4 result) #else - public static void Mult(ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) + public static void Mult (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) #endif { // the matrices are reversed: https://github.com/xamarin/xamarin-macios/issues/15094#issuecomment-1139699662 @@ -1038,7 +1038,7 @@ public static void Mult(ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix // Multiply two matrices in the order you'd expect (left * right). static void MatrixMultiply (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMatrix4 result) { - result = new SCNMatrix4( + result = new SCNMatrix4 ( left.Column0.X * right.Column0.X + left.Column1.X * right.Column0.Y + left.Column2.X * right.Column0.Z + left.Column3.X * right.Column0.W, left.Column0.X * right.Column1.X + left.Column1.X * right.Column1.Y + left.Column2.X * right.Column1.Z + left.Column3.X * right.Column1.W, left.Column0.X * right.Column2.X + left.Column1.X * right.Column2.Y + left.Column2.X * right.Column2.Z + left.Column3.X * right.Column2.W, @@ -1060,9 +1060,9 @@ static void MatrixMultiply (ref SCNMatrix4 left, ref SCNMatrix4 right, out SCNMa left.Column0.W * right.Column3.X + left.Column1.W * right.Column3.Y + left.Column2.W * right.Column3.Z + left.Column3.W * right.Column3.W); } -#endregion + #endregion -#region Invert Functions + #region Invert Functions static bool InvertSoftware (SCNMatrix4 matrix, out SCNMatrix4 result) { @@ -1094,9 +1094,9 @@ static bool InvertSoftware (SCNMatrix4 matrix, out SCNMatrix4 result) #endif { result = new SCNMatrix4 (pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, - pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN); + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN, + pfloat.NaN, pfloat.NaN, pfloat.NaN, pfloat.NaN); return false; } @@ -1154,9 +1154,9 @@ public static SCNMatrix4 Invert (SCNMatrix4 matrix) return inverse; } -#endregion + #endregion -#region Transpose + #region Transpose /// /// Calculate the transpose of the given matrix @@ -1179,11 +1179,11 @@ public static void Transpose (ref SCNMatrix4 mat, out SCNMatrix4 result) result = new SCNMatrix4 (mat.Column0, mat.Column1, mat.Column2, mat.Column3); } -#endregion + #endregion -#endregion + #endregion -#region Operators + #region Operators /// /// Matrix multiplication @@ -1218,11 +1218,11 @@ public static void Transpose (ref SCNMatrix4 mat, out SCNMatrix4 result) return !left.Equals (right); } -#endregion + #endregion -#region Overrides + #region Overrides -#region public override string ToString() + #region public override string ToString() /// /// Returns a System.String that represents the current SCNMatrix4. @@ -1233,9 +1233,9 @@ public override string ToString () return String.Format ("{0}\n{1}\n{2}\n{3}", Row0, Row1, Row2, Row3); } -#endregion + #endregion -#region public override int GetHashCode() + #region public override int GetHashCode() /// /// Returns the hashcode for this instance. @@ -1243,12 +1243,12 @@ public override string ToString () /// A System.Int32 containing the unique hashcode for this instance. public override int GetHashCode () { - return HashCode.Combine(Column0, Column1, Column2, Column3); + return HashCode.Combine (Column0, Column1, Column2, Column3); } -#endregion + #endregion -#region public override bool Equals(object obj) + #region public override bool Equals(object obj) /// /// Indicates whether this instance and a specified object are equal. @@ -1263,13 +1263,13 @@ public override bool Equals (object? obj) return this.Equals ((SCNMatrix4) obj); } -#endregion + #endregion -#endregion + #endregion -#endregion + #endregion -#region IEquatable Members + #region IEquatable Members /// Indicates whether the current matrix is equal to another matrix. /// An matrix to compare with this matrix. @@ -1283,17 +1283,17 @@ public bool Equals (SCNMatrix4 other) Column3 == other.Column3; } -#endregion + #endregion static void ToAxisAngle (Quaternion q, out Vector3 axis, out float angle) { if (q.W > 1.0f) - q = Quaternion.Normalize (q); + q = Quaternion.Normalize (q); angle = 2.0f * (float) System.Math.Acos (q.W); // angle var den = (float) System.Math.Sqrt (1.0 - q.W * q.W); if (den > 0.0001f) { - axis = new Vector3(q.X, q.Y, q.Z) / den; + axis = new Vector3 (q.X, q.Y, q.Z) / den; } else { // This occurs when the angle is zero. // Not a problem: just set an arbitrary normalized axis. diff --git a/src/SceneKit/SCNQuaternion.cs b/src/SceneKit/SCNQuaternion.cs index 24c45a7529e1..a71754c5f07c 100644 --- a/src/SceneKit/SCNQuaternion.cs +++ b/src/SceneKit/SCNQuaternion.cs @@ -60,10 +60,10 @@ namespace SceneKit { /// Represents a Quaternion. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -102,7 +102,7 @@ public SCNQuaternion (pfloat x, pfloat y, pfloat z, pfloat w) public SCNQuaternion (ref Matrix3 matrix) { #if NET - double scale = System.Math.Pow (matrix.GetDeterminant (), 1.0d / 3.0d); + double scale = System.Math.Pow (matrix.GetDeterminant (), 1.0d / 3.0d); #else double scale = System.Math.Pow (matrix.Determinant, 1.0d / 3.0d); #endif @@ -121,10 +121,10 @@ public SCNQuaternion (ref Matrix3 matrix) } #if NET - public SCNQuaternion (Quaternion quaternion) - : this (quaternion.X, quaternion.Y, quaternion.Z, quaternion.W) - { - } + public SCNQuaternion (Quaternion quaternion) + : this (quaternion.X, quaternion.Y, quaternion.Z, quaternion.W) + { + } #else public SCNQuaternion (Quaternion openTkQuaternion) : this (new SCNVector3 (openTkQuaternion.XYZ), openTkQuaternion.W) { diff --git a/src/SceneKit/SCNVector3.cs b/src/SceneKit/SCNVector3.cs index 19c4abf1c243..5242ae663659 100644 --- a/src/SceneKit/SCNVector3.cs +++ b/src/SceneKit/SCNVector3.cs @@ -61,10 +61,10 @@ namespace SceneKit { /// The Vector3 structure is suitable for interoperation with unmanaged code requiring three consecutive floats. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -771,17 +771,17 @@ public static SCNVector3 TransformVector (SCNVector3 vec, SCNMatrix4 mat) public static void TransformVector (ref SCNVector3 vec, ref SCNMatrix4 mat, out SCNVector3 result) { #if NET - result.X = vec.X * mat.Row0.X + - vec.Y * mat.Row0.Y + - vec.Z * mat.Row0.Z; + result.X = vec.X * mat.Row0.X + + vec.Y * mat.Row0.Y + + vec.Z * mat.Row0.Z; - result.Y = vec.X * mat.Row1.X + - vec.Y * mat.Row1.Y + - vec.Z * mat.Row1.Z; + result.Y = vec.X * mat.Row1.X + + vec.Y * mat.Row1.Y + + vec.Z * mat.Row1.Z; - result.Z = vec.X * mat.Row2.X + - vec.Y * mat.Row2.Y + - vec.Z * mat.Row2.Z; + result.Z = vec.X * mat.Row2.X + + vec.Y * mat.Row2.Y + + vec.Z * mat.Row2.Z; #else result.X = vec.X * mat.Row0.X + vec.Y * mat.Row1.X + @@ -803,7 +803,7 @@ public static void TransformVector (ref SCNVector3 vec, ref SCNMatrix4 mat, out /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// - /// The column-based normal to transform + /// The column-based normal to transform /// The desired transformation /// The transformed normal #else @@ -828,7 +828,7 @@ public static SCNVector3 TransformNormal (SCNVector3 norm, SCNMatrix4 mat) /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// - /// The column-based normal to transform + /// The column-based normal to transform /// The desired transformation /// The transformed normal #else @@ -853,7 +853,7 @@ public static void TransformNormal (ref SCNVector3 norm, ref SCNMatrix4 mat, out /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// - /// The column-based normal to transform + /// The column-based normal to transform /// The inverse of the desired transformation /// The transformed normal #else @@ -878,7 +878,7 @@ public static SCNVector3 TransformNormalInverse (SCNVector3 norm, SCNMatrix4 inv /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// - /// The column-based normal to transform + /// The column-based normal to transform /// The inverse of the desired transformation /// The transformed normal #else @@ -894,17 +894,17 @@ public static SCNVector3 TransformNormalInverse (SCNVector3 norm, SCNMatrix4 inv public static void TransformNormalInverse (ref SCNVector3 norm, ref SCNMatrix4 invMat, out SCNVector3 result) { #if NET - result.X = norm.X * invMat.Column0.X + - norm.Y * invMat.Column0.Y + - norm.Z * invMat.Column0.Z; + result.X = norm.X * invMat.Column0.X + + norm.Y * invMat.Column0.Y + + norm.Z * invMat.Column0.Z; - result.Y = norm.X * invMat.Column1.X + - norm.Y * invMat.Column1.Y + - norm.Z * invMat.Column1.Z; + result.Y = norm.X * invMat.Column1.X + + norm.Y * invMat.Column1.Y + + norm.Z * invMat.Column1.Z; - result.Z = norm.X * invMat.Column2.X + - norm.Y * invMat.Column2.Y + - norm.Z * invMat.Column2.Z; + result.Z = norm.X * invMat.Column2.X + + norm.Y * invMat.Column2.Y + + norm.Z * invMat.Column2.Z; #else result.X = norm.X * invMat.Row0.X + norm.Y * invMat.Row0.Y + @@ -922,7 +922,7 @@ public static void TransformNormalInverse (ref SCNVector3 norm, ref SCNMatrix4 i #if NET /// Transform a Position by the given Matrix - /// The column-based position to transform + /// The column-based position to transform /// The desired transformation /// The transformed position #else @@ -939,7 +939,7 @@ public static SCNVector3 TransformPosition (SCNVector3 pos, SCNMatrix4 mat) #if NET /// Transform a Position by the given Matrix - /// The column-based position to transform + /// The column-based position to transform /// The desired transformation /// The transformed position #else @@ -951,20 +951,20 @@ public static SCNVector3 TransformPosition (SCNVector3 pos, SCNMatrix4 mat) public static void TransformPosition (ref SCNVector3 pos, ref SCNMatrix4 mat, out SCNVector3 result) { #if NET - result.X = mat.Row0.X * pos.X + - mat.Row0.Y * pos.Y + - mat.Row0.Z * pos.Z + - mat.Row0.W; - - result.Y = mat.Row1.X * pos.X + - mat.Row1.Y * pos.Y + - mat.Row1.Z * pos.Z + - mat.Row1.W; - - result.Z = mat.Row2.X * pos.X + - mat.Row2.Y * pos.Y + - mat.Row2.Z * pos.Z + - mat.Row2.W; + result.X = mat.Row0.X * pos.X + + mat.Row0.Y * pos.Y + + mat.Row0.Z * pos.Z + + mat.Row0.W; + + result.Y = mat.Row1.X * pos.X + + mat.Row1.Y * pos.Y + + mat.Row1.Z * pos.Z + + mat.Row1.W; + + result.Z = mat.Row2.X * pos.X + + mat.Row2.Y * pos.Y + + mat.Row2.Z * pos.Z + + mat.Row2.W; #else result.X = pos.X * mat.Row0.X + pos.Y * mat.Row1.X + @@ -985,7 +985,7 @@ public static void TransformPosition (ref SCNVector3 pos, ref SCNMatrix4 mat, ou #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -1002,7 +1002,7 @@ public static SCNVector4 Transform (SCNVector3 vec, SCNMatrix4 mat) #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else diff --git a/src/SceneKit/SCNVector4.cs b/src/SceneKit/SCNVector4.cs index e28a85ffbe38..5e95a1576bd9 100644 --- a/src/SceneKit/SCNVector4.cs +++ b/src/SceneKit/SCNVector4.cs @@ -60,10 +60,10 @@ namespace SceneKit { /// The Vector4 structure is suitable for interoperation with unmanaged code requiring four consecutive floats. /// #if NET - [SupportedOSPlatform ("ios")] - [SupportedOSPlatform ("maccatalyst")] - [SupportedOSPlatform ("macos")] - [SupportedOSPlatform ("tvos")] + [SupportedOSPlatform ("ios")] + [SupportedOSPlatform ("maccatalyst")] + [SupportedOSPlatform ("macos")] + [SupportedOSPlatform ("tvos")] #endif [Serializable] [StructLayout (LayoutKind.Sequential)] @@ -836,7 +836,7 @@ public static void BaryCentric (ref SCNVector4 a, ref SCNVector4 b, ref SCNVecto #if NET /// Transform a Vector by the given Matrix - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -853,7 +853,7 @@ public static SCNVector4 Transform (SCNVector4 vec, SCNMatrix4 mat) #if NET /// Transform a Vector by the given Matrix. - /// The column vector to transform + /// The column vector to transform /// The desired transformation /// The transformed vector #else @@ -865,25 +865,25 @@ public static SCNVector4 Transform (SCNVector4 vec, SCNMatrix4 mat) public static void Transform (ref SCNVector4 vec, ref SCNMatrix4 mat, out SCNVector4 result) { #if NET - result.X = vec.X * mat.Column0.X + - vec.Y * mat.Column1.X + - vec.Z * mat.Column2.X + - vec.W * mat.Column3.X; - - result.Y = vec.X * mat.Column0.Y + - vec.Y * mat.Column1.Y + - vec.Z * mat.Column2.Y + - vec.W * mat.Column3.Y; - - result.Z = vec.X * mat.Column0.Z + - vec.Y * mat.Column1.Z + - vec.Z * mat.Column2.Z + - vec.W * mat.Column3.Z; - - result.W = vec.X * mat.Column0.W + - vec.Y * mat.Column1.W + - vec.Z * mat.Column2.W + - vec.W * mat.Column3.W; + result.X = vec.X * mat.Column0.X + + vec.Y * mat.Column1.X + + vec.Z * mat.Column2.X + + vec.W * mat.Column3.X; + + result.Y = vec.X * mat.Column0.Y + + vec.Y * mat.Column1.Y + + vec.Z * mat.Column2.Y + + vec.W * mat.Column3.Y; + + result.Z = vec.X * mat.Column0.Z + + vec.Y * mat.Column1.Z + + vec.Z * mat.Column2.Z + + vec.W * mat.Column3.Z; + + result.W = vec.X * mat.Column0.W + + vec.Y * mat.Column1.W + + vec.Z * mat.Column2.W + + vec.W * mat.Column3.W; #else result.X = vec.X * mat.Row0.X + vec.Y * mat.Row1.X + diff --git a/src/Security/Authorization.cs b/src/Security/Authorization.cs index 3b62567fedb2..da53d2a4d823 100644 --- a/src/Security/Authorization.cs +++ b/src/Security/Authorization.cs @@ -48,21 +48,21 @@ namespace Security { #endif // Untyped enum in ObjC public enum AuthorizationStatus { - Success = 0, - InvalidSet = -60001, - InvalidRef = -60002, - InvalidTag = -60003, - InvalidPointer = -60004, - Denied = -60005, - Canceled = -60006, - InteractionNotAllowed = -60007, - Internal = -60008, - ExternalizeNotAllowed = -60009, - InternalizeNotAllowed = -60010, - InvalidFlags = -60011, - ToolExecuteFailure = -60031, - ToolEnvironmentError = -60032, - BadAddress = -60033, + Success = 0, + InvalidSet = -60001, + InvalidRef = -60002, + InvalidTag = -60003, + InvalidPointer = -60004, + Denied = -60005, + Canceled = -60006, + InteractionNotAllowed = -60007, + Internal = -60008, + ExternalizeNotAllowed = -60009, + InternalizeNotAllowed = -60010, + InvalidFlags = -60011, + ToolExecuteFailure = -60031, + ToolEnvironmentError = -60032, + BadAddress = -60033, } #if NET @@ -115,7 +115,7 @@ public class AuthorizationParameters { public class AuthorizationEnvironment { public string? Username; public string? Password; - public bool AddToSharedCredentialPool; + public bool AddToSharedCredentialPool; } #if NET @@ -140,7 +140,7 @@ struct AuthorizationItem { #endif unsafe struct AuthorizationItemSet { public int /* UInt32 */ count; - public AuthorizationItem * /* AuthorizationItem* */ ptrToAuthorization; + public AuthorizationItem* /* AuthorizationItem* */ ptrToAuthorization; } #if NET @@ -151,7 +151,7 @@ unsafe struct AuthorizationItemSet { #endif public unsafe class Authorization : DisposableObject { [DllImport (Constants.SecurityLibrary)] - unsafe extern static int /* OSStatus = int */ AuthorizationCreate (AuthorizationItemSet *rights, AuthorizationItemSet *environment, AuthorizationFlags flags, IntPtr* auth); + unsafe extern static int /* OSStatus = int */ AuthorizationCreate (AuthorizationItemSet* rights, AuthorizationItemSet* environment, AuthorizationFlags flags, IntPtr* auth); #if NET [SupportedOSPlatform ("maccatalyst")] @@ -170,7 +170,7 @@ public unsafe class Authorization : DisposableObject { [DllImport (Constants.SecurityLibrary)] extern static int /* OSStatus = int */ AuthorizationFree (IntPtr handle, AuthorizationFlags flags); - + [Preserve (Conditional = true)] internal Authorization (NativeHandle handle, bool owns) : base (handle, owns) @@ -186,7 +186,7 @@ internal Authorization (NativeHandle handle, bool owns) #endif public int ExecuteWithPrivileges (string pathToTool, AuthorizationFlags flags, string []? args) { - string?[]? arguments = args!; + string? []? arguments = args!; if (arguments is not null) { // The arguments array must be null-terminated, so make sure that's the case @@ -213,19 +213,19 @@ protected override void Dispose (bool disposing) { Dispose (0, disposing); } - + public virtual void Dispose (AuthorizationFlags flags, bool disposing) { if (Handle != IntPtr.Zero && Owns) AuthorizationFree (Handle, flags); base.Dispose (disposing); } - + public static Authorization? Create (AuthorizationFlags flags) { return Create (null, null, flags); } - + static void EncodeString (ref AuthorizationItem item, string key, string? value) { item.name = Marshal.StringToHGlobalAuto (key); @@ -234,32 +234,32 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) item.valueLen = value.Length; } } - + public static Authorization? Create (AuthorizationParameters? parameters, AuthorizationEnvironment? environment, AuthorizationFlags flags) { AuthorizationItemSet pars = new AuthorizationItemSet (); - AuthorizationItemSet *ppars = null; - AuthorizationItem *pitems = null; + AuthorizationItemSet* ppars = null; + AuthorizationItem* pitems = null; AuthorizationItemSet env = new AuthorizationItemSet (); - AuthorizationItemSet *penv = null; - AuthorizationItem *eitems = null; + AuthorizationItemSet* penv = null; + AuthorizationItem* eitems = null; int code; IntPtr auth; try { unsafe { - if (parameters is not null){ + if (parameters is not null) { ppars = &pars; - pars.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 2); + pars.ptrToAuthorization = (AuthorizationItem*) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 2); if (parameters.PathToSystemPrivilegeTool is not null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "system.privilege.admin", parameters.PathToSystemPrivilegeTool); if (parameters.IconPath is not null) EncodeString (ref pars.ptrToAuthorization [pars.count++], "icon", parameters.IconPath); } - if (environment is not null || (parameters is not null && parameters.Prompt is not null)){ + if (environment is not null || (parameters is not null && parameters.Prompt is not null)) { penv = &env; - env.ptrToAuthorization = (AuthorizationItem *) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 4); - if (environment is not null){ + env.ptrToAuthorization = (AuthorizationItem*) Marshal.AllocHGlobal (sizeof (AuthorizationItem) * 4); + if (environment is not null) { if (environment.Username is not null) EncodeString (ref env.ptrToAuthorization [env.count++], "username", environment.Username); if (environment.Password is not null) @@ -267,7 +267,7 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) if (environment.AddToSharedCredentialPool) EncodeString (ref env.ptrToAuthorization [env.count++], "shared", null); } - if (parameters is not null){ + if (parameters is not null) { if (parameters.Prompt is not null) EncodeString (ref env.ptrToAuthorization [env.count++], "prompt", parameters.Prompt); } @@ -278,20 +278,20 @@ static void EncodeString (ref AuthorizationItem item, string key, string? value) return new Authorization (auth, true); } } finally { - if (ppars is not null){ - for (int i = 0; i < pars.count; i++){ + if (ppars is not null) { + for (int i = 0; i < pars.count; i++) { Marshal.FreeHGlobal (pars.ptrToAuthorization [i].name); Marshal.FreeHGlobal (pars.ptrToAuthorization [i].value); } - Marshal.FreeHGlobal ((IntPtr)pars.ptrToAuthorization); + Marshal.FreeHGlobal ((IntPtr) pars.ptrToAuthorization); } - if (penv is not null){ - for (int i = 0; i < env.count; i++){ + if (penv is not null) { + for (int i = 0; i < env.count; i++) { Marshal.FreeHGlobal (env.ptrToAuthorization [i].name); if (env.ptrToAuthorization [i].value != IntPtr.Zero) Marshal.FreeHGlobal (env.ptrToAuthorization [i].value); } - Marshal.FreeHGlobal ((IntPtr)env.ptrToAuthorization); + Marshal.FreeHGlobal ((IntPtr) env.ptrToAuthorization); } } } diff --git a/src/Security/Enums.cs b/src/Security/Enums.cs index e8266599bef3..5db43f766fcd 100644 --- a/src/Security/Enums.cs +++ b/src/Security/Enums.cs @@ -316,7 +316,7 @@ public enum SecStatusCode { InvalidCRLAuthority = -67827, /* The CRL authority was not valid. */ #if MONOMAC [Obsolete ("Use InvalidCRLAuthority.")] - InvaldCRLAuthority = InvalidCRLAuthority, + InvaldCRLAuthority = InvalidCRLAuthority, #endif InvalidCRLEncoding = -67828, /* The CRL encoding was not valid. */ InvalidCRLType = -67829, /* The CRL type was not valid. */ @@ -345,7 +345,7 @@ public enum SecStatusCode { InvalidTupleCredentials = -67852, /* The tuple credentials are not valid. */ #if MONOMAC [Obsolete ("Use InvalidTupleCredentials.")] - InvalidTupleCredendtials = InvalidTupleCredentials, + InvalidTupleCredendtials = InvalidTupleCredentials, #endif InvalidEncoding = -67853, /* The encoding was not valid. */ InvalidValidityPeriod = -67854, /* The validity period was not valid. */ diff --git a/src/Security/Items.cs b/src/Security/Items.cs index 6f49c0e74dfb..5c7fb45b6de7 100644 --- a/src/Security/Items.cs +++ b/src/Security/Items.cs @@ -338,11 +338,11 @@ public static SecStatusCode Update (SecRecord query, SecRecord newAttributes) extern static SecStatusCode SecKeychainAddGenericPassword ( IntPtr keychain, int serviceNameLength, - byte[]? serviceName, + byte []? serviceName, int accountNameLength, - byte[]? accountName, + byte []? accountName, int passwordLength, - byte[] passwordData, + byte [] passwordData, IntPtr itemRef); #if NET @@ -370,18 +370,18 @@ unsafe extern static SecStatusCode SecKeychainFindGenericPassword ( extern static SecStatusCode SecKeychainAddInternetPassword ( IntPtr keychain, int serverNameLength, - byte[]? serverName, + byte []? serverName, int securityDomainLength, - byte[]? securityDomain, + byte []? securityDomain, int accountNameLength, - byte[]? accountName, + byte []? accountName, int pathLength, - byte[]? path, + byte []? path, short port, IntPtr protocol, IntPtr authenticationType, int passwordLength, - byte[] passwordData, + byte [] passwordData, IntPtr itemRef); #if NET @@ -418,30 +418,30 @@ unsafe extern static SecStatusCode SecKeychainFindInternetPassword ( public static SecStatusCode AddInternetPassword ( string serverName, string accountName, - byte[] password, + byte [] password, SecProtocol protocolType = SecProtocol.Http, short port = 0, string? path = null, SecAuthenticationType authenticationType = SecAuthenticationType.Default, string? securityDomain = null) { - byte[]? serverNameBytes = null; - byte[]? securityDomainBytes = null; - byte[]? accountNameBytes = null; - byte[]? pathBytes = null; - + byte []? serverNameBytes = null; + byte []? securityDomainBytes = null; + byte []? accountNameBytes = null; + byte []? pathBytes = null; + if (!String.IsNullOrEmpty (serverName)) serverNameBytes = System.Text.Encoding.UTF8.GetBytes (serverName); - + if (!String.IsNullOrEmpty (securityDomain)) securityDomainBytes = System.Text.Encoding.UTF8.GetBytes (securityDomain); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - + if (!String.IsNullOrEmpty (path)) pathBytes = System.Text.Encoding.UTF8.GetBytes (path); - + return SecKeychainAddInternetPassword ( IntPtr.Zero, serverNameBytes?.Length ?? 0, @@ -459,12 +459,12 @@ public static SecStatusCode AddInternetPassword ( password!, IntPtr.Zero); } - - - public static SecStatusCode FindInternetPassword( + + + public static SecStatusCode FindInternetPassword ( string serverName, string accountName, - out byte[]? password, + out byte []? password, SecProtocol protocolType = SecProtocol.Http, short port = 0, string? path = null, @@ -472,36 +472,36 @@ public static SecStatusCode FindInternetPassword( string? securityDomain = null) { password = null; - - byte[]? serverBytes = null; - byte[]? securityDomainBytes = null; - byte[]? accountNameBytes = null; - byte[]? pathBytes = null; + + byte []? serverBytes = null; + byte []? securityDomainBytes = null; + byte []? accountNameBytes = null; + byte []? pathBytes = null; IntPtr passwordPtr = IntPtr.Zero; - + try { if (!String.IsNullOrEmpty (serverName)) serverBytes = System.Text.Encoding.UTF8.GetBytes (serverName); - + if (!String.IsNullOrEmpty (securityDomain)) securityDomainBytes = System.Text.Encoding.UTF8.GetBytes (securityDomain); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - - if (!String.IsNullOrEmpty(path)) + + if (!String.IsNullOrEmpty (path)) pathBytes = System.Text.Encoding.UTF8.GetBytes (path); - + int passwordLength = 0; - + SecStatusCode code; unsafe { fixed (byte* serverBytesPtr = serverBytes) { fixed (byte* securityDomainBytesPtr = securityDomainBytes) { fixed (byte* accountNameBytesPtr = accountNameBytes) { fixed (byte* pathBytesPtr = pathBytes) { - code = SecKeychainFindInternetPassword( + code = SecKeychainFindInternetPassword ( IntPtr.Zero, serverBytes?.Length ?? 0, serverBytesPtr, @@ -512,8 +512,8 @@ public static SecStatusCode FindInternetPassword( pathBytes?.Length ?? 0, pathBytesPtr, port, - SecProtocolKeys.FromSecProtocol(protocolType), - KeysAuthenticationType.FromSecAuthenticationType(authenticationType), + SecProtocolKeys.FromSecProtocol (protocolType), + KeysAuthenticationType.FromSecAuthenticationType (authenticationType), &passwordLength, &passwordPtr, IntPtr.Zero); @@ -522,32 +522,32 @@ public static SecStatusCode FindInternetPassword( } } } - + if (code == SecStatusCode.Success && passwordLength > 0) { - password = new byte[passwordLength]; - Marshal.Copy(passwordPtr, password, 0, passwordLength); + password = new byte [passwordLength]; + Marshal.Copy (passwordPtr, password, 0, passwordLength); } - + return code; - + } finally { if (passwordPtr != IntPtr.Zero) - SecKeychainItemFreeContent(IntPtr.Zero, passwordPtr); + SecKeychainItemFreeContent (IntPtr.Zero, passwordPtr); } } - public static SecStatusCode AddGenericPassword (string serviceName, string accountName, byte[] password) + public static SecStatusCode AddGenericPassword (string serviceName, string accountName, byte [] password) { - byte[]? serviceNameBytes = null; - byte[]? accountNameBytes = null; - + byte []? serviceNameBytes = null; + byte []? accountNameBytes = null; + if (!String.IsNullOrEmpty (serviceName)) serviceNameBytes = System.Text.Encoding.UTF8.GetBytes (serviceName); if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - return SecKeychainAddGenericPassword( + return SecKeychainAddGenericPassword ( IntPtr.Zero, serviceNameBytes?.Length ?? 0, serviceNameBytes, @@ -559,30 +559,30 @@ public static SecStatusCode AddGenericPassword (string serviceName, string accou ); } - public static SecStatusCode FindGenericPassword (string serviceName, string accountName, out byte[]? password) + public static SecStatusCode FindGenericPassword (string serviceName, string accountName, out byte []? password) { password = null; - byte[]? serviceNameBytes = null; - byte[]? accountNameBytes = null; - + byte []? serviceNameBytes = null; + byte []? accountNameBytes = null; + IntPtr passwordPtr = IntPtr.Zero; - + try { - + if (!String.IsNullOrEmpty (serviceName)) serviceNameBytes = System.Text.Encoding.UTF8.GetBytes (serviceName); - + if (!String.IsNullOrEmpty (accountName)) accountNameBytes = System.Text.Encoding.UTF8.GetBytes (accountName); - + int passwordLength = 0; - + SecStatusCode code; unsafe { fixed (byte* serviceNameBytesPtr = serviceNameBytes) { fixed (byte* accountNameBytesPtr = accountNameBytes) { - code = SecKeychainFindGenericPassword( + code = SecKeychainFindGenericPassword ( IntPtr.Zero, serviceNameBytes?.Length ?? 0, serviceNameBytesPtr, @@ -595,17 +595,17 @@ public static SecStatusCode FindGenericPassword (string serviceName, string acco } } } - - if (code == SecStatusCode.Success && passwordLength > 0){ - password = new byte[passwordLength]; - Marshal.Copy(passwordPtr, password, 0, passwordLength); + + if (code == SecStatusCode.Success && passwordLength > 0) { + password = new byte [passwordLength]; + Marshal.Copy (passwordPtr, password, 0, passwordLength); } - + return code; - + } finally { if (passwordPtr != IntPtr.Zero) - SecKeychainItemFreeContent(IntPtr.Zero, passwordPtr); + SecKeychainItemFreeContent (IntPtr.Zero, passwordPtr); } } #else diff --git a/src/Security/SecCertificate2.cs b/src/Security/SecCertificate2.cs index 1ca0f1ba97e4..2f48736262d9 100644 --- a/src/Security/SecCertificate2.cs +++ b/src/Security/SecCertificate2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecCertificate2 : NativeObject { [Preserve (Conditional = true)] #if NET - internal SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) {} + internal SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) { } #else public SecCertificate2 (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Security/SecIdentity2.cs b/src/Security/SecIdentity2.cs index 6db4f0df505b..0bc7f441890c 100644 --- a/src/Security/SecIdentity2.cs +++ b/src/Security/SecIdentity2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecIdentity2 : NativeObject { #if NET [Preserve (Conditional = true)] - internal SecIdentity2 (NativeHandle handle, bool owns) : base (handle, owns) {} + internal SecIdentity2 (NativeHandle handle, bool owns) : base (handle, owns) { } #else internal SecIdentity2 (NativeHandle handle) : base (handle, false) { } [Preserve (Conditional = true)] diff --git a/src/Security/SecSharedCredential.cs b/src/Security/SecSharedCredential.cs index 3749b610945e..149ac4d5d322 100644 --- a/src/Security/SecSharedCredential.cs +++ b/src/Security/SecSharedCredential.cs @@ -17,12 +17,12 @@ public static partial class SecSharedCredential { [DllImport (Constants.SecurityLibrary)] unsafe extern static void SecAddSharedWebCredential (IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, IntPtr /* CFStringRef */ password, BlockLiteral* /* void (^completionHandler)( CFErrorRef error) ) */ completionHandler); - + #if !NET [UnmanagedFunctionPointerAttribute (CallingConvention.Cdecl)] internal delegate void DActionArity1V12 (IntPtr block, IntPtr obj); #endif - + // This class bridges native block invocations that call into C# static internal class ActionTrampoline { #if !NET @@ -32,14 +32,15 @@ static internal class ActionTrampoline { #else [UnmanagedCallersOnly] #endif - internal static unsafe void Invoke (IntPtr block, IntPtr obj) { - var descriptor = (BlockLiteral *) block; + internal static unsafe void Invoke (IntPtr block, IntPtr obj) + { + var descriptor = (BlockLiteral*) block; var del = (global::System.Action) (descriptor->Target); if (del is not null) { - del ( Runtime.GetNSObject (obj)); + del (Runtime.GetNSObject (obj)); } - } - } + } + } [BindingImpl (BindingImplOptions.Optimizable)] public static void AddSharedWebCredential (string domainName, string account, string password, Action handler) @@ -78,7 +79,7 @@ public static void AddSharedWebCredential (string domainName, string account, st [Deprecated (PlatformName.MacOSX, 11,0)] #endif [DllImport (Constants.SecurityLibrary)] - unsafe extern static void SecRequestSharedWebCredential ( IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, + unsafe extern static void SecRequestSharedWebCredential (IntPtr /* CFStringRef */ fqdn, IntPtr /* CFStringRef */ account, BlockLiteral* /* void (^completionHandler)( CFArrayRef credentials, CFErrorRef error) */ completionHandler); #if !NET @@ -98,11 +99,12 @@ static internal class ArrayErrorActionTrampoline { #else [UnmanagedCallersOnly] #endif - internal static unsafe void Invoke (IntPtr block, IntPtr array, IntPtr err) { - var descriptor = (BlockLiteral *) block; + internal static unsafe void Invoke (IntPtr block, IntPtr array, IntPtr err) + { + var descriptor = (BlockLiteral*) block; var del = (global::System.Action) (descriptor->Target); if (del is not null) - del ( Runtime.GetNSObject (array), Runtime.GetNSObject (err)); + del (Runtime.GetNSObject (array), Runtime.GetNSObject (err)); } } @@ -126,7 +128,7 @@ public static void RequestSharedWebCredential (string domainName, string account [Deprecated (PlatformName.MacOSX, 11,0, message: "Use 'ASAuthorizationPasswordRequest' instead.")] #endif [BindingImpl (BindingImplOptions.Optimizable)] - public static void RequestSharedWebCredential (string domainName, string account, Action handler) + public static void RequestSharedWebCredential (string domainName, string account, Action handler) { Action onComplete = (NSArray a, NSError e) => { var creds = new SecSharedCredentialInfo [a.Count]; diff --git a/src/Security/SecTrust2.cs b/src/Security/SecTrust2.cs index fec07746c4eb..50f338b88ab3 100644 --- a/src/Security/SecTrust2.cs +++ b/src/Security/SecTrust2.cs @@ -36,7 +36,7 @@ namespace Security { public class SecTrust2 : NativeObject { [Preserve (Conditional = true)] #if NET - internal SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) {} + internal SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) { } #else public SecTrust2 (NativeHandle handle, bool owns) : base (handle, owns) { } #endif diff --git a/src/Simd/MathHelper.cs b/src/Simd/MathHelper.cs index 2f2e0a93470b..5739adfe867a 100644 --- a/src/Simd/MathHelper.cs +++ b/src/Simd/MathHelper.cs @@ -16,8 +16,7 @@ static class MathHelper { /// internal static float InverseSqrtFast (float x) { - unsafe - { + unsafe { float xhalf = 0.5f * x; int i = *(int*) &x; // Read bits as integer. i = 0x5f375a86 - (i >> 1); // Make an initial guess for Newton-Raphson approximation diff --git a/src/Simd/MatrixFloat3x3RM.cs b/src/Simd/MatrixFloat3x3RM.cs index a4cc13c99fe1..66aa43926348 100644 --- a/src/Simd/MatrixFloat3x3RM.cs +++ b/src/Simd/MatrixFloat3x3RM.cs @@ -25,12 +25,10 @@ // This type does not come from the CoreGraphics framework #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [NativeName ("GLKMatrix3")] [StructLayout (LayoutKind.Sequential)] - public struct RMatrix3 : IEquatable - { + public struct RMatrix3 : IEquatable { public float M11; public float M12; public float M13; @@ -123,7 +121,7 @@ public RMatrix3 ( break; } - throw new IndexOutOfRangeException(); + throw new IndexOutOfRangeException (); } set { switch (row) { @@ -150,7 +148,7 @@ public RMatrix3 ( break; } - throw new IndexOutOfRangeException(); + throw new IndexOutOfRangeException (); } } @@ -292,17 +290,17 @@ public override string ToString () public override int GetHashCode () { - var hash = new HashCode(); - hash.Add(M11); - hash.Add(M12); - hash.Add(M13); - hash.Add(M21); - hash.Add(M22); - hash.Add(M23); - hash.Add(M31); - hash.Add(M32); - hash.Add(M33); - return hash.ToHashCode(); + var hash = new HashCode (); + hash.Add (M11); + hash.Add (M12); + hash.Add (M13); + hash.Add (M21); + hash.Add (M22); + hash.Add (M23); + hash.Add (M31); + hash.Add (M32); + hash.Add (M33); + return hash.ToHashCode (); } public override bool Equals (object? obj) diff --git a/src/Simd/MatrixFloat4x3.cs b/src/Simd/MatrixFloat4x3.cs index cdb52fb94a5a..f06a7c0154ad 100644 --- a/src/Simd/MatrixFloat4x3.cs +++ b/src/Simd/MatrixFloat4x3.cs @@ -16,7 +16,7 @@ using System.Runtime.Versioning; #if NET -using VectorFloat4=global::System.Numerics.Vector4; +using VectorFloat4 = global::System.Numerics.Vector4; #else using VectorFloat4 = global::OpenTK.Vector4; #endif diff --git a/src/Simd/QuaternionDouble.cs b/src/Simd/QuaternionDouble.cs index d5725590a524..a64edbe59ba6 100644 --- a/src/Simd/QuaternionDouble.cs +++ b/src/Simd/QuaternionDouble.cs @@ -20,11 +20,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/quaternion.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NQuaterniond : IEquatable - { + public struct NQuaterniond : IEquatable { public double X; public double Y; public double Z; @@ -46,8 +44,7 @@ public NQuaterniond (NVector3d vectorPart, double scalarPart) W = scalarPart; } - internal NVector3d Xyz - { + internal NVector3d Xyz { get => new NVector3d (X, Y, Z); set { X = value.X; @@ -66,7 +63,7 @@ public override string ToString () => $"({X}, {Y}, {Z}, {W})"; public override int GetHashCode () => - HashCode.Combine(X, Y, Z, W); + HashCode.Combine (X, Y, Z, W); public override bool Equals (object? obj) { @@ -100,7 +97,7 @@ internal NVector4d ToAxisAngle () { NQuaterniond q = this; if (q.W > 1.0f) - q.Normalize(); + q.Normalize (); NVector4d result = new NVector4d (); diff --git a/src/Simd/VectorDouble2.cs b/src/Simd/VectorDouble2.cs index 8f2c57e77309..b33768c141ee 100644 --- a/src/Simd/VectorDouble2.cs +++ b/src/Simd/VectorDouble2.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector2d : IEquatable - { + public struct NVector2d : IEquatable { public double X; public double Y; @@ -47,7 +45,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y); + return HashCode.Combine (X, Y); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorDouble4.cs b/src/Simd/VectorDouble4.cs index 2a8459dd8c7a..5aa60c8c370a 100644 --- a/src/Simd/VectorDouble4.cs +++ b/src/Simd/VectorDouble4.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector4d : IEquatable - { + public struct NVector4d : IEquatable { public double X; public double Y; public double Z; @@ -34,8 +32,7 @@ public NVector4d (double x, double y, double z, double w) W = w; } - internal NVector3d Xyz - { + internal NVector3d Xyz { get => new NVector3d (X, Y, Z); set { X = value.X; @@ -61,7 +58,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y, Z, W); + return HashCode.Combine (X, Y, Z, W); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt2.cs b/src/Simd/VectorInt2.cs index e1682e07a5d3..5802b10cd0ee 100644 --- a/src/Simd/VectorInt2.cs +++ b/src/Simd/VectorInt2.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector2i : IEquatable - { + public struct NVector2i : IEquatable { public int X; public int Y; @@ -47,7 +45,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y); + return HashCode.Combine (X, Y); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt3.cs b/src/Simd/VectorInt3.cs index 40ae57929c98..a1a811c2b0fb 100644 --- a/src/Simd/VectorInt3.cs +++ b/src/Simd/VectorInt3.cs @@ -16,11 +16,9 @@ // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h #if NET -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector3i : IEquatable - { + public struct NVector3i : IEquatable { public int X; public int Y; public int Z; @@ -51,7 +49,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y, Z); + return HashCode.Combine (X, Y, Z); } public override bool Equals (object? obj) diff --git a/src/Simd/VectorInt4.cs b/src/Simd/VectorInt4.cs index a4ddc37c4397..26336605fb02 100644 --- a/src/Simd/VectorInt4.cs +++ b/src/Simd/VectorInt4.cs @@ -16,11 +16,9 @@ #if NET // This type does not come from the CoreGraphics framework; it's defined in /usr/include/simd/vector_types.h -namespace CoreGraphics -{ +namespace CoreGraphics { [StructLayout (LayoutKind.Sequential)] - public struct NVector4i : IEquatable - { + public struct NVector4i : IEquatable { public int X; public int Y; public int Z; @@ -51,7 +49,7 @@ public override string ToString () public override int GetHashCode () { - return HashCode.Combine(X, Y, Z, W); + return HashCode.Combine (X, Y, Z, W); } public override bool Equals (object? obj) diff --git a/src/StoreKit/SKOverlayAppClipConfiguration.cs b/src/StoreKit/SKOverlayAppClipConfiguration.cs index 4fe5fbdd9871..7f431db6a955 100644 --- a/src/StoreKit/SKOverlayAppClipConfiguration.cs +++ b/src/StoreKit/SKOverlayAppClipConfiguration.cs @@ -10,10 +10,9 @@ namespace StoreKit { #if !COREBUILD - public partial class SKOverlayAppClipConfiguration - { - public NSObject? this[string i] { - get => GetAdditionalValue (i); + public partial class SKOverlayAppClipConfiguration { + public NSObject? this [string i] { + get => GetAdditionalValue (i); set => SetAdditionalValue (value, i); } } diff --git a/src/StoreKit/SKOverlayAppConfiguration.cs b/src/StoreKit/SKOverlayAppConfiguration.cs index 937f5b6b5e87..81d3da2f8c83 100644 --- a/src/StoreKit/SKOverlayAppConfiguration.cs +++ b/src/StoreKit/SKOverlayAppConfiguration.cs @@ -10,10 +10,9 @@ namespace StoreKit { #if !COREBUILD - public partial class SKOverlayAppConfiguration - { - public NSObject? this[string i] { - get => GetAdditionalValue (i); + public partial class SKOverlayAppConfiguration { + public NSObject? this [string i] { + get => GetAdditionalValue (i); set => SetAdditionalValue (value, i); } } diff --git a/src/System.Net.Http/CFNetworkHandler.cs b/src/System.Net.Http/CFNetworkHandler.cs index b94bf44140e2..521c50886157 100644 --- a/src/System.Net.Http/CFNetworkHandler.cs +++ b/src/System.Net.Http/CFNetworkHandler.cs @@ -36,7 +36,7 @@ #if NET using CFNetwork; using CoreFoundation; -using CF=CoreFoundation; +using CF = CoreFoundation; #else using CoreServices; using CoreFoundation; diff --git a/src/UIKit/NSLayoutManager.cs b/src/UIKit/NSLayoutManager.cs index 530730812d64..3c04a9069a0c 100644 --- a/src/UIKit/NSLayoutManager.cs +++ b/src/UIKit/NSLayoutManager.cs @@ -19,7 +19,7 @@ using ObjCRuntime; #if MONOMAC -using UIFont=AppKit.NSFont; +using UIFont = AppKit.NSFont; #endif #if MONOMAC diff --git a/src/UIKit/UIActionSheet.cs b/src/UIKit/UIActionSheet.cs index 285586845534..494a237b948f 100644 --- a/src/UIKit/UIActionSheet.cs +++ b/src/UIKit/UIActionSheet.cs @@ -41,7 +41,7 @@ public UIActionSheet (string title, IUIActionSheetDelegate del, string cancelTit return; } - foreach (string b in other){ + foreach (string b in other) { if (b is not null) AddButton (b); } @@ -49,7 +49,7 @@ public UIActionSheet (string title, IUIActionSheetDelegate del, string cancelTit if (cancelTitle is not null) CancelButtonIndex = AddButton (cancelTitle); } - + #if !NET [Obsolete ("Use overload with a IUIActionSheetDelegate parameter")] public UIActionSheet (string title, UIActionSheetDelegate del) @@ -59,10 +59,10 @@ public UIActionSheet (string title, UIActionSheetDelegate del) #endif public UIActionSheet (string title, IUIActionSheetDelegate del) - : this (title, del, null, null, (string) null) {} + : this (title, del, null, null, (string) null) { } public UIActionSheet (string title) - : this (title, null, null, null, (string) null) {} + : this (title, null, null, null, (string) null) { } public void Add (string name) { @@ -75,7 +75,7 @@ public IEnumerator GetEnumerator () yield return ButtonTitle (i); } } - + } #endif // IOS diff --git a/src/UIKit/UIAppearance.cs b/src/UIKit/UIAppearance.cs index da6d4b9a0b68..481eaa9ca64c 100644 --- a/src/UIKit/UIAppearance.cs +++ b/src/UIKit/UIAppearance.cs @@ -76,7 +76,7 @@ static IntPtr [] TypesToPointers (Type [] whenFoundIn) public static IntPtr GetAppearance (IntPtr class_ptr, params Type [] whenFoundIn) { using (var array = NSArray.FromIntPtrs (TypesToPointers (whenFoundIn))) { - return Messaging.IntPtr_objc_msgSend_IntPtr (class_ptr, + return Messaging.IntPtr_objc_msgSend_IntPtr (class_ptr, Selector.GetHandle (UIAppearance.selAppearanceWhenContainedInInstancesOfClasses), array.Handle); } } @@ -90,7 +90,7 @@ public static IntPtr GetAppearance (IntPtr class_ptr, UITraitCollection traits, throw new ArgumentNullException ("traits"); using (var array = NSArray.FromIntPtrs (TypesToPointers (whenFoundIn))) { - return Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, + return Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (class_ptr, Selector.GetHandle (UIAppearance.selAppearanceForTraitCollectionWhenContainedInInstancesOfClasses), traits.Handle, array.Handle); } diff --git a/src/UIKit/UIButton.cs b/src/UIKit/UIButton.cs index 21bdc132fa36..b389b49c995a 100644 --- a/src/UIKit/UIButton.cs +++ b/src/UIKit/UIButton.cs @@ -15,7 +15,7 @@ public partial class UIButton { public UIButton (UIButtonType type) #if NET - : base (ObjCRuntime.Messaging.NativeHandle_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int)type)) + : base (ObjCRuntime.Messaging.NativeHandle_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int) type)) #else : base (ObjCRuntime.Messaging.IntPtr_objc_msgSend_int (class_ptr, Selector.GetHandle ("buttonWithType:"), (int) type)) #endif diff --git a/src/UIKit/UIDevice.cs b/src/UIKit/UIDevice.cs index afe3d44476c2..cdbfe560d04a 100644 --- a/src/UIKit/UIDevice.cs +++ b/src/UIKit/UIDevice.cs @@ -15,7 +15,7 @@ public partial class UIDevice { public bool CheckSystemVersion (int major, int minor) { #if __MACCATALYST__ - return Runtime.CheckSystemVersion (major, minor, Runtime.iOSSupportVersion); + return Runtime.CheckSystemVersion (major, minor, Runtime.iOSSupportVersion); #else return Runtime.CheckSystemVersion (major, minor, SystemVersion); #endif diff --git a/src/UIKit/UIDocumentBrowserViewController.cs b/src/UIKit/UIDocumentBrowserViewController.cs index 74668099e54b..8781942e7b66 100644 --- a/src/UIKit/UIDocumentBrowserViewController.cs +++ b/src/UIKit/UIDocumentBrowserViewController.cs @@ -31,10 +31,10 @@ namespace UIKit { - public partial class UIDocumentBrowserViewController - { + public partial class UIDocumentBrowserViewController { - static bool CheckSystemVersion () { + static bool CheckSystemVersion () + { #if IOS return SystemVersion.CheckiOS (12, 0); #else diff --git a/src/UIKit/UIImage.cs b/src/UIKit/UIImage.cs index 76fb5eadee3e..4b93d0387ef2 100644 --- a/src/UIKit/UIImage.cs +++ b/src/UIKit/UIImage.cs @@ -32,11 +32,11 @@ partial class UIImage { public void SaveToPhotosAlbum (SaveStatus status) { UIImageStatusDispatcher? dis = null; - UIApplication.EnsureUIThread (); + UIApplication.EnsureUIThread (); if (status is not null) dis = new UIImageStatusDispatcher (status); - + UIImageWriteToSavedPhotosAlbum (Handle, dis is not null ? dis.Handle : IntPtr.Zero, dis is not null ? Selector.GetHandle (UIImageStatusDispatcher.callbackSelector) : IntPtr.Zero, IntPtr.Zero); } #endif @@ -155,7 +155,7 @@ public DataWrapper (IntPtr buffer, uint len) internal class UIImageStatusDispatcher : NSObject { public const string callbackSelector = "Xamarin_Internal__image:didFinishSavingWithError:contextInfo:"; UIImage.SaveStatus status; - + public UIImageStatusDispatcher (UIImage.SaveStatus status) { IsDirectBinding = false; diff --git a/src/UIKit/UINavigationBar.cs b/src/UIKit/UINavigationBar.cs index 516a22786811..0e5579a415df 100644 --- a/src/UIKit/UINavigationBar.cs +++ b/src/UIKit/UINavigationBar.cs @@ -23,12 +23,12 @@ public virtual UITextAttributes GetTitleTextAttributes () { return new UITextAttributes (_TitleTextAttributes); } - + public virtual void SetTitleTextAttributes (UITextAttributes attributes) { if (attributes is null) throw new ArgumentNullException ("attributes"); - + _TitleTextAttributes = attributes.ToDictionary (); } } diff --git a/src/UIKit/UIPasteboard.cs b/src/UIKit/UIPasteboard.cs index 9c9307db7074..c55b53c0a80c 100644 --- a/src/UIKit/UIPasteboard.cs +++ b/src/UIKit/UIPasteboard.cs @@ -25,16 +25,16 @@ UIImage [] GetImageArray (IntPtr handle) var obj = Runtime.GetNSObject (array.ValueAt (i)); var data = obj as NSData; UIImage img; - + if (data is not null) { img = new UIImage (data); } else { img = (UIImage) obj; } - + ret [i] = img; } - + return ret; } } @@ -46,11 +46,11 @@ UIImage [] GetImageArray (IntPtr handle) // API and not make users change their code. [CompilerGenerated] - public virtual UIImage[] Images { + public virtual UIImage [] Images { [Export ("images", ArgumentSemantic.Copy)] get { global::UIKit.UIApplication.EnsureUIThread (); - UIImage[] ret; + UIImage [] ret; if (IsDirectBinding) { ret = GetImageArray (ObjCRuntime.Messaging.IntPtr_objc_msgSend (this.Handle, Selector.GetHandle (selImages))); } else { @@ -58,12 +58,12 @@ public virtual UIImage[] Images { } return ret; } - + [Export ("setImages:", ArgumentSemantic.Copy)] set { global::UIKit.UIApplication.EnsureUIThread (); var nsa_value = NSArray.FromNSObjects (value); - + if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (selSetImages_), nsa_value.Handle); } else { diff --git a/src/UIKit/UIPickerView.cs b/src/UIKit/UIPickerView.cs index dd24a6ea2397..8dce0b97fcc4 100644 --- a/src/UIKit/UIPickerView.cs +++ b/src/UIKit/UIPickerView.cs @@ -2,7 +2,7 @@ using System; -using Foundation; +using Foundation; using CoreGraphics; using ObjCRuntime; diff --git a/src/UIKit/UIPopoverPresentationController.cs b/src/UIKit/UIPopoverPresentationController.cs index 61eb25a88b38..826a0e5ba8a6 100644 --- a/src/UIKit/UIPopoverPresentationController.cs +++ b/src/UIKit/UIPopoverPresentationController.cs @@ -22,7 +22,7 @@ public virtual Type PopoverBackgroundViewType { return Class.Lookup (p); } set { - PopoverBackgroundViewClass = (value is null) ? IntPtr.Zero : + PopoverBackgroundViewClass = (value is null) ? IntPtr.Zero : Class.GetHandle (value); } } diff --git a/src/UIKit/UIStringDrawing.cs b/src/UIKit/UIStringDrawing.cs index 1fad3f3ebc22..6720e7845b79 100644 --- a/src/UIKit/UIStringDrawing.cs +++ b/src/UIKit/UIStringDrawing.cs @@ -8,7 +8,7 @@ using ObjCRuntime; namespace UIKit { - public unsafe static partial class UIStringDrawing { + public unsafe static partial class UIStringDrawing { #if NET [SupportedOSPlatform ("ios")] [SupportedOSPlatform ("maccatalyst")] diff --git a/src/UIKit/UITextAttributes.cs b/src/UIKit/UITextAttributes.cs index 68cee22e67ad..b831b39010b3 100644 --- a/src/UIKit/UITextAttributes.cs +++ b/src/UIKit/UITextAttributes.cs @@ -25,14 +25,14 @@ public class UITextAttributes { public UITextAttributes () { } - + internal UITextAttributes (NSDictionary dict) { if (dict is null) return; - + NSObject val; - + if (dict.TryGetValue (UITextAttributesConstants.Font, out val)) Font = val as UIFont; if (dict.TryGetValue (UITextAttributesConstants.TextColor, out val)) @@ -45,7 +45,7 @@ internal UITextAttributes (NSDictionary dict) TextShadowOffset = value.UIOffsetValue; } } - + internal NSDictionary ToDictionary () { int n = 0; @@ -67,27 +67,27 @@ internal NSDictionary ToDictionary () var keys = new NSObject [n]; var values = new NSObject [n]; n = 0; - if (font is not null){ + if (font is not null) { keys [n] = UITextAttributesConstants.Font; values [n] = font; n++; } - if (text_color is not null){ + if (text_color is not null) { keys [n] = UITextAttributesConstants.TextColor; values [n] = text_color; n++; } - if (text_shadow_color is not null){ + if (text_shadow_color is not null) { keys [n] = UITextAttributesConstants.TextShadowColor; values [n] = text_shadow_color; n++; } - if (text_shadow_offset.Horizontal != 0 || text_shadow_offset.Vertical != 0){ + if (text_shadow_offset.Horizontal != 0 || text_shadow_offset.Vertical != 0) { keys [n] = UITextAttributesConstants.TextShadowOffset; values [n] = NSValue.FromUIOffset (text_shadow_offset); } using (NSArray avalues = NSArray.FromObjects (values), - akeys = NSArray.FromObjects (keys)){ + akeys = NSArray.FromObjects (keys)) { return NSDictionary.FromObjectsAndKeysInternal (avalues, akeys); } } diff --git a/src/UIKit/UIToolbar.cs b/src/UIKit/UIToolbar.cs index 605190d7b70d..fdeb2256aeb9 100644 --- a/src/UIKit/UIToolbar.cs +++ b/src/UIKit/UIToolbar.cs @@ -12,20 +12,20 @@ namespace UIKit { public partial class UIToolbar : UIView { - + // note: we cannot autogenerate this overload and still update the (same) __mt_Items_var local // previously we 'lost' the managed reference to the array and this caused bug #410 // http://bugzilla.xamarin.com/show_bug.cgi?id=410 [Export ("setItems:animated:")] - public virtual void SetItems (UIBarButtonItem[] items, bool animated) + public virtual void SetItems (UIBarButtonItem [] items, bool animated) { if (items is null) throw new ArgumentNullException ("items"); - + // must be identical the [get|set]_Items var nsa_items = NSArray.FromNSObjects (items); - + #if NET if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_bool (this.Handle, Selector.GetHandle ("setItems:animated:"), nsa_items.Handle, animated ? (byte) 1 : (byte) 0); diff --git a/src/UIKit/UIVideo.cs b/src/UIKit/UIVideo.cs index 64bc283fb7fb..82a8d14c1c01 100644 --- a/src/UIKit/UIVideo.cs +++ b/src/UIKit/UIVideo.cs @@ -22,7 +22,7 @@ namespace UIKit { internal class UIVideoStatusDispatcher : NSObject { public const string callbackSelector = "Xamarin_Internal__video:didFinishSavingWithError:contextInfo:"; UIVideo.SaveStatus status; - + public UIVideoStatusDispatcher (UIVideo.SaveStatus status) { this.status = status; @@ -38,13 +38,13 @@ public void Callback (string str, NSError err, IntPtr ctx) DangerousRelease (); } } - + public static class UIVideo { public delegate void SaveStatus (string path, NSError error); - + [DllImport (Constants.UIKitLibrary)] extern static /* BOOL */ byte UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (/* NSString* */ IntPtr videoPath); - + public static bool IsCompatibleWithSavedPhotosAlbum (string path) { UIApplication.EnsureUIThread (); @@ -63,11 +63,11 @@ public static void SaveToPhotosAlbum (string path, SaveStatus status) throw new ArgumentNullException ("status"); UIApplication.EnsureUIThread (); var dis = new UIVideoStatusDispatcher (status); - + using (var ns = new NSString (path)) UISaveVideoAtPathToSavedPhotosAlbum (ns.Handle, dis.Handle, Selector.GetHandle (UIVideoStatusDispatcher.callbackSelector), IntPtr.Zero); } - + } } diff --git a/src/VideoToolbox/VTCompressionSession.cs b/src/VideoToolbox/VTCompressionSession.cs index deb4485ce60f..83dd6febe765 100644 --- a/src/VideoToolbox/VTCompressionSession.cs +++ b/src/VideoToolbox/VTCompressionSession.cs @@ -179,7 +179,7 @@ unsafe extern static VTStatus VTCompressionSessionCreate ( VTVideoEncoderSpecification? encoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. NSDictionary? sourceImageBufferAttributes, // Undocumented options, probably always null #if NET - delegate* unmanaged staticCback) + delegate* unmanaged staticCback) #else CompressionOutputCallback? staticCback) #endif diff --git a/src/VideoToolbox/VTDecompressionSession.cs b/src/VideoToolbox/VTDecompressionSession.cs index 3424ff153749..802d6abc3795 100644 --- a/src/VideoToolbox/VTDecompressionSession.cs +++ b/src/VideoToolbox/VTDecompressionSession.cs @@ -201,8 +201,8 @@ public static VTDecompressionSession Create (CMVideoFormatDescription formatDesc public static VTDecompressionSession? Create (VTDecompressionOutputCallback outputCallback, CMVideoFormatDescription formatDescription, #if NET - VTVideoDecoderSpecification? decoderSpecification = null, // hardware acceleration is default behavior on iOS. no opt-in required. - CVPixelBufferAttributes? destinationImageBufferAttributes = null) + VTVideoDecoderSpecification? decoderSpecification = null, // hardware acceleration is default behavior on iOS. no opt-in required. + CVPixelBufferAttributes? destinationImageBufferAttributes = null) #else VTVideoDecoderSpecification? decoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. CVPixelBufferAttributes? destinationImageBufferAttributes) @@ -222,7 +222,7 @@ public static VTDecompressionSession Create (CMVideoFormatDescription formatDesc VTVideoDecoderSpecification? decoderSpecification, // hardware acceleration is default behavior on iOS. no opt-in required. NSDictionary? destinationImageBufferAttributes, #if NET - delegate* unmanaged cback) + delegate* unmanaged cback) #else IntPtr cback) #endif diff --git a/src/VideoToolbox/VTRawProcessingSession.cs b/src/VideoToolbox/VTRawProcessingSession.cs index 410529239c7a..7663da13a70c 100644 --- a/src/VideoToolbox/VTRawProcessingSession.cs +++ b/src/VideoToolbox/VTRawProcessingSession.cs @@ -111,7 +111,7 @@ public static nint GetTypeId () [DllImport (Constants.VideoToolboxLibrary)] unsafe static extern VTStatus VTRAWProcessingSessionSetParameterChangedHander ( IntPtr /* VTRAWProcessingSessionRef */ session, - BlockLiteral * /* VTRAWProcessingParameterChangeHandler */ parameterChangeHandler + BlockLiteral* /* VTRAWProcessingParameterChangeHandler */ parameterChangeHandler ); /// Provide a callback that will be called when the VTRawProcessingPlugin changes the set of processing parameters. @@ -145,7 +145,7 @@ unsafe static extern VTStatus VTRAWProcessingSessionProcessFrame ( IntPtr /* VTRAWProcessingSessionRef */ session, IntPtr /* CVPixelBufferRef */ inputPixelBuffer, IntPtr /* CM_NULLABLE CFDictionaryRef */ frameOptions, - BlockLiteral * /* VTRAWProcessingOutputHandler */ outputHandler + BlockLiteral* /* VTRAWProcessingOutputHandler */ outputHandler ); /// Use this function to submit RAW frames for processing using sequence and frame level parameters. diff --git a/src/accessorysetupkit.cs b/src/accessorysetupkit.cs index d7338d289dcd..0739adb6305d 100644 --- a/src/accessorysetupkit.cs +++ b/src/accessorysetupkit.cs @@ -11,16 +11,16 @@ namespace AccessorySetupKit { [Native] [iOS (18, 0)] public enum ASAccessoryState : long { - Unauthorized = 0, - AwaitingAuthorization = 10, - Authorized = 20, + Unauthorized = 0, + AwaitingAuthorization = 10, + Authorized = 20, } [Flags] [Native] [iOS (18, 0)] public enum ASAccessoryRenameOptions : ulong { - Ssid = 1U << 0, + Ssid = 1U << 0, } [Flags] @@ -73,19 +73,19 @@ interface ASAccessory { [Native] [iOS (18, 0)] public enum ASAccessoryEventType : long { - Unknown = 0, - Activated = 10, - Invalidated = 11, - MigrationComplete = 20, - AccessoryAdded = 30, - AccessoryRemoved = 31, - AccessoryChanged = 32, - PickerDidPresent = 40, - PickerDidDismiss = 50, + Unknown = 0, + Activated = 10, + Invalidated = 11, + MigrationComplete = 20, + AccessoryAdded = 30, + AccessoryRemoved = 31, + AccessoryChanged = 32, + PickerDidPresent = 40, + PickerDidDismiss = 50, PickerSetupBridging = 60, - PickerSetupFailed = 70, - PickerSetupPairing = 80, - PickerSetupRename = 90, + PickerSetupFailed = 70, + PickerSetupPairing = 80, + PickerSetupRename = 90, } [BaseType (typeof (NSObject))] @@ -202,18 +202,18 @@ interface ASDiscoveryDescriptor { [iOS (18, 0)] [ErrorDomain ("ASErrorDomain")] enum ASErrorCode : long { - Success = 0, - Unknown = 1, - ActivationFailed = 100, - ConnectionFailed = 150, - DiscoveryTimeout = 200, - ExtensionNotFound = 300, - Invalidated = 400, - InvalidRequest = 450, + Success = 0, + Unknown = 1, + ActivationFailed = 100, + ConnectionFailed = 150, + DiscoveryTimeout = 200, + ExtensionNotFound = 300, + Invalidated = 400, + InvalidRequest = 450, PickerAlreadyActive = 500, - PickerRestricted = 550, - UserCancelled = 700, - UserRestricted = 750, + PickerRestricted = 550, + UserCancelled = 700, + UserRestricted = 750, } [BaseType (typeof (NSObject))] diff --git a/src/appkit.cs b/src/appkit.cs index 7320ec7c35a6..1a5346eefab9 100644 --- a/src/appkit.cs +++ b/src/appkit.cs @@ -15040,7 +15040,7 @@ partial interface NSSpellChecker { bool IsAutomaticTextCompletionEnabled { get; } #if NET - [Async (ResultTypeName="NSSpellCheckerCandidates")] + [Async (ResultTypeName = "NSSpellCheckerCandidates")] #else [Async (ResultTypeName = "NSSpellCheckerCanidates")] #endif @@ -19847,7 +19847,7 @@ NSTextContentType ContentType { // This came from the NSTextFinderClient protocol in legacy Xamarin, but NSTextView doesn't really implement that protocol, // so when it was removed for .NET, we still need to expose the API from NSTextFinderClient that NSTextView actually has. [Export ("selectedRanges", ArgumentSemantic.Copy)] - NSArray SelectedRanges { get; set; } + NSArray SelectedRanges { get; set; } #endif [NoiOS] diff --git a/src/authenticationservices.cs b/src/authenticationservices.cs index 27bdb45f578f..1516e3f1d7bb 100644 --- a/src/authenticationservices.cs +++ b/src/authenticationservices.cs @@ -630,7 +630,8 @@ interface IASAuthorizationControllerDelegate { } [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1048,7 +1049,8 @@ interface IASWebAuthenticationSessionRequestDelegate { } [NoTV] [NoiOS] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1162,7 +1164,8 @@ interface IASAccountAuthenticationModificationControllerDelegate { } [iOS (14, 0)] [NoTV, NoMac] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/avfoundation.cs b/src/avfoundation.cs index 29f1b1c94063..3479fca03b7e 100644 --- a/src/avfoundation.cs +++ b/src/avfoundation.cs @@ -1336,17 +1336,17 @@ interface AVAudio3DMixing { #if NET [Abstract] - [TV (13,0), iOS (13,0)] + [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] [Export ("sourceMode", ArgumentSemantic.Assign)] AVAudio3DMixingSourceMode SourceMode { get; set; } [Abstract] - [TV (13,0), iOS (13,0)] + [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] [Export ("pointSourceInHeadMode", ArgumentSemantic.Assign)] AVAudio3DMixingPointSourceInHeadMode PointSourceInHeadMode { get; set; } - + #else [TV (13, 0), iOS (13, 0)] [Export ("sourceMode", ArgumentSemantic.Assign)] @@ -8858,7 +8858,7 @@ interface AVAssetExportSession { [Export ("supportedFileTypes")] #if NET - string [] SupportedFileTypes { get; } + string [] SupportedFileTypes { get; } #else NSObject [] SupportedFileTypes { get; } #endif @@ -11857,7 +11857,7 @@ interface AVCaptureDeviceDiscoverySession { #else [Static] [Export ("discoverySessionWithDeviceTypes:mediaType:position:")] - AVCaptureDeviceDiscoverySession Create ([BindAs (typeof (AVCaptureDeviceType[]))] NSString[] deviceTypes, [NullAllowed] [BindAs (typeof (AVMediaTypes))] NSString mediaType, AVCaptureDevicePosition position); + AVCaptureDeviceDiscoverySession Create ([BindAs (typeof (AVCaptureDeviceType []))] NSString [] deviceTypes, [NullAllowed][BindAs (typeof (AVMediaTypes))] NSString mediaType, AVCaptureDevicePosition position); #endif [Export ("devices")] diff --git a/src/backgroundassets.cs b/src/backgroundassets.cs index d5dc0fb046f5..4ae0a5a877d8 100644 --- a/src/backgroundassets.cs +++ b/src/backgroundassets.cs @@ -127,7 +127,8 @@ interface IBADownloadManagerDelegate { } [NoTV, Mac (13, 0), iOS (16, 0), MacCatalyst (16, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/browserenginekit.cs b/src/browserenginekit.cs index e5788e8b1abf..53ac4c0f7be8 100644 --- a/src/browserenginekit.cs +++ b/src/browserenginekit.cs @@ -52,11 +52,10 @@ using OS_xpc_object = Foundation.NSObject; namespace BrowserEngineKit { - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BELayerHierarchyHandle : NSSecureCoding - { + interface BELayerHierarchyHandle : NSSecureCoding { [Static] [Export ("handleWithXPCRepresentation:error:")] [return: NullAllowed] @@ -66,11 +65,10 @@ interface BELayerHierarchyHandle : NSSecureCoding OS_xpc_object CreateXpcRepresentation (); } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BELayerHierarchy - { + interface BELayerHierarchy { [Static] [Export ("layerHierarchyWithError:")] [return: NullAllowed] @@ -86,19 +84,17 @@ interface BELayerHierarchy void Invalidate (); } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIView))] - interface BELayerHierarchyHostingView - { + interface BELayerHierarchyHostingView { [Export ("handle", ArgumentSemantic.Strong), NullAllowed] BELayerHierarchyHandle LayerHierarchyHandle { get; set; } } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding - { + interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding { [Static] [Export ("coordinatorWithError:")] [return: NullAllowed] @@ -123,11 +119,10 @@ interface BELayerHierarchyHostingTransactionCoordinator : NSSecureCoding void Commit (); } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(UIContextMenuConfiguration))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (UIContextMenuConfiguration))] [DisableDefaultCtor] - interface BEContextMenuConfiguration - { + interface BEContextMenuConfiguration { [DesignatedInitializer] [Export ("init")] NativeHandle Constructor (); @@ -136,13 +131,12 @@ interface BEContextMenuConfiguration bool Fulfill ([NullAllowed] UIContextMenuConfiguration configuration); } - delegate bool BEDragInteractionDelegateGetDragItemsCallback (UIDragItem[] items); + delegate bool BEDragInteractionDelegateGetDragItemsCallback (UIDragItem [] items); - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIDragInteractionDelegate))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BEDragInteractionDelegate - { + interface BEDragInteractionDelegate { [Export ("dragInteraction:prepareDragSession:completion:")] void PrepareDragSession (BEDragInteraction dragInteraction, IUIDragSession session, Func completion); @@ -150,12 +144,11 @@ interface BEDragInteractionDelegate void GetDragItems (BEDragInteraction dragInteraction, IUIDragSession session, CGPoint point, BEDragInteractionDelegateGetDragItemsCallback completion); } - interface IBEDragInteractionDelegate {} + interface IBEDragInteractionDelegate { } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIDragInteraction))] - interface BEDragInteraction - { + interface BEDragInteraction { [Wrap ("WeakDelegate")] [NullAllowed] IBEDragInteractionDelegate Delegate { get; } @@ -168,11 +161,10 @@ interface BEDragInteraction NativeHandle Constructor (IBEDragInteractionDelegate @delegate); } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (UIScrollViewDelegate))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BEScrollViewDelegate - { + interface BEScrollViewDelegate { [Export ("scrollView:handleScrollUpdate:completion:")] void HandleScrollUpdate (BEScrollView scrollView, BEScrollViewScrollUpdate scrollUpdate, Action completion); @@ -181,12 +173,11 @@ interface BEScrollViewDelegate BEScrollView GetParentScrollView (BEScrollView scrollView); } - interface IBEScrollViewDelegate {} + interface IBEScrollViewDelegate { } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(UIScrollView))] - interface BEScrollView - { + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (UIScrollView))] + interface BEScrollView { [Wrap ("WeakDelegate")] [NullAllowed] IBEScrollViewDelegate Delegate { get; set; } @@ -195,21 +186,19 @@ interface BEScrollView NSObject WeakDelegate { get; set; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BEScrollViewScrollUpdatePhase : long - { + public enum BEScrollViewScrollUpdatePhase : long { Began, Changed, Ended, Cancelled, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEScrollViewScrollUpdate - { + interface BEScrollViewScrollUpdate { [Export ("timestamp")] double Timestamp { get; } @@ -225,11 +214,10 @@ interface BEScrollViewScrollUpdate delegate void BEWebContentProcessCreateCallback ([NullAllowed] BEWebContentProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEWebContentProcess - { + interface BEWebContentProcess { [Static] [Export ("webContentProcessWithInterruptionHandler:completion:")] [Async] @@ -257,7 +245,7 @@ interface BEWebContentProcess IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error); // Inlined from the CapabilityInvalidationHandler (BEWebContentProcess) category - [NoTV, NoMac, iOS (17,6), MacCatalyst (17, 6)] + [NoTV, NoMac, iOS (17, 6), MacCatalyst (17, 6)] [Export ("grantCapability:error:invalidationHandler:")] [return: NullAllowed] IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error, Action invalidationHandler); @@ -265,11 +253,10 @@ interface BEWebContentProcess delegate void BENetworkingProcessCreateCallback ([NullAllowed] BENetworkingProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BENetworkingProcess - { + interface BENetworkingProcess { [Static] [Export ("networkProcessWithInterruptionHandler:completion:")] [Async] @@ -302,11 +289,10 @@ interface BENetworkingProcess delegate void BERenderingProcessCreateCallback ([NullAllowed] BERenderingProcess proces, [NullAllowed] NSError error); - [NoTV, Mac (14, 3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BERenderingProcess - { + interface BERenderingProcess { [Static] [Export ("renderingProcessWithInterruptionHandler:completion:")] [Async] @@ -334,25 +320,24 @@ interface BERenderingProcess IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error); // Inlined from the CapabilityInvalidationHandler (BERenderingProcess) category - [NoTV, NoMac, iOS (17,6), MacCatalyst (17, 6)] + [NoTV, NoMac, iOS (17, 6), MacCatalyst (17, 6)] [Export ("grantCapability:error:invalidationHandler:")] [return: NullAllowed] IBEProcessCapabilityGrant GrantCapability (BEProcessCapability capability, [NullAllowed] out NSError error, Action invalidationHandler); } // Headers say this is available on macOS 14.3, but the BETextInput type isn't, so just remove this type from macOS as well. - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (NSObject))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BETextInputDelegate - { + interface BETextInputDelegate { [Abstract] [Export ("shouldDeferEventHandlingToSystemForTextInput:context:")] bool ShouldDeferEventHandlingToSystem (IBETextInput textInput, BEKeyEntryContext keyEventContext); [Abstract] [Export ("textInput:setCandidateSuggestions:")] - void SetCandidateSuggestions (IBETextInput textInput, [NullAllowed] BETextSuggestion[] suggestions); + void SetCandidateSuggestions (IBETextInput textInput, [NullAllowed] BETextSuggestion [] suggestions); [Abstract] [Export ("selectionWillChangeForTextInput:")] @@ -371,21 +356,19 @@ interface BETextInputDelegate void InvalidateTextEntryContext (IBETextInput textInput); } - interface IBETextInputDelegate {} + interface IBETextInputDelegate { } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BEKeyPressState : long - { + public enum BEKeyPressState : long { Down = 1, Up = 2, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEKeyEntry - { + interface BEKeyEntry { [Export ("key")] UIKey Key { get; } @@ -399,10 +382,9 @@ interface BEKeyEntry double Timestamp { get; } } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BEGestureType : long - { + public enum BEGestureType : long { Loupe = 0, OneFingerTap = 1, DoubleTapAndHold = 2, @@ -415,10 +397,9 @@ public enum BEGestureType : long ForceTouch = 15, } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BESelectionTouchPhase : long - { + public enum BESelectionTouchPhase : long { Started, Moved, Ended, @@ -428,51 +409,46 @@ public enum BESelectionTouchPhase : long } [Flags] - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BESelectionFlags : ulong - { + public enum BESelectionFlags : ulong { None = 0x0, WordIsNearTap = 1uL << 0, SelectionFlipped = 1uL << 1, PhraseBoundaryChanged = 1uL << 2, } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextAlternatives - { + interface BETextAlternatives { [Export ("primaryString")] string PrimaryString { get; } [Export ("alternativeStrings")] - string[] AlternativeStrings { get; } + string [] AlternativeStrings { get; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Flags] [Native] - public enum BETextReplacementOptions : ulong - { + public enum BETextReplacementOptions : ulong { None = 0x0, AddUnderline = 1uL << 0, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Flags] [Native] - public enum BEKeyModifierFlags : long - { + public enum BEKeyModifierFlags : long { None, Shift, CapsLock, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEResponderEditActions : UIResponderStandardEditActions - { + interface BEResponderEditActions : UIResponderStandardEditActions { [Export ("share:")] void Share ([NullAllowed] NSObject sender); @@ -498,10 +474,9 @@ interface BEResponderEditActions : UIResponderStandardEditActions void TransliterateChinese ([NullAllowed] NSObject sender); } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BETextSelectionDirectionNavigation - { + interface BETextSelectionDirectionNavigation { [Abstract] [Export ("moveInLayoutDirection:")] void MoveInLayoutDirection (UITextLayoutDirection direction); @@ -519,10 +494,9 @@ interface BETextSelectionDirectionNavigation void ExtendInStorageDirection (UITextStorageDirection direction, UITextGranularity granularity); } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEExtendedTextInputTraits : UITextInputTraits - { + interface BEExtendedTextInputTraits : UITextInputTraits { [Export ("singleLineDocument")] bool SingleLineDocument { [Bind ("isSingleLineDocument")] get; } @@ -539,17 +513,16 @@ interface BEExtendedTextInputTraits : UITextInputTraits UIColor SelectionHighlightColor { get; } } - interface IBEExtendedTextInputTraits {} + interface IBEExtendedTextInputTraits { } delegate void BETextInputHandleKeyEntryCallback (BEKeyEntry entry, bool handled); - delegate void BETextInputReplaceTextCallback (UITextSelectionRect[] rects); + delegate void BETextInputReplaceTextCallback (UITextSelectionRect [] rects); delegate void BETextInputRequestTextContextForAutocorrectionCallback (BETextDocumentContext context); - delegate void BETextInputRequestTextRectsCallback (UITextSelectionRect[] rects); + delegate void BETextInputRequestTextRectsCallback (UITextSelectionRect [] rects); - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BEResponderEditActions - { + interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BEResponderEditActions { [Wrap ("WeakAsyncInputDelegate"), Abstract] [NullAllowed] IBETextInputDelegate AsyncInputDelegate { get; set; } @@ -677,7 +650,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Abstract] [Export ("selectionRectsForRange:")] - UITextSelectionRect[] GetSelectionRects (UITextRange range); + UITextSelectionRect [] GetSelectionRects (UITextRange range); [Abstract] [Export ("selectWordForReplacement")] @@ -766,7 +739,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Abstract] [return: NullAllowed] [Export ("alternativesForSelectedText")] - BETextAlternatives[] GetAlternativesForSelectedText (); + BETextAlternatives [] GetAlternativesForSelectedText (); [Abstract] [Export ("addTextAlternatives:")] @@ -776,7 +749,7 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Export ("insertTextAlternatives:")] void InsertTextAlternatives (BETextAlternatives alternatives); - [iOS (18,0), MacCatalyst (18, 0), TV (18, 0)] + [iOS (18, 0), MacCatalyst (18, 0), TV (18, 0)] [Export ("removeTextAlternatives")] void RemoveTextAlternatives (); @@ -824,18 +797,17 @@ interface BETextInput : UIKeyInput, BETextSelectionDirectionNavigation, BERespon [Export ("cancelAutoscroll")] void CancelAutoscroll (); - [iOS (18,0), MacCatalyst (18, 0), TV (18, 0)] + [iOS (18, 0), MacCatalyst (18, 0), TV (18, 0)] [Export ("keyboardWillDismiss")] void KeyboardWillDismiss (); } - interface IBETextInput {} + interface IBETextInput { } - [TV (17, 4), Mac (14, 4), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), Mac (14, 4), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextSuggestion - { + interface BETextSuggestion { [Export ("initWithInputText:")] NativeHandle Constructor (string inputText); @@ -843,19 +815,17 @@ interface BETextSuggestion string InputText { get; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(BETextSuggestion))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (BETextSuggestion))] [DisableDefaultCtor] - interface BEAutoFillTextSuggestion - { + interface BEAutoFillTextSuggestion { [Export ("contents", ArgumentSemantic.Copy)] NSDictionary Contents { get; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] - interface BETextInteraction : UIInteraction - { + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] + interface BETextInteraction : UIInteraction { [Wrap ("WeakDelegate")] [NullAllowed] IBETextInteractionDelegate Delegate { get; set; } @@ -916,11 +886,10 @@ interface BETextInteraction : UIInteraction } // Headers say this is available on macOS 14.3, but the BETextInteraction type isn't, so just remove this type from macOS as well. - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [BaseType (typeof (NSObject))] [Protocol (BackwardsCompatibleCodeGeneration = false), Model] - interface BETextInteractionDelegate - { + interface BETextInteractionDelegate { [Abstract] [Export ("systemWillChangeSelectionForInteraction:")] void SystemWillChangeSelection (BETextInteraction textInteraction); @@ -930,13 +899,12 @@ interface BETextInteractionDelegate void SystemDidChangeSelection (BETextInteraction textInteraction); } - interface IBETextInteractionDelegate {} + interface IBETextInteractionDelegate { } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEKeyEntryContext - { + interface BEKeyEntryContext { [Export ("keyEntry", ArgumentSemantic.Strong)] BEKeyEntry KeyEntry { get; } @@ -955,10 +923,9 @@ interface BEKeyEntryContext } [Flags] - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] [Native] - public enum BETextDocumentRequestOptions : long - { + public enum BETextDocumentRequestOptions : long { None = 0x0, Text = 1L << 0, AttributedText = 1L << 1, @@ -967,11 +934,10 @@ public enum BETextDocumentRequestOptions : long AutocorrectedRanges = 1L << 7, } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextDocumentRequest - { + interface BETextDocumentRequest { [Export ("options", ArgumentSemantic.Assign)] BETextDocumentRequestOptions Options { get; set; } @@ -982,11 +948,10 @@ interface BETextDocumentRequest nint GranularityCount { get; set; } } - [TV (17, 4), NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [TV (17, 4), NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BETextDocumentContext - { + interface BETextDocumentContext { [Export ("initWithSelectedText:contextBefore:contextAfter:markedText:selectedRangeInMarkedText:")] NativeHandle Constructor ([NullAllowed] string selectedText, [NullAllowed] string contextBefore, [NullAllowed] string contextAfter, [NullAllowed] string markedText, NSRange selectedRangeInMarkedText); @@ -997,13 +962,12 @@ interface BETextDocumentContext void AddTextRect (CGRect rect, NSRange range); [Export ("autocorrectedRanges", ArgumentSemantic.Copy)] - NSValue[] AutocorrectedRanges { get; set; } + NSValue [] AutocorrectedRanges { get; set; } } - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEProcessCapabilityGrant - { + interface BEProcessCapabilityGrant { [Abstract] [Export ("invalidate")] bool Invalidate (); @@ -1013,13 +977,12 @@ interface BEProcessCapabilityGrant bool Valid { [Bind ("isValid")] get; } } - interface IBEProcessCapabilityGrant {} + interface IBEProcessCapabilityGrant { } - [NoTV, NoMac, iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, NoMac, iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEMediaEnvironment - { + interface BEMediaEnvironment { [Export ("initWithWebPageURL:")] [DesignatedInitializer] NativeHandle Constructor (NSUrl url); @@ -1041,11 +1004,10 @@ interface BEMediaEnvironment AVCaptureSession MakeCaptureSession ([NullAllowed] out NSError error); } - [NoTV, Mac (14,3), iOS (17,4), MacCatalyst (17, 4)] - [BaseType (typeof(NSObject))] + [NoTV, Mac (14, 3), iOS (17, 4), MacCatalyst (17, 4)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEProcessCapability - { + interface BEProcessCapability { [NoMac] [Static] [Export ("mediaPlaybackAndCaptureWithEnvironment:")] @@ -1067,11 +1029,10 @@ interface BEProcessCapability IBEProcessCapabilityGrant Request ([NullAllowed] out NSError error); } - [TV (17, 5), Mac (14, 5), iOS (17,5), MacCatalyst (17, 5)] - [BaseType (typeof(NSObject))] + [TV (17, 5), Mac (14, 5), iOS (17, 5), MacCatalyst (17, 5)] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEWebAppManifest - { + interface BEWebAppManifest { [Export ("initWithJSONData:manifestURL:")] [DesignatedInitializer] NativeHandle Constructor (NSData jsonData, NSUrl manifestUrl); @@ -1085,8 +1046,7 @@ interface BEWebAppManifest [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Native] - public enum BEAccessibilityPressedState : long - { + public enum BEAccessibilityPressedState : long { Undefined = 0, False, True, @@ -1096,8 +1056,7 @@ public enum BEAccessibilityPressedState : long [Flags] [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Native] - public enum BEAccessibilityContainerType : ulong - { + public enum BEAccessibilityContainerType : ulong { None = 0x0, Landmark = 1uL << 0, Table = 1uL << 1, @@ -1116,8 +1075,7 @@ public enum BEAccessibilityContainerType : ulong [TV (18, 0), Mac (15, 0), iOS (18, 0), MacCatalyst (18, 0)] [Category] [BaseType (typeof (NSObject))] - interface NSObject_BEAccessibility - { + interface NSObject_BEAccessibility { [Export ("browserAccessibilityCurrentStatus")] [return: NullAllowed] string GetBrowserAccessibilityCurrentStatus (); @@ -1225,14 +1183,12 @@ public enum BEAccessibilityNotification : long { [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] - interface BEAccessibilityTextMarker : NSCopying, NSSecureCoding - { + interface BEAccessibilityTextMarker : NSCopying, NSSecureCoding { } [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] - interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding - { + interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding { [Export ("startMarker", ArgumentSemantic.Strong)] BEAccessibilityTextMarker StartMarker { get; set; } @@ -1242,8 +1198,7 @@ interface BEAccessibilityTextMarkerRange : NSCopying, NSSecureCoding [iOS (18, 2), TV (18, 2), Mac (15, 2), MacCatalyst (18, 2)] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface BEAccessibilityTextMarkerSupport - { + interface BEAccessibilityTextMarkerSupport { [Abstract] [Export ("accessibilityBoundsForTextMarkerRange:")] CGRect GetAccessibilityBounds (BEAccessibilityTextMarkerRange range); @@ -1305,8 +1260,7 @@ interface BEAccessibilityTextMarkerSupport [NoTV, NoMac, iOS (18, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEDownloadMonitorLocation - { + interface BEDownloadMonitorLocation { [Export ("url")] NSUrl Url { get; } @@ -1321,8 +1275,7 @@ interface BEDownloadMonitorLocation [NoTV, NoMac, iOS (18, 2), MacCatalyst (18, 2)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface BEDownloadMonitor - { + interface BEDownloadMonitor { [Export ("initWithSourceURL:destinationURL:observedProgress:liveActivityAccessToken:")] NativeHandle Constructor (NSUrl sourceUrl, NSUrl destinationUrl, NSProgress observedProgress, NSData liveActivityAccessToken); diff --git a/src/contactsui.cs b/src/contactsui.cs index 21e5fb594382..e4bafaa3c6aa 100644 --- a/src/contactsui.cs +++ b/src/contactsui.cs @@ -69,11 +69,12 @@ interface CNContactPickerViewController { interface ICNContactPickerDelegate { } #if MONOMAC - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface CNContactPickerDelegate - { + [BaseType (typeof (NSObject))] + interface CNContactPickerDelegate { [Export ("contactPicker:didSelectContact:")] void ContactSelected (CNContactPicker picker, CNContact contact); diff --git a/src/coreanimation.cs b/src/coreanimation.cs index 929bd78831e8..701e61be1182 100644 --- a/src/coreanimation.cs +++ b/src/coreanimation.cs @@ -1272,7 +1272,8 @@ interface CALayerDelegate { /// /// /// Apple documentation for CAEAGLLayer - [NoMac][NoMacCatalyst] + [NoMac] + [NoMacCatalyst] [Deprecated (PlatformName.TvOS, 12, 0, message: "Use 'CAMetalLayer' instead.")] [Deprecated (PlatformName.iOS, 12, 0, message: "Use 'CAMetalLayer' instead.")] [BaseType (typeof (CALayer))] @@ -1301,7 +1302,7 @@ interface CAAction { /// [BaseType (typeof (NSObject) #if NET - , Delegates = new string [] {"WeakDelegate"}, Events = new Type [] { typeof (CAAnimationDelegate) } + , Delegates = new string [] { "WeakDelegate" }, Events = new Type [] { typeof (CAAnimationDelegate) } #endif )] interface CAAnimation : CAAction, CAMediaTiming, NSSecureCoding, NSMutableCopying, SCNAnimationProtocol { diff --git a/src/coredata.cs b/src/coredata.cs index 5b807e12de6c..6fd01dfced52 100644 --- a/src/coredata.cs +++ b/src/coredata.cs @@ -624,7 +624,7 @@ interface NSFetchedResultsController { string GetSectionIndexTitle (string sectionName); [Export ("sectionIndexTitles")] - string[] SectionIndexTitles { get; } + string [] SectionIndexTitles { get; } #endif [Static] @@ -895,7 +895,7 @@ interface NSManagedObject : NSFetchRequestResult { #if XAMCORE_5_0 NSDictionary GetCommittedValues ([NullAllowed] string[] keys); #elif NET - NSDictionary GetCommittedValues ([NullAllowed] string[] keys); + NSDictionary GetCommittedValues ([NullAllowed] string [] keys); #else NSDictionary CommittedValuesForKeys ([NullAllowed] string [] keys); #endif @@ -1271,7 +1271,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { [Static, Export ("mergedModelFromBundles:")] [return: NullAllowed] #if NET - NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles); + NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle [] bundles); #else NSManagedObjectModel MergedModelFromBundles ([NullAllowed] NSBundle [] bundles); #endif @@ -1337,7 +1337,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { #if XAMCORE_5_0 NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles, NSDictionary metadata); #elif NET - NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle[] bundles, NSDictionary metadata); + NSManagedObjectModel GetMergedModel ([NullAllowed] NSBundle [] bundles, NSDictionary metadata); #else NSManagedObjectModel MergedModelFromBundles ([NullAllowed] NSBundle [] bundles, NSDictionary metadata); #endif @@ -1347,7 +1347,7 @@ interface NSManagedObjectModel : NSCoding, NSCopying { #if XAMCORE_5_0 NSManagedObjectModel GetModelByMerging (NSManagedObjectModel[] models, NSDictionary metadata); #elif NET - NSManagedObjectModel GetModelByMerging (NSManagedObjectModel[] models, NSDictionary metadata); + NSManagedObjectModel GetModelByMerging (NSManagedObjectModel [] models, NSDictionary metadata); #else NSManagedObjectModel ModelByMergingModels (NSManagedObjectModel [] models, NSDictionary metadata); #endif @@ -1395,7 +1395,7 @@ interface NSMappingModel { [Static, Export ("mappingModelFromBundles:forSourceModel:destinationModel:")] [return: NullAllowed] #if NET - NSMappingModel GetMappingModel ([NullAllowed] NSBundle[] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); + NSMappingModel GetMappingModel ([NullAllowed] NSBundle [] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); #else NSMappingModel MappingModelFromBundles ([NullAllowed] NSBundle [] bundles, [NullAllowed] NSManagedObjectModel sourceModel, [NullAllowed] NSManagedObjectModel destinationModel); #endif @@ -2386,7 +2386,7 @@ interface NSAsynchronousFetchResult { [Export ("finalResult", ArgumentSemantic.Retain)] [NullAllowed] #if NET - INSFetchRequestResult[] FinalResult { get; } + INSFetchRequestResult [] FinalResult { get; } #else NSObject [] FinalResult { get; } #endif diff --git a/src/corehaptics.cs b/src/corehaptics.cs index dd6df1f4d4a5..150be43b5014 100644 --- a/src/corehaptics.cs +++ b/src/corehaptics.cs @@ -22,7 +22,7 @@ namespace CoreHaptics { // we are not binding the API on Mac OS X yet due to an issue on Apples side: https://github.com/xamarin/maccore/issues/1951 #if MONOMAC || TV - interface AVAudioSession {} + interface AVAudioSession { } #endif [iOS (13, 0), TV (14, 0)] diff --git a/src/coreimage.cs b/src/coreimage.cs index be8db0eee89f..1a2bb50e4a2f 100644 --- a/src/coreimage.cs +++ b/src/coreimage.cs @@ -256,14 +256,16 @@ interface CIContext { CIContext Create (); #if HAS_OPENGLES - [NoMac][NoMacCatalyst] + [NoMac] + [NoMacCatalyst] [Deprecated (PlatformName.iOS, 12, 0)] [Deprecated (PlatformName.TvOS, 12, 0)] [Static] [Export ("contextWithEAGLContext:")] CIContext FromContext (EAGLContext eaglContext); - [NoMac][NoMacCatalyst] + [NoMac] + [NoMacCatalyst] [Deprecated (PlatformName.iOS, 12, 0)] [Deprecated (PlatformName.TvOS, 12, 0)] [Static] diff --git a/src/corelocation.cs b/src/corelocation.cs index 07b38a503d6e..f728e652bfee 100644 --- a/src/corelocation.cs +++ b/src/corelocation.cs @@ -58,7 +58,7 @@ public enum CLProximity : long { [ErrorDomain ("CLLocationPushServiceErrorDomain")] #if NET // Apple fixed this in Xcode 13.1 - [iOS (15,0), NoTV, NoMacCatalyst, NoMac] + [iOS (15, 0), NoTV, NoMacCatalyst, NoMac] #else [iOS (15, 0), NoTV, MacCatalyst (15, 0), NoMac] #endif @@ -1064,7 +1064,7 @@ interface CLBeaconIdentityConstraint : NSCopying, NSSecureCoding { } #if NET // Apple fixed this in Xcode 13.1 - [iOS (15,0), NoTV, NoMacCatalyst, NoMac] + [iOS (15, 0), NoTV, NoMacCatalyst, NoMac] #else [iOS (15, 0), NoTV, MacCatalyst (15, 0), NoMac] #endif diff --git a/src/corenfc.cs b/src/corenfc.cs index bcabf9246b31..49d22130a2d8 100644 --- a/src/corenfc.cs +++ b/src/corenfc.cs @@ -870,7 +870,7 @@ enum VasErrorCode [MacCatalyst (13, 1)] #if NET [Native] - enum NFCVasMode + enum NFCVasMode #else [Native ("NFCVASMode")] enum VasMode @@ -1071,7 +1071,8 @@ interface INFCTagReaderSessionDelegate { } [iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -1119,7 +1120,8 @@ interface INFCVasReaderSessionDelegate { } [iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/coretext.cs b/src/coretext.cs index bb02cfff3cd8..40d28ebdfb86 100644 --- a/src/coretext.cs +++ b/src/coretext.cs @@ -126,7 +126,8 @@ interface CTFontManagerErrorKeys { #if NET [Internal] - [Static][Partial] + [Static] + [Partial] interface CTBaselineClassID { [Field ("kCTBaselineClassRoman")] NSString Roman { get; } @@ -148,7 +149,8 @@ interface CTBaselineClassID { } [Internal] - [Static][Partial] + [Static] + [Partial] interface CTBaselineFontID { [Field ("kCTBaselineReferenceFont")] NSString Reference { get; } @@ -274,7 +276,8 @@ interface CTFontTraitKey { } [Internal] - [Static][Partial] + [Static] + [Partial] interface CTFontNameKeyId { [Field ("kCTFontCopyrightNameKey")] NSString Copyright { get; } diff --git a/src/cryptotokenkit.cs b/src/cryptotokenkit.cs index 7da6fd74417a..cd5de12aa674 100644 --- a/src/cryptotokenkit.cs +++ b/src/cryptotokenkit.cs @@ -20,8 +20,7 @@ namespace CryptoTokenKit { [Native] [ErrorDomain ("TKErrorDomain")] [iOS (9, 0), Mac (10, 10), MacCatalyst (13, 1), TV (9, 0)] - public enum TKErrorCode : long - { + public enum TKErrorCode : long { NotImplemented = -1, CommunicationError = -2, CorruptedData = -3, @@ -38,8 +37,7 @@ public enum TKErrorCode : long #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] [Native] - public enum TKSmartCardSlotState : long - { + public enum TKSmartCardSlotState : long { Missing = 0, Empty = 1, Probing = 2, @@ -52,8 +50,7 @@ public enum TKSmartCardSlotState : long #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINCharset")] - public enum TKSmartCardPinCharset : long - { + public enum TKSmartCardPinCharset : long { Numeric = 0, Alphanumeric = 1, UpperAlphanumeric = 2, @@ -64,8 +61,7 @@ public enum TKSmartCardPinCharset : long #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINEncoding")] - public enum TKSmartCardPinEncoding : long - { + public enum TKSmartCardPinEncoding : long { Binary = 0, Ascii = 1, Bcd = 2, @@ -76,8 +72,7 @@ public enum TKSmartCardPinEncoding : long #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINJustification")] - public enum TKSmartCardPinJustification : long - { + public enum TKSmartCardPinJustification : long { Left = 0, Right = 1, } @@ -88,8 +83,7 @@ public enum TKSmartCardPinJustification : long [Flags] [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINCompletion")] - public enum TKSmartCardPinCompletion : ulong - { + public enum TKSmartCardPinCompletion : ulong { MaxLength = (1uL << 0), Key = (1uL << 1), Timeout = (1uL << 2), @@ -101,8 +95,7 @@ public enum TKSmartCardPinCompletion : ulong [Flags] [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Native ("TKSmartCardPINConfirmation")] - public enum TKSmartCardPinConfirmation : ulong - { + public enum TKSmartCardPinConfirmation : ulong { None = 0x0, New = (1uL << 0), Current = (1uL << 1), @@ -114,8 +107,7 @@ public enum TKSmartCardPinConfirmation : ulong [Flags] [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] [Native] - public enum TKSmartCardProtocol : ulong - { + public enum TKSmartCardProtocol : ulong { None = 0x0, T0 = (1uL << 0), T1 = (1uL << 1), @@ -128,8 +120,7 @@ public enum TKSmartCardProtocol : ulong #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Native] - public enum TKTokenOperation : long - { + public enum TKTokenOperation : long { None = 0, ReadData = 1, SignData = 2, @@ -142,8 +133,7 @@ public enum TKTokenOperation : long #endif [iOS (13, 0), Mac (10, 12), MacCatalyst (13, 1), TV (13, 0)] [Protocol] - interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate - { + interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate { [Abstract] [Export ("tokenDriver:createTokenForSmartCard:AID:error:")] [return: NullAllowed] @@ -153,15 +143,14 @@ interface TKSmartCardTokenDriverDelegate : TKTokenDriverDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKSmartCardTokenDriverDelegate {} + interface ITKSmartCardTokenDriverDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [Protocol] - interface TKSmartCardUserInteractionDelegate - { + interface TKSmartCardUserInteractionDelegate { [Export ("characterEnteredInUserInteraction:")] void CharacterEntered (TKSmartCardUserInteraction interaction); @@ -187,16 +176,15 @@ interface TKSmartCardUserInteractionDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKSmartCardUserInteractionDelegate {} + interface ITKSmartCardUserInteractionDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface TKTokenDelegate - { + [BaseType (typeof (NSObject))] + interface TKTokenDelegate { [Abstract] [Export ("token:createSessionWithError:")] [return: NullAllowed] @@ -209,17 +197,16 @@ interface TKTokenDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenDelegate {} + interface ITKTokenDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface TKTokenDriverDelegate - { - [TV (14,0), Mac (10,15), iOS (14,0)] + [BaseType (typeof (NSObject))] + interface TKTokenDriverDelegate { + [TV (14, 0), Mac (10, 15), iOS (14, 0)] [Export ("tokenDriver:tokenForConfiguration:error:")] [return: NullAllowed] TKToken GetToken (TKTokenDriver driver, TKTokenConfiguration configuration, [NullAllowed] out NSError error); @@ -231,16 +218,15 @@ interface TKTokenDriverDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenDriverDelegate {} + interface ITKTokenDriverDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface TKTokenSessionDelegate - { + [BaseType (typeof (NSObject))] + interface TKTokenSessionDelegate { [Export ("tokenSession:beginAuthForOperation:constraint:error:")] [return: NullAllowed] TKTokenAuthOperation BeginAuthentication (TKTokenSession session, TKTokenOperation operation, NSObject constraint, [NullAllowed] out NSError error); @@ -264,15 +250,14 @@ interface TKTokenSessionDelegate #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif - interface ITKTokenSessionDelegate {} + interface ITKTokenSessionDelegate { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTlvRecord), Name = "TKBERTLVRecord")] - interface TKBerTlvRecord - { + [BaseType (typeof (TKTlvRecord), Name = "TKBERTLVRecord")] + interface TKBerTlvRecord { [Static] [Export ("dataForTag:")] NSData GetData (ulong tag); @@ -281,16 +266,15 @@ interface TKBerTlvRecord NativeHandle Constructor (ulong tag, NSData value); [Export ("initWithTag:records:")] - NativeHandle Constructor (ulong tag, TKTlvRecord[] records); + NativeHandle Constructor (ulong tag, TKTlvRecord [] records); } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTlvRecord), Name = "TKCompactTLVRecord")] - interface TKCompactTlvRecord - { + [BaseType (typeof (TKTlvRecord), Name = "TKCompactTLVRecord")] + interface TKCompactTlvRecord { [Export ("initWithTag:value:")] NativeHandle Constructor (byte tag, NSData value); } @@ -299,9 +283,8 @@ interface TKCompactTlvRecord [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTlvRecord), Name = "TKSimpleTLVRecord")] - interface TKSimpleTlvRecord - { + [BaseType (typeof (TKTlvRecord), Name = "TKSimpleTLVRecord")] + interface TKSimpleTlvRecord { [Export ("initWithTag:value:")] NativeHandle Constructor (byte tag, NSData value); } @@ -320,9 +303,8 @@ interface TKSimpleTlvRecord [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] - interface TKSmartCard - { + [BaseType (typeof (NSObject))] + interface TKSmartCard { [Export ("slot")] TKSmartCardSlot Slot { get; } @@ -377,11 +359,11 @@ interface TKSmartCard [Export ("sendIns:p1:p2:data:le:reply:")] void Send (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, TKSmartCardSendCallback reply); - [Mac (10,12)] + [Mac (10, 12)] [Export ("inSessionWithError:executeBlock:")] bool ExecuteBlock ([NullAllowed] out NSError error, TKSmartCardExecuteCallback block); - [Mac (10,12)] + [Mac (10, 12)] [Export ("sendIns:p1:p2:data:le:sw:error:")] [return: NullAllowed] NSData Send (byte ins, byte p1, byte p2, [NullAllowed] NSData requestData, [NullAllowed] NSNumber le, out ushort sw, [NullAllowed] out NSError error); @@ -391,10 +373,9 @@ interface TKSmartCard [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject), Name = "TKSmartCardATR")] + [BaseType (typeof (NSObject), Name = "TKSmartCardATR")] [DisableDefaultCtor] - interface TKSmartCardAtr - { + interface TKSmartCardAtr { [Export ("initWithBytes:")] NativeHandle Constructor (NSData bytes); @@ -405,8 +386,8 @@ interface TKSmartCardAtr NSData Bytes { get; } [Export ("protocols")] - [BindAs (typeof (TKSmartCardProtocol[]))] - NSNumber[] Protocols { get; } + [BindAs (typeof (TKSmartCardProtocol []))] + NSNumber [] Protocols { get; } // -(TKSmartCardATRInterfaceGroup * _Nullable)interfaceGroupAtIndex:(NSInteger)index; [Export ("interfaceGroupAtIndex:")] @@ -423,16 +404,15 @@ interface TKSmartCardAtr [Mac (10, 12)] [Export ("historicalRecords")] [NullAllowed] - TKCompactTlvRecord[] HistoricalRecords { get; } + TKCompactTlvRecord [] HistoricalRecords { get; } } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject), Name = "TKSmartCardATRInterfaceGroup")] - interface TKSmartCardAtrInterfaceGroup - { + [BaseType (typeof (NSObject), Name = "TKSmartCardATRInterfaceGroup")] + interface TKSmartCardAtrInterfaceGroup { [NullAllowed, Export ("TA")] NSNumber TA { get; } @@ -453,10 +433,9 @@ interface TKSmartCardAtrInterfaceGroup [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenSession - { + interface TKTokenSession { [Export ("initWithToken:")] [DesignatedInitializer] NativeHandle Constructor (TKToken token); @@ -476,9 +455,8 @@ interface TKTokenSession [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject), Name = "TKSmartCardPINFormat")] - interface TKSmartCardPinFormat - { + [BaseType (typeof (NSObject), Name = "TKSmartCardPINFormat")] + interface TKSmartCardPinFormat { [Export ("charset", ArgumentSemantic.Assign)] TKSmartCardPinCharset Charset { get; set; } @@ -511,9 +489,8 @@ interface TKSmartCardPinFormat [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] - interface TKSmartCardSlot - { + [BaseType (typeof (NSObject))] + interface TKSmartCardSlot { [Export ("state")] TKSmartCardSlotState State { get; } @@ -543,22 +520,21 @@ interface TKSmartCardSlot [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 10), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKSmartCardSlotManager - { + interface TKSmartCardSlotManager { [Static] [NullAllowed, Export ("defaultManager")] TKSmartCardSlotManager DefaultManager { get; } [Export ("slotNames")] - string[] SlotNames { get; } + string [] SlotNames { get; } [Export ("getSlotWithName:reply:")] [Async] void GetSlot (string name, TKGetSlotCallback reply); - [Mac (10,13)] + [Mac (10, 13)] [Export ("slotNamed:")] [return: NullAllowed] TKSmartCardSlot GetSlot (string name); @@ -568,9 +544,8 @@ interface TKSmartCardSlotManager [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKToken))] - interface TKSmartCardToken - { + [BaseType (typeof (TKToken))] + interface TKSmartCardToken { [Export ("initWithSmartCard:AID:instanceID:tokenDriver:")] [DesignatedInitializer] NativeHandle Constructor (TKSmartCard smartCard, [NullAllowed] NSData aid, string instanceId, TKSmartCardTokenDriver tokenDriver); @@ -584,17 +559,15 @@ interface TKSmartCardToken #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] [BaseType (typeof (TKTokenDriver))] - interface TKSmartCardTokenDriver - { + interface TKSmartCardTokenDriver { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenSession))] - interface TKSmartCardTokenSession - { + [BaseType (typeof (TKTokenSession))] + interface TKSmartCardTokenSession { // Re-implemented from base class. [Export ("initWithToken:")] [DesignatedInitializer] @@ -608,9 +581,8 @@ interface TKSmartCardTokenSession [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(NSObject))] - interface TKSmartCardUserInteraction - { + [BaseType (typeof (NSObject))] + interface TKSmartCardUserInteraction { [Wrap ("WeakDelegate")] [NullAllowed] ITKSmartCardUserInteractionDelegate Delegate { get; set; } @@ -636,15 +608,14 @@ interface TKSmartCardUserInteraction [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(TKSmartCardUserInteraction), Name = "TKSmartCardUserInteractionForPINOperation")] - interface TKSmartCardUserInteractionForPinOperation - { + [BaseType (typeof (TKSmartCardUserInteraction), Name = "TKSmartCardUserInteractionForPINOperation")] + interface TKSmartCardUserInteractionForPinOperation { [Export ("PINCompletion", ArgumentSemantic.Assign)] TKSmartCardPinCompletion PinCompletion { get; set; } // not clear from the documentation if we can BindAs this to something or not [NullAllowed, Export ("PINMessageIndices", ArgumentSemantic.Assign)] - NSNumber[] PinMessageIndices { get; set; } + NSNumber [] PinMessageIndices { get; set; } [NullAllowed, Export ("locale", ArgumentSemantic.Assign)] NSLocale Locale { get; set; } @@ -660,9 +631,8 @@ interface TKSmartCardUserInteractionForPinOperation [Experimental ("APL0001")] #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] - [BaseType (typeof(TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINChange")] - interface TKSmartCardUserInteractionForSecurePinChange - { + [BaseType (typeof (TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINChange")] + interface TKSmartCardUserInteractionForSecurePinChange { [Export ("PINConfirmation", ArgumentSemantic.Assign)] TKSmartCardPinConfirmation PinConfirmation { get; set; } } @@ -672,18 +642,16 @@ interface TKSmartCardUserInteractionForSecurePinChange #endif [iOS (13, 0), Mac (10, 11), MacCatalyst (13, 1), TV (13, 0)] [BaseType (typeof (TKSmartCardUserInteractionForPinOperation), Name = "TKSmartCardUserInteractionForSecurePINVerification")] - interface TKSmartCardUserInteractionForSecurePinVerification - { + interface TKSmartCardUserInteractionForSecurePinVerification { } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject), Name = "TKTLVRecord")] + [BaseType (typeof (NSObject), Name = "TKTLVRecord")] [DisableDefaultCtor] - interface TKTlvRecord - { + interface TKTlvRecord { [Export ("tag")] ulong Tag { get; } @@ -701,17 +669,16 @@ interface TKTlvRecord [Static] [Export ("sequenceOfRecordsFromData:")] [return: NullAllowed] - TKTlvRecord[] CreateSequenceOfRecords (NSData data); + TKTlvRecord [] CreateSequenceOfRecords (NSData data); } #if !STABLE_CRYPTOTOKENKIT [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKToken - { + interface TKToken { [Export ("initWithTokenDriver:instanceID:")] [DesignatedInitializer] NativeHandle Constructor (TKTokenDriver tokenDriver, string instanceId); @@ -738,9 +705,8 @@ interface TKToken [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenAuthOperation : NSSecureCoding - { + [BaseType (typeof (NSObject))] + interface TKTokenAuthOperation : NSSecureCoding { [Export ("finishWithError:")] bool Finish ([NullAllowed] out NSError error); } @@ -749,10 +715,9 @@ interface TKTokenAuthOperation : NSSecureCoding [Experimental ("APL0001")] #endif [iOS (14, 0), Mac (10, 15), MacCatalyst (14, 0), TV (14, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenConfiguration - { + interface TKTokenConfiguration { [Export ("instanceID")] string InstanceId { get; } @@ -760,7 +725,7 @@ interface TKTokenConfiguration NSData ConfigurationData { get; set; } [Export ("keychainItems", ArgumentSemantic.Copy)] - TKTokenKeychainItem[] KeychainItems { get; set; } + TKTokenKeychainItem [] KeychainItems { get; set; } [Export ("keyForObjectID:error:")] [return: NullAllowed] @@ -775,9 +740,8 @@ interface TKTokenConfiguration [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenDriver - { + [BaseType (typeof (NSObject))] + interface TKTokenDriver { [Wrap ("WeakDelegate")] [NullAllowed] ITKTokenDriverDelegate Delegate { get; set; } @@ -790,10 +754,9 @@ interface TKTokenDriver [Experimental ("APL0001")] #endif [iOS (14, 0), Mac (10, 15), MacCatalyst (14, 0), TV (14, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenDriverConfiguration - { + interface TKTokenDriverConfiguration { [Static] [Export ("driverConfigurations")] NSDictionary DriverConfigurations { get; } @@ -815,10 +778,9 @@ interface TKTokenDriverConfiguration [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenKeyAlgorithm - { + interface TKTokenKeyAlgorithm { [Export ("isAlgorithm:")] bool IsAlgorithm ([BindAs (typeof (SecKeyAlgorithm))] NSString algorithm); @@ -830,9 +792,8 @@ interface TKTokenKeyAlgorithm [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenKeychainItem))] - interface TKTokenKeychainCertificate - { + [BaseType (typeof (TKTokenKeychainItem))] + interface TKTokenKeychainCertificate { [Export ("initWithCertificate:objectID:")] [DesignatedInitializer] NativeHandle Constructor ([BindAs (typeof (SecKeyAlgorithm))] NSString certificateRef, NSObject objectId); @@ -845,15 +806,14 @@ interface TKTokenKeychainCertificate [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenKeychainContents - { + interface TKTokenKeychainContents { [Export ("fillWithItems:")] - void Fill (TKTokenKeychainItem[] items); + void Fill (TKTokenKeychainItem [] items); [Export ("items", ArgumentSemantic.Copy)] - TKTokenKeychainItem[] Items { get; } + TKTokenKeychainItem [] Items { get; } [Export ("keyForObjectID:error:")] [return: NullAllowed] @@ -868,10 +828,9 @@ interface TKTokenKeychainContents [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenKeychainItem - { + interface TKTokenKeychainItem { [Export ("initWithObjectID:")] [DesignatedInitializer] NativeHandle Constructor (NSObject objectId); @@ -890,9 +849,8 @@ interface TKTokenKeychainItem [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenKeychainItem))] - interface TKTokenKeychainKey - { + [BaseType (typeof (TKTokenKeychainItem))] + interface TKTokenKeychainKey { [Export ("initWithCertificate:objectID:")] [DesignatedInitializer] NativeHandle Constructor (IntPtr certificate, NSObject objectId); @@ -932,9 +890,8 @@ interface TKTokenKeychainKey [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenKeyExchangeParameters - { + [BaseType (typeof (NSObject))] + interface TKTokenKeyExchangeParameters { [Export ("requestedSize")] nint RequestedSize { get; } @@ -946,9 +903,8 @@ interface TKTokenKeyExchangeParameters [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenAuthOperation))] - interface TKTokenPasswordAuthOperation - { + [BaseType (typeof (TKTokenAuthOperation))] + interface TKTokenPasswordAuthOperation { [NullAllowed, Export ("password")] string Password { get; set; } } @@ -957,9 +913,8 @@ interface TKTokenPasswordAuthOperation [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(TKTokenAuthOperation), Name = "TKTokenSmartCardPINAuthOperation")] - interface TKTokenSmartCardPinAuthOperation - { + [BaseType (typeof (TKTokenAuthOperation), Name = "TKTokenSmartCardPINAuthOperation")] + interface TKTokenSmartCardPinAuthOperation { [Export ("PINFormat", ArgumentSemantic.Assign)] TKSmartCardPinFormat PinFormat { get; set; } @@ -980,11 +935,10 @@ interface TKTokenSmartCardPinAuthOperation [Experimental ("APL0001")] #endif [iOS (10, 0), Mac (10, 12), MacCatalyst (13, 1), TV (11, 0)] - [BaseType (typeof(NSObject))] - interface TKTokenWatcher - { + [BaseType (typeof (NSObject))] + interface TKTokenWatcher { [Export ("tokenIDs")] - string[] TokenIds { get; } + string [] TokenIds { get; } // -(instancetype _Nonnull)initWithInsertionHandler:(void (^ _Nonnull)(NSString * _Nonnull))insertionHandler __attribute__((availability(macos, introduced=10.12, deprecated=10.13))) __attribute__((availability(ios, introduced=10.0, deprecated=11.0))); [Deprecated (PlatformName.MacOSX, 10, 13, "Use the default constructor followed by a call to the 'SetInsertionHandler' method.")] @@ -1011,10 +965,9 @@ interface TKTokenWatcher [Experimental ("APL0001")] #endif [iOS (15, 0), Mac (12, 0), MacCatalyst (15, 0), TV (15, 0)] - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface TKTokenWatcherTokenInfo - { + interface TKTokenWatcherTokenInfo { [Export ("tokenID")] string TokenId { get; } diff --git a/src/eventkit.cs b/src/eventkit.cs index 00c950adde57..1727818fcdbd 100644 --- a/src/eventkit.cs +++ b/src/eventkit.cs @@ -455,7 +455,7 @@ interface EKRecurrenceEnd : NSCopying, NSSecureCoding { interface EKRecurrenceDayOfWeek : NSCopying, NSSecureCoding { [Export ("dayOfTheWeek")] #if NET - EKWeekday DayOfTheWeek { get; } + EKWeekday DayOfTheWeek { get; } #else nint DayOfTheWeek { get; } #endif diff --git a/src/foundation.cs b/src/foundation.cs index 1779b7dfa1e0..98ee6f0a8983 100644 --- a/src/foundation.cs +++ b/src/foundation.cs @@ -6024,7 +6024,9 @@ string SuggestedInvocationPhrase { #if HAS_APPCLIP // Inlined from NSUserActivity (AppClip) - [iOS (14,0)][NoTV][NoMac] + [iOS (14, 0)] + [NoTV] + [NoMac] [MacCatalyst (14, 0)] [Export ("appClipActivationPayload", ArgumentSemantic.Strong)] [NullAllowed] @@ -9475,7 +9477,7 @@ interface NSLinguisticAnalysis { [Wrap ("GetLinguisticTags (This, range, scheme.GetConstant ()!, options, orthography, out tokenRanges)")] #if NET - NSLinguisticTag[] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue[] tokenRanges); + NSLinguisticTag [] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue [] tokenRanges); #else NSLinguisticTagUnit [] GetLinguisticTags (NSRange range, NSLinguisticTagScheme scheme, NSLinguisticTaggerOptions options, [NullAllowed] NSOrthography orthography, [NullAllowed] out NSValue [] tokenRanges); #endif @@ -9675,9 +9677,11 @@ interface NSObject2 : NSObjectProtocol { [Export ("exposedBindings")] NSString [] ExposedBindings (); #else - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] [Export ("exposedBindings")] - NSString[] ExposedBindings { get; } + NSString [] ExposedBindings { get; } #endif #if !NET @@ -14930,20 +14934,24 @@ interface NSFileProviderService { #if MONOMAC partial interface NSFilePresenter { - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] [NullAllowed] [Export ("primaryPresentedItemURL")] NSUrl PrimaryPresentedItemUrl { get; } } - [NoiOS][NoMacCatalyst][NoTV] - [Deprecated (PlatformName.MacOSX, 12, 0, message : "Use the Network.framework instead.")] + [NoiOS] + [NoMacCatalyst] + [NoTV] + [Deprecated (PlatformName.MacOSX, 12, 0, message: "Use the Network.framework instead.")] [BaseType (typeof (NSObject))] [DisableDefaultCtor] partial interface NSHost { [Static, Internal, Export ("currentHost")] - NSHost _Current { get;} + NSHost _Current { get; } [Static, Internal, Export ("hostWithName:")] NSHost _FromName ([NullAllowed] string name); @@ -14970,7 +14978,7 @@ partial interface NSHost { string _Address { get; } [Internal, Export ("addresses")] - string [] _Addresses { get; } + string [] _Addresses { get; } [Export ("hash"), Internal] nuint _Hash { get; } @@ -17668,7 +17676,8 @@ interface NSUrlSessionWebSocketTask { [TV (13, 0), iOS (13, 0)] [MacCatalyst (13, 1)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/gamekit.cs b/src/gamekit.cs index 8481c3ce6f1b..407a381b191f 100644 --- a/src/gamekit.cs +++ b/src/gamekit.cs @@ -58,10 +58,10 @@ namespace GameKit { delegate void GKEntriesForPlayersHandler (GKLeaderboardEntry localPlayerEntry, GKLeaderboardEntry [] entries, NSError error); #if MONOMAC - delegate void GKImageLoadedHandler (NSImage image, NSError error); + delegate void GKImageLoadedHandler (NSImage image, NSError error); delegate void GKPlayerPhotoLoaded (NSImage photo, NSError error); delegate void GKChallengeComposeHandler (NSViewController composeController, bool issuedChallenge, string [] sentPlayerIDs); - delegate void GKChallengeComposeHandler2 (NSViewController composeController, bool issuedChallenge, GKPlayer[] sentPlayers); + delegate void GKChallengeComposeHandler2 (NSViewController composeController, bool issuedChallenge, GKPlayer [] sentPlayers); #else delegate void GKImageLoadedHandler (UIImage image, NSError error); delegate void GKPlayerPhotoLoaded (UIImage photo, NSError error); @@ -765,8 +765,8 @@ interface GKLeaderboardViewControllerDelegate { [Deprecated (PlatformName.MacOSX, 10, 10, message: "Use 'GKGameCenterViewController' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'GKGameCenterViewController' instead.")] #if MONOMAC - [BaseType (typeof (GKGameCenterViewController), Events=new Type [] { typeof (GKLeaderboardViewControllerDelegate)}, Delegates=new string [] {"WeakDelegate"})] - interface GKLeaderboardViewController + [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKLeaderboardViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] + interface GKLeaderboardViewController #else [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKLeaderboardViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] interface GKLeaderboardViewController : UIAppearance @@ -1466,7 +1466,7 @@ interface GKMatchmaker { [MacCatalyst (13, 1)] #if MONOMAC - [BaseType (typeof (NSViewController), Delegates=new string [] { "WeakMatchmakerDelegate" }, Events=new Type [] {typeof(GKMatchmakerViewControllerDelegate)})] + [BaseType (typeof (NSViewController), Delegates = new string [] { "WeakMatchmakerDelegate" }, Events = new Type [] { typeof (GKMatchmakerViewControllerDelegate) })] #else [BaseType (typeof (UINavigationController), Delegates = new string [] { "WeakMatchmakerDelegate" }, Events = new Type [] { typeof (GKMatchmakerViewControllerDelegate) })] #endif @@ -1839,8 +1839,8 @@ interface GKAchievementViewControllerDelegate { [Deprecated (PlatformName.MacOSX, 10, 10, message: "Use 'GKGameCenterViewController' instead.")] [Deprecated (PlatformName.MacCatalyst, 13, 1, message: "Use 'GKGameCenterViewController' instead.")] #if MONOMAC - [BaseType (typeof (GKGameCenterViewController), Events=new Type [] { typeof (GKAchievementViewControllerDelegate)}, Delegates=new string [] {"WeakDelegate"})] - interface GKAchievementViewController + [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKAchievementViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] + interface GKAchievementViewController #else [BaseType (typeof (GKGameCenterViewController), Events = new Type [] { typeof (GKAchievementViewControllerDelegate) }, Delegates = new string [] { "WeakDelegate" })] interface GKAchievementViewController : UIAppearance @@ -1885,7 +1885,7 @@ interface GKDialogController { [NoTV] [Deprecated (PlatformName.MacCatalyst, 13, 1)] #if MONOMAC - [BaseType (typeof (NSViewController), Events=new Type [] { typeof (GKFriendRequestComposeViewControllerDelegate)}, Delegates=new string[] {"WeakComposeViewDelegate"})] + [BaseType (typeof (NSViewController), Events = new Type [] { typeof (GKFriendRequestComposeViewControllerDelegate) }, Delegates = new string [] { "WeakComposeViewDelegate" })] interface GKFriendRequestComposeViewController : GKViewController { [Export ("initWithNibName:bundle:")] [NoiOS] diff --git a/src/healthkit.cs b/src/healthkit.cs index a6acc3a0510a..52cc1a2262ec 100644 --- a/src/healthkit.cs +++ b/src/healthkit.cs @@ -220,7 +220,7 @@ public enum HKAudiogramSensitivityTestSide : long { #if NET /// The completion handler for . /// Completion handler for anchored object queries. - delegate void HKAnchoredObjectResultHandler (HKAnchoredObjectQuery query, HKSample[] results, nuint newAnchor, NSError error); + delegate void HKAnchoredObjectResultHandler (HKAnchoredObjectQuery query, HKSample [] results, nuint newAnchor, NSError error); #else delegate void HKAnchoredObjectResultHandler2 (HKAnchoredObjectQuery query, HKSample [] results, nuint newAnchor, NSError error); diff --git a/src/mapkit.cs b/src/mapkit.cs index 2a5bfe34006e..3a4245405bf5 100644 --- a/src/mapkit.cs +++ b/src/mapkit.cs @@ -28,11 +28,11 @@ using System; #if MONOMAC -using UIImage=AppKit.NSImage; -using UIView=AppKit.NSView; -using UIEdgeInsets=AppKit.NSEdgeInsets; -using UIColor=AppKit.NSColor; -using UIScene=AppKit.NSColor; +using UIImage = AppKit.NSImage; +using UIView = AppKit.NSView; +using UIEdgeInsets = AppKit.NSEdgeInsets; +using UIColor = AppKit.NSColor; +using UIScene = AppKit.NSColor; using UIControl = AppKit.NSControl; using UIBarButtonItem = Foundation.NSObject; using UIViewController = AppKit.NSViewController; diff --git a/src/mediaextension.cs b/src/mediaextension.cs index b7a7883c2c46..8706da954203 100644 --- a/src/mediaextension.cs +++ b/src/mediaextension.cs @@ -11,11 +11,10 @@ using UniformTypeIdentifiers; namespace MediaExtension { - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] [ErrorDomain ("MediaExtensionErrorDomain")] - public enum MEError : long - { + public enum MEError : long { UnsupportedFeature = -19320, AllocationFailure = -19321, InvalidParameter = -19322, @@ -30,37 +29,33 @@ public enum MEError : long ReferenceMissing = -19331, } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] - public enum MEFileInfoFragmentsStatus : long - { + public enum MEFileInfoFragmentsStatus : long { CouldNotContainFragments = 0, ContainsFragments = 1, CouldContainButDoesNotContainFragments = 2, } - [Flags, NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [Flags, NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] - public enum MEFormatReaderParseAdditionalFragmentsStatus : ulong - { + public enum MEFormatReaderParseAdditionalFragmentsStatus : ulong { SizeIncreased = 1uL << 0, FragmentAdded = 1uL << 1, FragmentsComplete = 1uL << 2, } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MEFormatReaderInstantiationOptions : NSCopying - { + interface MEFormatReaderInstantiationOptions : NSCopying { [Export ("allowIncrementalFragmentParsing")] bool AllowIncrementalFragmentParsing { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEFormatReaderExtension - { + interface MEFormatReaderExtension { [Abstract] [Export ("formatReaderWithByteSource:options:error:")] [return: NullAllowed] @@ -68,14 +63,13 @@ interface MEFormatReaderExtension } delegate void MEFormatReaderLoadFileInfoCallback ([NullAllowed] MEFileInfo fileInfo, [NullAllowed] NSError error); - delegate void MEFormatReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem[] metadata, [NullAllowed] NSError error); - delegate void MEFormatReaderLoadTrackReadersCallback ([NullAllowed] IMETrackReader[] trackReaders, [NullAllowed] NSError error); + delegate void MEFormatReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem [] metadata, [NullAllowed] NSError error); + delegate void MEFormatReaderLoadTrackReadersCallback ([NullAllowed] IMETrackReader [] trackReaders, [NullAllowed] NSError error); delegate void MEFormatReaderParseAdditionalFragmentsCallback ([NullAllowed] MEFormatReaderParseAdditionalFragmentsStatus fragmentStatus, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEFormatReader - { + interface MEFormatReader { [Abstract] [Export ("loadFileInfoWithCompletionHandler:")] void LoadFileInfo (MEFormatReaderLoadFileInfoCallback completionHandler); @@ -94,10 +88,9 @@ interface MEFormatReader interface IMEFormatReader { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] - interface MEFileInfo : NSCopying - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] + interface MEFileInfo : NSCopying { [Export ("duration", ArgumentSemantic.Assign)] CMTime Duration { get; set; } @@ -110,12 +103,11 @@ interface MEFileInfo : NSCopying delegate void METrackReaderLoadUneditedDurationCallback ([NullAllowed] CMTime uneditedDuration, [NullAllowed] NSError error); delegate void METrackReaderLoadTotalSampleDataLengthCallback (long totalSampleDataLength, [NullAllowed] NSError error); delegate void METrackReaderLoadEstimatedDataRateCallback (float estimatedDataRate, [NullAllowed] NSError error); - delegate void METrackReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem[] metadata, [NullAllowed] NSError error); + delegate void METrackReaderLoadMetadataCallback ([NullAllowed] AVMetadataItem [] metadata, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface METrackReader - { + interface METrackReader { [Abstract] [Export ("loadTrackInfoWithCompletionHandler:")] void LoadTrackInfo (METrackReaderLoadTrackInfoCallback completionHandler); @@ -147,15 +139,14 @@ interface METrackReader interface IMETrackReader { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface METrackInfo : NSCopying - { + interface METrackInfo : NSCopying { [Export ("initWithMediaType:trackID:formatDescriptions:")] [DesignatedInitializer] // It's not clear from the documentation which type the format descriptors are, so keep as an array of NSObject for now. - NativeHandle Constructor (CMMediaType mediaType, int trackId, [Params] NSObject[] formatDescriptions); + NativeHandle Constructor (CMMediaType mediaType, int trackId, [Params] NSObject [] formatDescriptions); [Export ("mediaType")] CMMediaType MediaType { get; } @@ -169,7 +160,7 @@ interface METrackInfo : NSCopying // It's not clear from the documentation which type the format descriptors are, so keep as an array of NSObject for now. // However, name as 'Weak' to leave the good name open for when we know. [Export ("formatDescriptions", ArgumentSemantic.Copy)] - NSObject[] WeakFormatDescriptions { get; } + NSObject [] WeakFormatDescriptions { get; } // Inlined from the OptionalProperties (METrackInfo) category [Export ("naturalTimescale")] @@ -178,7 +169,7 @@ interface METrackInfo : NSCopying // Inlined from the OptionalProperties (METrackInfo) category [Export ("trackEdits", ArgumentSemantic.Copy), NullAllowed] [BindAs (typeof (CMTimeMapping []))] - NSValue[] TrackEdits { get; set; } + NSValue [] TrackEdits { get; set; } // Inlined from the LanguageTagOptionalProperties (METrackInfo) category [NullAllowed, Export ("extendedLanguageTag")] @@ -206,10 +197,9 @@ interface METrackInfo : NSCopying delegate void MESampleCursorLoadSampleBufferCallback ([NullAllowed] CMSampleBuffer newSampleBuffer, [NullAllowed] NSError error); delegate void MESampleCursorLoadPostDecodeProcessingMetadataCallback ([NullAllowed] NSDictionary postDecodeProcessingMetadata, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MESampleCursor : INSCopying - { + interface MESampleCursor : INSCopying { [Abstract] [Export ("presentationTimeStamp")] CMTime PresentationTimeStamp { get; } @@ -299,11 +289,10 @@ interface MESampleCursor : INSCopying interface IMESampleCursor { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MESampleCursorChunk : NSCopying - { + interface MESampleCursorChunk : NSCopying { [Export ("initWithByteSource:chunkStorageRange:chunkInfo:sampleIndexWithinChunk:")] [DesignatedInitializer] #if XAMCORE_5_0 @@ -338,11 +327,10 @@ interface MESampleCursorChunk : NSCopying nint SampleIndexWithinChunk { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MESampleLocation : NSCopying - { + interface MESampleLocation : NSCopying { [Export ("initWithByteSource:sampleLocation:")] [DesignatedInitializer] NativeHandle Constructor (MEByteSource byteSource, AVSampleCursorStorageRange sampleLocation); @@ -354,11 +342,10 @@ interface MESampleLocation : NSCopying MEByteSource ByteSource { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MEEstimatedSampleLocation : INSCopying - { + interface MEEstimatedSampleLocation : INSCopying { [Export ("initWithByteSource:estimatedSampleLocation:refinementDataLocation:")] [DesignatedInitializer] NativeHandle Constructor (MEByteSource byteSource, AVSampleCursorStorageRange estimatedSampleLocation, AVSampleCursorStorageRange refinementDataLocation); @@ -373,10 +360,9 @@ interface MEEstimatedSampleLocation : INSCopying MEByteSource ByteSource { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject), Name = "MEHEVCDependencyInfo")] - interface MEHevcDependencyInfo : INSCopying - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject), Name = "MEHEVCDependencyInfo")] + interface MEHevcDependencyInfo : INSCopying { [Export ("temporalSubLayerAccess")] bool TemporalSubLayerAccess { [Bind ("hasTemporalSubLayerAccess")] get; set; } @@ -418,11 +404,10 @@ interface MEHevcDependencyInfo : INSCopying delegate void MEByteSourceReadBytesCallback (nuint bytesRead, [NullAllowed] NSError error); delegate void MEByteSourceReadDataCallback ([NullAllowed] NSData data, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [BaseType (typeof (NSObject))] [DisableDefaultCtor] - interface MEByteSource - { + interface MEByteSource { [Export ("fileName")] string FileName { get; } @@ -433,7 +418,7 @@ interface MEByteSource long FileLength { get; } [Export ("relatedFileNamesInSameDirectory")] - string[] RelatedFileNamesInSameDirectory { get; } + string [] RelatedFileNamesInSameDirectory { get; } [Export ("readDataOfLength:fromOffset:toDestination:completionHandler:")] unsafe void ReadData (nuint length, long offset, byte* dest, MEByteSourceReadBytesCallback completionHandler); @@ -455,18 +440,16 @@ interface MEByteSource [Flags] [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Native] - public enum MEDecodeFrameStatus : ulong - { + public enum MEDecodeFrameStatus : ulong { NoStatus = 0, FrameDropped = 1uL << 0, } delegate void MEVideoDecoderDecodeFrameCallback ([NullAllowed] CVImageBuffer imageBuffer, MEDecodeFrameStatus decodeStatus, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEVideoDecoder - { + interface MEVideoDecoder { [Export ("producesRAWOutput")] bool ProducesRawOutput { get; } @@ -484,7 +467,7 @@ interface MEVideoDecoder // of (and not call themselves), in which case the manual code would be // useless. Thus there's no strongly typed binding for this property. [Export ("supportedPixelFormatsOrderedByQuality")] - NSNumber[] SupportedPixelFormatsOrderedByQuality { get; } + NSNumber [] SupportedPixelFormatsOrderedByQuality { get; } [Export ("reducedResolution", ArgumentSemantic.Assign)] CGSize ReducedResolution { get; set; } @@ -494,7 +477,7 @@ interface MEVideoDecoder // of (and not call themselves), in which case the manual code would be // useless. Thus there's no strongly typed binding for this property. [Export ("pixelFormatsWithReducedResolutionDecodeSupport")] - NSNumber[] PixelFormatsWithReducedResolutionDecodeSupport { get; } + NSNumber [] PixelFormatsWithReducedResolutionDecodeSupport { get; } [Abstract] [Export ("readyForMoreMediaData")] @@ -508,9 +491,9 @@ interface MEVideoDecoder bool CanAcceptFormatDescription (CMFormatDescription formatDescription); } - interface IMEVideoDecoder {} + interface IMEVideoDecoder { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Static] interface MEVideoDecoderFields { [Notification] @@ -518,10 +501,9 @@ interface MEVideoDecoderFields { NSString ReadyForMoreMediaDataDidChangeNotification { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false, Name = "MERAWProcessorExtension")] - interface MERawProcessorExtension - { + interface MERawProcessorExtension { [Abstract] [Export ("init")] NativeHandle Constructor (); @@ -532,10 +514,9 @@ interface MERawProcessorExtension IMERawProcessor CreateProcessor (CMVideoFormatDescription formatDescription, MERawProcessorPixelBufferManager extensionPixelBufferManager, [NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject), Name = "MERAWProcessorPixelBufferManager")] - interface MERawProcessorPixelBufferManager - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject), Name = "MERAWProcessorPixelBufferManager")] + interface MERawProcessorPixelBufferManager { [Export ("pixelBufferAttributes", ArgumentSemantic.Copy)] NSDictionary PixelBufferAttributes { get; set; } @@ -544,10 +525,9 @@ interface MERawProcessorPixelBufferManager CVPixelBuffer CreatePixelBuffer ([NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject), Name = "MERAWProcessingParameter")] - interface MERawProcessingParameter - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject), Name = "MERAWProcessingParameter")] + interface MERawProcessingParameter { [Export ("name")] string Name { get; } @@ -561,10 +541,9 @@ interface MERawProcessingParameter bool Enabled { get; set; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingListElementParameter")] - interface MERawProcessingListElementParameter - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingListElementParameter")] + interface MERawProcessingListElementParameter { [Export ("initWithName:description:elementID:")] NativeHandle Constructor (string name, string description, nint elementId); @@ -572,11 +551,10 @@ interface MERawProcessingListElementParameter nint ListElementId { get; } } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingBooleanParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingBooleanParameter")] [DisableDefaultCtor] - interface MERawProcessingBooleanParameter - { + interface MERawProcessingBooleanParameter { [Export ("initWithName:key:description:initialValue:")] NativeHandle Constructor (string name, string key, string description, bool initialValue); @@ -605,11 +583,10 @@ interface MERawProcessingBooleanParameter bool HasCameraValue ([NullAllowed] out bool cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingIntegerParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingIntegerParameter")] [DisableDefaultCtor] - interface MERawProcessingIntegerParameter - { + interface MERawProcessingIntegerParameter { [Export ("initWithName:key:description:initialValue:maximum:minimum:")] NativeHandle Constructor (string name, string key, string description, nint initialValue, nint maximum, nint minimum); @@ -644,11 +621,10 @@ interface MERawProcessingIntegerParameter bool HasCameraValue ([NullAllowed] out nint cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingFloatParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingFloatParameter")] [DisableDefaultCtor] - interface MERawProcessingFloatParameter - { + interface MERawProcessingFloatParameter { [Export ("initWithName:key:description:initialValue:maximum:minimum:")] NativeHandle Constructor (string name, string key, string description, float initialValue, float maximum, float minimum); @@ -683,28 +659,27 @@ interface MERawProcessingFloatParameter bool HasCameraValue ([NullAllowed] out float cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingListParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingListParameter")] [DisableDefaultCtor] - interface MERawProcessingListParameter - { + interface MERawProcessingListParameter { [Export ("initWithName:key:description:list:initialValue:")] - NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue); + NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue); [Internal] [Export ("initWithName:key:description:list:initialValue:neutralValue:")] - NativeHandle _InitWithNeutralValue (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralValue); + NativeHandle _InitWithNeutralValue (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralValue); [Internal] [Export ("initWithName:key:description:list:initialValue:cameraValue:")] - NativeHandle _InitWithCameraValue (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint cameraValue); + NativeHandle _InitWithCameraValue (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint cameraValue); [Export ("initWithName:key:description:list:initialValue:neutralValue:cameraValue:")] [DesignatedInitializer] - NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter[] listElements, nint initialValue, nint neutralValue, nint cameraValue); + NativeHandle Constructor (string name, string key, string description, MERawProcessingListElementParameter [] listElements, nint initialValue, nint neutralValue, nint cameraValue); [Export ("listElements")] - MERawProcessingListElementParameter[] ListElements { get; } + MERawProcessingListElementParameter [] ListElements { get; } [Export ("initialValue")] nint InitialValue { get; } @@ -719,24 +694,22 @@ interface MERawProcessingListParameter bool HasCameraValue ([NullAllowed] out nint cameraValue); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(MERawProcessingParameter), Name = "MERAWProcessingSubGroupParameter")] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (MERawProcessingParameter), Name = "MERAWProcessingSubGroupParameter")] [DisableDefaultCtor] - interface MERawProcessingSubGroupParameter - { + interface MERawProcessingSubGroupParameter { [Export ("initWithName:description:parameters:")] - NativeHandle Constructor (string name, string description, MERawProcessingParameter[] parameters); + NativeHandle Constructor (string name, string description, MERawProcessingParameter [] parameters); [Export ("subGroupParameters")] - MERawProcessingParameter[] SubGroupParameters { get; } + MERawProcessingParameter [] SubGroupParameters { get; } } delegate void MERawProcessorProcessFrameCallback ([NullAllowed] CVPixelBuffer pixelBuffer, [NullAllowed] NSError error); - [NoTV, NoiOS, Mac (15,0), MacCatalyst (18, 0)] + [NoTV, NoiOS, Mac (15, 0), MacCatalyst (18, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false, Name = "MERAWProcessor")] - interface MERawProcessor - { + interface MERawProcessor { [Export ("metalDeviceRegistryID")] ulong MetalDeviceRegistryId { get; set; } @@ -745,7 +718,7 @@ interface MERawProcessor [Abstract] [Export ("processingParameters")] - MERawProcessingParameter[] ProcessingParameters { get; } + MERawProcessingParameter [] ProcessingParameters { get; } [Abstract] [Export ("readyForMoreMediaData")] @@ -756,10 +729,9 @@ interface MERawProcessor void ProcessFrame (CVPixelBuffer inputFrame, MERawProcessorProcessFrameCallback completionHandler); } - [NoTV, NoiOS, Mac (15,0), MacCatalyst (18, 0)] + [NoTV, NoiOS, Mac (15, 0), MacCatalyst (18, 0)] [Static] - interface MERawProcessorFields - { + interface MERawProcessorFields { [Notification] [Field ("MERAWProcessorValuesDidChangeNotification")] NSString ValuesDidChangeNotification { get; } @@ -769,12 +741,11 @@ interface MERawProcessorFields NSString ReadyForMoreMediaDataDidChangeNotification { get; } } - interface IMERawProcessor {} + interface IMERawProcessor { } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] [Protocol (BackwardsCompatibleCodeGeneration = false)] - interface MEVideoDecoderExtension - { + interface MEVideoDecoderExtension { [Abstract] [Export ("init")] NativeHandle Constructor (); @@ -785,10 +756,9 @@ interface MEVideoDecoderExtension IMEVideoDecoder CreateVideoDecoder (CMVideoCodecType codecType, CMVideoFormatDescription videoFormatDescription, NSDictionary videoDecoderSpecifications, MEVideoDecoderPixelBufferManager extensionDecoderPixelBufferManager, [NullAllowed] out NSError error); } - [NoTV, NoiOS, Mac (15,0), NoMacCatalyst] - [BaseType (typeof(NSObject))] - interface MEVideoDecoderPixelBufferManager - { + [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] + [BaseType (typeof (NSObject))] + interface MEVideoDecoderPixelBufferManager { [Export ("pixelBufferAttributes", ArgumentSemantic.Copy)] NSDictionary PixelBufferAttributes { get; set; } @@ -801,9 +771,8 @@ interface MEVideoDecoderPixelBufferManager } [NoTV, NoiOS, Mac (15, 0), NoMacCatalyst] - [BaseType (typeof(NSObject))] - interface MEDecodeFrameOptions - { + [BaseType (typeof (NSObject))] + interface MEDecodeFrameOptions { [Export ("doNotOutputFrame")] bool DoNotOutputFrame { get; set; } diff --git a/src/mediaplayer.cs b/src/mediaplayer.cs index 8826acbb7651..602bc96109ae 100644 --- a/src/mediaplayer.cs +++ b/src/mediaplayer.cs @@ -371,7 +371,7 @@ interface MPMediaLibrary : NSSecureCoding { [Export ("addItemWithProductID:completionHandler:")] [Async] #if IOS - void AddItem (string productID, [NullAllowed] Action completionHandler); + void AddItem (string productID, [NullAllowed] Action completionHandler); #else void AddItem (string productID, [NullAllowed] Action completionHandler); #endif @@ -824,7 +824,7 @@ interface MPMoviePlayerTimedMetadataEventArgs { [NoMac] #if NET - [TV (16,0)] + [TV (16, 0)] [MacCatalyst (13, 1)] #else [Obsoleted (PlatformName.TvOS, 14, 0, message: "Removed in Xcode 12.")] @@ -1250,7 +1250,7 @@ interface MPTimedMetadata { [Export ("value")] #if NET - NSObject Value { get; } + NSObject Value { get; } #else NSObject value { get; } #endif diff --git a/src/metal.cs b/src/metal.cs index a913d1b0dc8c..ea8437ecefe7 100644 --- a/src/metal.cs +++ b/src/metal.cs @@ -1584,7 +1584,7 @@ partial interface MTLDevice { [MacCatalyst (14, 0)] [NullAllowed, Export ("counterSets")] #if NET - IMTLCounterSet[] CounterSets { get; } + IMTLCounterSet [] CounterSets { get; } #else [Obsolete ("Use 'GetIMTLCounterSets' instead.")] MTLCounterSet [] CounterSets { get; } diff --git a/src/metrickit.cs b/src/metrickit.cs index 2c75b672a4c2..f1ecfa2488c8 100644 --- a/src/metrickit.cs +++ b/src/metrickit.cs @@ -163,7 +163,7 @@ interface MXMetaData : NSSecureCoding { [MacCatalyst (14, 0)] [Export ("dictionaryRepresentation")] #if MONOMAC - NSDictionary DictionaryRepresentation { get; } + NSDictionary DictionaryRepresentation { get; } #else [Internal] NSDictionary _DictionaryRepresentation14 { get; } diff --git a/src/networkextension.cs b/src/networkextension.cs index 698c2462256d..4bf350d5a2e6 100644 --- a/src/networkextension.cs +++ b/src/networkextension.cs @@ -1322,9 +1322,9 @@ interface NETunnelProviderManager { // CopyAppRules was incorrectly bound to AppRules and it is only available on macOS #if NET || MONOMAC || __MACCATALYST__ - [NoTV, NoiOS, MacCatalyst (15,0)] + [NoTV, NoiOS, MacCatalyst (15, 0)] [Export ("appRules", ArgumentSemantic.Copy)] - NEAppRule[] AppRules { get; set; } + NEAppRule [] AppRules { get; set; } #else [NoTV] [Obsolete ("Use 'CopyAppRules' instead, this property will be removed in the future.")] diff --git a/src/quicklook.cs b/src/quicklook.cs index 7b841c61b331..4d5a08c3abde 100644 --- a/src/quicklook.cs +++ b/src/quicklook.cs @@ -33,7 +33,7 @@ using CoreGraphics; #if MONOMAC using AppKit; -using UIWindowSceneActivationConfiguration=Foundation.NSObject; +using UIWindowSceneActivationConfiguration = Foundation.NSObject; #else using UIKit; #endif @@ -315,7 +315,9 @@ interface QLPreviewingController { } #else [Static] - [NoiOS][NoMacCatalyst][NoTV] + [NoiOS] + [NoMacCatalyst] + [NoTV] interface QLThumbnailImage { [Internal, Field ("kQLThumbnailOptionScaleFactorKey")] NSString OptionScaleFactorKey { get; } diff --git a/src/scenekit.cs b/src/scenekit.cs index dc58ba55938a..ed14e0b6e0a4 100644 --- a/src/scenekit.cs +++ b/src/scenekit.cs @@ -4063,7 +4063,7 @@ interface SCNAction : NSCopying, NSSecureCoding { [NullAllowed, Export ("timingFunction", ArgumentSemantic.Assign)] #if NET - Func TimingFunction { get; set; } + Func TimingFunction { get; set; } #else Func TimingFunction2 { get; set; } #endif diff --git a/src/sharedwithyou.cs b/src/sharedwithyou.cs index 47b631dc0ee3..0d92484412c3 100644 --- a/src/sharedwithyou.cs +++ b/src/sharedwithyou.cs @@ -19,12 +19,12 @@ #if MONOMAC using AppKit; -using UIViewController=AppKit.NSViewController; -using UIView=AppKit.NSView; -using UIMenu=AppKit.NSMenu; -using UIImage=AppKit.NSImage; -using ICloudSharingControllerDelegate=AppKit.INSCloudSharingServiceDelegate; -using UIWindow=AppKit.NSWindow; +using UIViewController = AppKit.NSViewController; +using UIView = AppKit.NSView; +using UIMenu = AppKit.NSMenu; +using UIImage = AppKit.NSImage; +using ICloudSharingControllerDelegate = AppKit.INSCloudSharingServiceDelegate; +using UIWindow = AppKit.NSWindow; #else using UIKit; using ICloudSharingControllerDelegate = UIKit.IUICloudSharingControllerDelegate; diff --git a/src/soundanalysis.cs b/src/soundanalysis.cs index 997463167641..2b723ba87212 100644 --- a/src/soundanalysis.cs +++ b/src/soundanalysis.cs @@ -210,7 +210,7 @@ interface SNTimeDurationConstraint /* privately conforms to NSCoding, NSCopying, SNTimeDurationConstraintType Type { get; } #if NET - [BindAs (typeof (CMTime[]))] + [BindAs (typeof (CMTime []))] #endif [Export ("enumeratedDurations", ArgumentSemantic.Strong)] NSValue [] EnumeratedDurations { get; } diff --git a/src/storekit.cs b/src/storekit.cs index 1b3269170981..1f273c0191f4 100644 --- a/src/storekit.cs +++ b/src/storekit.cs @@ -79,13 +79,17 @@ partial interface SKDownload { [Export ("state")] SKDownloadState State { get; } #if MONOMAC - [NoiOS][NoTV][NoMacCatalyst] + [NoiOS] + [NoTV] + [NoMacCatalyst] [Obsolete ("Use 'State' instead.")] [Wrap ("State", IsVirtual = true)] - SKDownloadState DownloadState { get; } + SKDownloadState DownloadState { get; } - [NoiOS][NoTV][NoMacCatalyst] - [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'ExpectedContentLength' instead.")] + [NoiOS] + [NoTV] + [NoMacCatalyst] + [Deprecated (PlatformName.MacOSX, 10, 15, message: "Use 'ExpectedContentLength' instead.")] [Export ("contentLength", ArgumentSemantic.Copy)] NSNumber ContentLength { get; } #else @@ -374,8 +378,10 @@ interface SKProduct { string ProductIdentifier { get; } #if MONOMAC -[NoiOS][NoTV][NoMacCatalyst] - [Deprecated (PlatformName.MacOSX, 10,15, message: "Use 'IsDownloadable' instead.")] + [NoiOS] + [NoTV] + [NoMacCatalyst] + [Deprecated (PlatformName.MacOSX, 10, 15, message: "Use 'IsDownloadable' instead.")] [Export ("downloadable")] bool Downloadable { get; } #elif !NET diff --git a/src/tvmlkit.cs b/src/tvmlkit.cs index b63ba6ae19e7..ac782b340890 100644 --- a/src/tvmlkit.cs +++ b/src/tvmlkit.cs @@ -716,7 +716,8 @@ interface ITVBrowserViewControllerDataSource { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -734,7 +735,8 @@ interface ITVBrowserViewControllerDelegate { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] @@ -799,7 +801,8 @@ interface ITVDocumentViewControllerDelegate { } [Deprecated (PlatformName.TvOS, 18, 0, message: "Use SwiftUI or UIKit instead.")] [TV (13, 0)] #if NET - [Protocol][Model] + [Protocol] + [Model] #else [Protocol] [Model (AutoGeneratedName = true)] diff --git a/src/uikit.cs b/src/uikit.cs index dc2a77d216f0..e88ec7e7c10a 100644 --- a/src/uikit.cs +++ b/src/uikit.cs @@ -15777,7 +15777,7 @@ interface UITableViewRowAction : NSCopying { // , Events=new Type [] {typeof(UITextFieldDelegate)})] custom logic needed, see https://bugzilla.xamarin.com/show_bug.cgi?id=53174 interface UITextField : UITextInput, UIContentSizeCategoryAdjusting, UILetterformAwareAdjusting #if IOS - , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting + , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting #endif // IOS { [Export ("initWithFrame:")] @@ -15993,7 +15993,7 @@ interface UITextFieldDelegate { [BaseType (typeof (UIScrollView), Delegates = new string [] { "WeakDelegate" }, Events = new Type [] { typeof (UITextViewDelegate) })] interface UITextView : UITextInput, NSCoding, UIContentSizeCategoryAdjusting, UILetterformAwareAdjusting #if IOS - , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting + , UITextDraggable, UITextDroppable, UITextPasteConfigurationSupporting #endif // IOS { [Export ("initWithFrame:")] diff --git a/src/webkit.cs b/src/webkit.cs index 08a7e3be2435..3eb3bd941851 100644 --- a/src/webkit.cs +++ b/src/webkit.cs @@ -32,7 +32,7 @@ #if MONOMAC using AppKit; -using UIColor=AppKit.NSColor; +using UIColor = AppKit.NSColor; using UIScrollView = AppKit.NSScrollView; using UIImage = AppKit.NSImage; using IUIContextMenuInteractionCommitAnimating = Foundation.NSObject; @@ -2539,7 +2539,7 @@ partial interface WebUIDelegate { [Export ("webView:shouldPerformAction:fromSender:"), DelegateName ("WebViewPerformAction"), DefaultValue (null)] bool UIShouldPerformActionfromSender (WebView webView, Selector action, NSObject sender); #else - [Export ("webView:shouldPerformAction:fromSender:"), DelegateName("WebViewPerformAction"), DefaultValue (null)] + [Export ("webView:shouldPerformAction:fromSender:"), DelegateName ("WebViewPerformAction"), DefaultValue (null)] bool UIShouldPerformAction (WebView webView, Selector action, NSObject sender); #endif @@ -5760,7 +5760,7 @@ interface WKWindowFeatures { } #if MONOMAC - interface UIPreviewActionItem {} + interface UIPreviewActionItem { } #endif interface IWKPreviewActionItem { } diff --git a/src/xkit.cs b/src/xkit.cs index 6aa374e5d656..fb04b16ca6c7 100644 --- a/src/xkit.cs +++ b/src/xkit.cs @@ -44,21 +44,21 @@ using NSView = System.Object; using NSWindow = System.Object; #else -using UICollectionLayoutListConfiguration=System.Object; -using UIContentInsetsReference=System.Object; -using UIEdgeInsets=System.Object; -using UITraitCollection=System.Object; +using UICollectionLayoutListConfiguration = System.Object; +using UIContentInsetsReference = System.Object; +using UIEdgeInsets = System.Object; +using UITraitCollection = System.Object; #endif // !MONOMAC #if MONOMAC -using BezierPath=AppKit.NSBezierPath; -using Image=AppKit.NSImage; -using TextAlignment=AppKit.NSTextAlignment; -using LineBreakMode=AppKit.NSLineBreakMode; -using CollectionLayoutSectionOrthogonalScrollingBehavior=AppKit.NSCollectionLayoutSectionOrthogonalScrollingBehavior; -using CollectionElementCategory=AppKit.NSCollectionElementCategory; -using StringAttributes=AppKit.NSStringAttributes; -using View=AppKit.NSView; +using BezierPath = AppKit.NSBezierPath; +using Image = AppKit.NSImage; +using TextAlignment = AppKit.NSTextAlignment; +using LineBreakMode = AppKit.NSLineBreakMode; +using CollectionLayoutSectionOrthogonalScrollingBehavior = AppKit.NSCollectionLayoutSectionOrthogonalScrollingBehavior; +using CollectionElementCategory = AppKit.NSCollectionElementCategory; +using StringAttributes = AppKit.NSStringAttributes; +using View = AppKit.NSView; using UICollectionLayoutSectionOrthogonalScrollingProperties = System.Object; #else using BezierPath = UIKit.UIBezierPath; @@ -72,26 +72,26 @@ #endif #if MONOMAC - using IXWritingToolsCoordinatorDelegate = AppKit.INSWritingToolsCoordinatorDelegate; - using XWritingToolsBehavior = AppKit.NSWritingToolsBehavior; - using XWritingToolsCoordinator = AppKit.NSWritingToolsCoordinator; - using XWritingToolsCoordinatorAnimationParameters = AppKit.NSWritingToolsCoordinatorAnimationParameters; - using XWritingToolsCoordinatorContext = AppKit.NSWritingToolsCoordinatorContext; - using XWritingToolsCoordinatorContextScope = AppKit.NSWritingToolsCoordinatorContextScope; - using XWritingToolsCoordinatorDelegate = AppKit.NSWritingToolsCoordinatorDelegate; - using XWritingToolsCoordinatorDelegateReplaceRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateReplaceRangeCallback; - using XWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback; - using XWritingToolsCoordinatorDelegateRequestsContextsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsContextsCallback; - using XWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback; - using XWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback; - using XWritingToolsCoordinatorDelegateRequestsRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsRangeCallback; - using XWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback; - using XWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback; - using XWritingToolsCoordinatorState = AppKit.NSWritingToolsCoordinatorState; - using XWritingToolsCoordinatorTextAnimation = AppKit.NSWritingToolsCoordinatorTextAnimation; - using XWritingToolsCoordinatorTextReplacementReason = AppKit.NSWritingToolsCoordinatorTextReplacementReason; - using XWritingToolsCoordinatorTextUpdateReason = AppKit.NSWritingToolsCoordinatorTextUpdateReason; - using XWritingToolsResultOptions = AppKit.NSWritingToolsResultOptions; +using IXWritingToolsCoordinatorDelegate = AppKit.INSWritingToolsCoordinatorDelegate; +using XWritingToolsBehavior = AppKit.NSWritingToolsBehavior; +using XWritingToolsCoordinator = AppKit.NSWritingToolsCoordinator; +using XWritingToolsCoordinatorAnimationParameters = AppKit.NSWritingToolsCoordinatorAnimationParameters; +using XWritingToolsCoordinatorContext = AppKit.NSWritingToolsCoordinatorContext; +using XWritingToolsCoordinatorContextScope = AppKit.NSWritingToolsCoordinatorContextScope; +using XWritingToolsCoordinatorDelegate = AppKit.NSWritingToolsCoordinatorDelegate; +using XWritingToolsCoordinatorDelegateReplaceRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateReplaceRangeCallback; +using XWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback; +using XWritingToolsCoordinatorDelegateRequestsContextsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsContextsCallback; +using XWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback; +using XWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback; +using XWritingToolsCoordinatorDelegateRequestsRangeCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsRangeCallback; +using XWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback; +using XWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback = AppKit.NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback; +using XWritingToolsCoordinatorState = AppKit.NSWritingToolsCoordinatorState; +using XWritingToolsCoordinatorTextAnimation = AppKit.NSWritingToolsCoordinatorTextAnimation; +using XWritingToolsCoordinatorTextReplacementReason = AppKit.NSWritingToolsCoordinatorTextReplacementReason; +using XWritingToolsCoordinatorTextUpdateReason = AppKit.NSWritingToolsCoordinatorTextUpdateReason; +using XWritingToolsResultOptions = AppKit.NSWritingToolsResultOptions; #else using IXWritingToolsCoordinatorDelegate = UIKit.IUIWritingToolsCoordinatorDelegate; using XWritingToolsBehavior = UIKit.UIWritingToolsBehavior; @@ -4183,7 +4183,7 @@ interface NSTextList : NSCoding, NSCopying, NSSecureCoding { NativeHandle Constructor (NSTextListMarkerFormats format); #if NET - [BindAs (typeof (NSTextListMarkerFormats))] + [BindAs (typeof (NSTextListMarkerFormats))] #endif [Export ("markerFormat")] #if NET @@ -4733,20 +4733,20 @@ interface UIWritingToolsCoordinator : UIInteraction } #if MONOMAC - interface INSWritingToolsCoordinatorDelegate {} + interface INSWritingToolsCoordinatorDelegate { } #else interface IUIWritingToolsCoordinatorDelegate { } #endif #if MONOMAC - delegate void NSWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext[] contexts); + delegate void NSWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext [] contexts); delegate void NSWritingToolsCoordinatorDelegateReplaceRangeCallback ([NullAllowed] NSAttributedString replacementText); delegate void NSWritingToolsCoordinatorDelegateRequestsRangeCallback (NSRange range, NSUuid contextId); - delegate void NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback (BezierPath[] paths); - delegate void NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback (BezierPath[] paths); + delegate void NSWritingToolsCoordinatorDelegateRequestsBoundingBezierPathsCallback (BezierPath [] paths); + delegate void NSWritingToolsCoordinatorDelegateRequestsUnderlinePathsCallback (BezierPath [] paths); delegate void NSWritingToolsCoordinatorDelegateRequestsPreviewForTextAnimationCallback ([NullAllowed] NSTextPreview [] view); // different signature vs other platforms delegate void NSWritingToolsCoordinatorDelegateRequestsPreviewCallback ([NullAllowed] NSTextPreview textPreview); // doesn't exist on other platforms - delegate void NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback (/* [BindAs (typeof (NSRange[]))] */ NSValue[] ranges); // BindAs doesn't work here + delegate void NSWritingToolsCoordinatorDelegateRequestsSingleContainerSubrangesCallback (/* [BindAs (typeof (NSRange[]))] */ NSValue [] ranges); // BindAs doesn't work here delegate void NSWritingToolsCoordinatorDelegateRequestsDecorationContainerViewCallback (View view); #else delegate void UIWritingToolsCoordinatorDelegateRequestsContextsCallback (XWritingToolsCoordinatorContext [] contexts);