From 7b1000013e385400e1a93d3017d86237c4bd8049 Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Wed, 30 Nov 2022 15:51:17 -0800 Subject: [PATCH] Reverted code formatting for Apple platforms We didn't get the merge right, and rather than tease out exactly what happened, I'm just reverting for now. --- src/render/metal/SDL_render_metal.m | 1791 ++++++++++----------- src/video/cocoa/SDL_cocoaclipboard.h | 2 +- src/video/cocoa/SDL_cocoaclipboard.m | 97 +- src/video/cocoa/SDL_cocoaevents.h | 2 +- src/video/cocoa/SDL_cocoaevents.m | 269 ++-- src/video/cocoa/SDL_cocoakeyboard.h | 4 +- src/video/cocoa/SDL_cocoakeyboard.m | 195 +-- src/video/cocoa/SDL_cocoamessagebox.m | 59 +- src/video/cocoa/SDL_cocoametalview.h | 12 +- src/video/cocoa/SDL_cocoametalview.m | 115 +- src/video/cocoa/SDL_cocoamodes.h | 10 +- src/video/cocoa/SDL_cocoamodes.m | 391 ++--- src/video/cocoa/SDL_cocoamouse.h | 7 +- src/video/cocoa/SDL_cocoamouse.m | 328 ++-- src/video/cocoa/SDL_cocoaopengl.h | 25 +- src/video/cocoa/SDL_cocoaopengl.m | 510 +++--- src/video/cocoa/SDL_cocoaopengles.m | 53 +- src/video/cocoa/SDL_cocoashape.h | 10 +- src/video/cocoa/SDL_cocoashape.m | 153 +- src/video/cocoa/SDL_cocoavideo.h | 18 +- src/video/cocoa/SDL_cocoavideo.m | 244 ++- src/video/cocoa/SDL_cocoavulkan.h | 12 +- src/video/cocoa/SDL_cocoavulkan.m | 31 +- src/video/cocoa/SDL_cocoawindow.h | 131 +- src/video/cocoa/SDL_cocoawindow.m | 1375 ++++++++-------- src/video/uikit/SDL_uikitappdelegate.h | 4 +- src/video/uikit/SDL_uikitappdelegate.m | 48 +- src/video/uikit/SDL_uikitclipboard.m | 23 +- src/video/uikit/SDL_uikitevents.m | 85 +- src/video/uikit/SDL_uikitmessagebox.m | 54 +- src/video/uikit/SDL_uikitmetalview.h | 11 +- src/video/uikit/SDL_uikitmetalview.m | 92 +- src/video/uikit/SDL_uikitmodes.h | 16 +- src/video/uikit/SDL_uikitmodes.m | 290 ++-- src/video/uikit/SDL_uikitopengles.h | 10 +- src/video/uikit/SDL_uikitopengles.m | 39 +- src/video/uikit/SDL_uikitopenglview.h | 12 +- src/video/uikit/SDL_uikitopenglview.m | 13 +- src/video/uikit/SDL_uikitvideo.h | 2 +- src/video/uikit/SDL_uikitvideo.m | 43 +- src/video/uikit/SDL_uikitview.h | 2 +- src/video/uikit/SDL_uikitview.m | 63 +- src/video/uikit/SDL_uikitviewcontroller.h | 16 +- src/video/uikit/SDL_uikitviewcontroller.m | 88 +- src/video/uikit/SDL_uikitvulkan.h | 12 +- src/video/uikit/SDL_uikitvulkan.m | 54 +- src/video/uikit/SDL_uikitwindow.h | 8 +- src/video/uikit/SDL_uikitwindow.m | 102 +- 48 files changed, 3489 insertions(+), 3442 deletions(-) diff --git a/src/render/metal/SDL_render_metal.m b/src/render/metal/SDL_render_metal.m index 51899f582..80fd96f07 100644 --- a/src/render/metal/SDL_render_metal.m +++ b/src/render/metal/SDL_render_metal.m @@ -120,46 +120,47 @@ typedef struct METAL_ShaderPipelines } METAL_ShaderPipelines; @interface METAL_RenderData : NSObject -@property(nonatomic, retain) id mtldevice; -@property(nonatomic, retain) id mtlcmdqueue; -@property(nonatomic, retain) id mtlcmdbuffer; -@property(nonatomic, retain) id mtlcmdencoder; -@property(nonatomic, retain) id mtllibrary; -@property(nonatomic, retain) id mtlbackbuffer; -@property(nonatomic, retain) id mtlsamplernearest; -@property(nonatomic, retain) id mtlsamplerlinear; -@property(nonatomic, retain) id mtlbufconstants; -@property(nonatomic, retain) id mtlbufquadindices; -@property(nonatomic, assign) SDL_MetalView mtlview; -@property(nonatomic, retain) CAMetalLayer *mtllayer; -@property(nonatomic, retain) MTLRenderPassDescriptor *mtlpassdesc; -@property(nonatomic, assign) METAL_ShaderPipelines *activepipelines; -@property(nonatomic, assign) METAL_ShaderPipelines *allpipelines; -@property(nonatomic, assign) int pipelinescount; + @property (nonatomic, retain) id mtldevice; + @property (nonatomic, retain) id mtlcmdqueue; + @property (nonatomic, retain) id mtlcmdbuffer; + @property (nonatomic, retain) id mtlcmdencoder; + @property (nonatomic, retain) id mtllibrary; + @property (nonatomic, retain) id mtlbackbuffer; + @property (nonatomic, retain) id mtlsamplernearest; + @property (nonatomic, retain) id mtlsamplerlinear; + @property (nonatomic, retain) id mtlbufconstants; + @property (nonatomic, retain) id mtlbufquadindices; + @property (nonatomic, assign) SDL_MetalView mtlview; + @property (nonatomic, retain) CAMetalLayer *mtllayer; + @property (nonatomic, retain) MTLRenderPassDescriptor *mtlpassdesc; + @property (nonatomic, assign) METAL_ShaderPipelines *activepipelines; + @property (nonatomic, assign) METAL_ShaderPipelines *allpipelines; + @property (nonatomic, assign) int pipelinescount; @end @implementation METAL_RenderData @end @interface METAL_TextureData : NSObject -@property(nonatomic, retain) id mtltexture; -@property(nonatomic, retain) id mtltexture_uv; -@property(nonatomic, retain) id mtlsampler; -@property(nonatomic, assign) SDL_MetalFragmentFunction fragmentFunction; + @property (nonatomic, retain) id mtltexture; + @property (nonatomic, retain) id mtltexture_uv; + @property (nonatomic, retain) id mtlsampler; + @property (nonatomic, assign) SDL_MetalFragmentFunction fragmentFunction; #if SDL_HAVE_YUV -@property(nonatomic, assign) BOOL yuv; -@property(nonatomic, assign) BOOL nv12; -@property(nonatomic, assign) size_t conversionBufferOffset; + @property (nonatomic, assign) BOOL yuv; + @property (nonatomic, assign) BOOL nv12; + @property (nonatomic, assign) size_t conversionBufferOffset; #endif -@property(nonatomic, assign) BOOL hasdata; -@property(nonatomic, retain) id lockedbuffer; -@property(nonatomic, assign) SDL_Rect lockedrect; + @property (nonatomic, assign) BOOL hasdata; + @property (nonatomic, retain) id lockedbuffer; + @property (nonatomic, assign) SDL_Rect lockedrect; @end @implementation METAL_TextureData @end -static int IsMetalAvailable(const SDL_SysWMinfo *syswm) +static int +IsMetalAvailable(const SDL_SysWMinfo *syswm) { if (syswm->subsystem != SDL_SYSWM_COCOA && syswm->subsystem != SDL_SYSWM_UIKIT) { return SDL_SetError("Metal render target only supports Cocoa and UIKit video targets at the moment."); @@ -178,84 +179,63 @@ static int IsMetalAvailable(const SDL_SysWMinfo *syswm) static const MTLBlendOperation invalidBlendOperation = (MTLBlendOperation)0xFFFFFFFF; static const MTLBlendFactor invalidBlendFactor = (MTLBlendFactor)0xFFFFFFFF; -static MTLBlendOperation GetBlendOperation(SDL_BlendOperation operation) +static MTLBlendOperation +GetBlendOperation(SDL_BlendOperation operation) { switch (operation) { - case SDL_BLENDOPERATION_ADD: - return MTLBlendOperationAdd; - case SDL_BLENDOPERATION_SUBTRACT: - return MTLBlendOperationSubtract; - case SDL_BLENDOPERATION_REV_SUBTRACT: - return MTLBlendOperationReverseSubtract; - case SDL_BLENDOPERATION_MINIMUM: - return MTLBlendOperationMin; - case SDL_BLENDOPERATION_MAXIMUM: - return MTLBlendOperationMax; - default: - return invalidBlendOperation; + case SDL_BLENDOPERATION_ADD: return MTLBlendOperationAdd; + case SDL_BLENDOPERATION_SUBTRACT: return MTLBlendOperationSubtract; + case SDL_BLENDOPERATION_REV_SUBTRACT: return MTLBlendOperationReverseSubtract; + case SDL_BLENDOPERATION_MINIMUM: return MTLBlendOperationMin; + case SDL_BLENDOPERATION_MAXIMUM: return MTLBlendOperationMax; + default: return invalidBlendOperation; } } -static MTLBlendFactor GetBlendFactor(SDL_BlendFactor factor) +static MTLBlendFactor +GetBlendFactor(SDL_BlendFactor factor) { switch (factor) { - case SDL_BLENDFACTOR_ZERO: - return MTLBlendFactorZero; - case SDL_BLENDFACTOR_ONE: - return MTLBlendFactorOne; - case SDL_BLENDFACTOR_SRC_COLOR: - return MTLBlendFactorSourceColor; - case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR: - return MTLBlendFactorOneMinusSourceColor; - case SDL_BLENDFACTOR_SRC_ALPHA: - return MTLBlendFactorSourceAlpha; - case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: - return MTLBlendFactorOneMinusSourceAlpha; - case SDL_BLENDFACTOR_DST_COLOR: - return MTLBlendFactorDestinationColor; - case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR: - return MTLBlendFactorOneMinusDestinationColor; - case SDL_BLENDFACTOR_DST_ALPHA: - return MTLBlendFactorDestinationAlpha; - case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA: - return MTLBlendFactorOneMinusDestinationAlpha; - default: - return invalidBlendFactor; + case SDL_BLENDFACTOR_ZERO: return MTLBlendFactorZero; + case SDL_BLENDFACTOR_ONE: return MTLBlendFactorOne; + case SDL_BLENDFACTOR_SRC_COLOR: return MTLBlendFactorSourceColor; + case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return MTLBlendFactorOneMinusSourceColor; + case SDL_BLENDFACTOR_SRC_ALPHA: return MTLBlendFactorSourceAlpha; + case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return MTLBlendFactorOneMinusSourceAlpha; + case SDL_BLENDFACTOR_DST_COLOR: return MTLBlendFactorDestinationColor; + case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR: return MTLBlendFactorOneMinusDestinationColor; + case SDL_BLENDFACTOR_DST_ALPHA: return MTLBlendFactorDestinationAlpha; + case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return MTLBlendFactorOneMinusDestinationAlpha; + default: return invalidBlendFactor; } } -static NSString *GetVertexFunctionName(SDL_MetalVertexFunction function) +static NSString * +GetVertexFunctionName(SDL_MetalVertexFunction function) { switch (function) { - case SDL_METAL_VERTEX_SOLID: - return @"SDL_Solid_vertex"; - case SDL_METAL_VERTEX_COPY: - return @"SDL_Copy_vertex"; - default: - return nil; + case SDL_METAL_VERTEX_SOLID: return @"SDL_Solid_vertex"; + case SDL_METAL_VERTEX_COPY: return @"SDL_Copy_vertex"; + default: return nil; } } -static NSString *GetFragmentFunctionName(SDL_MetalFragmentFunction function) +static NSString * +GetFragmentFunctionName(SDL_MetalFragmentFunction function) { switch (function) { - case SDL_METAL_FRAGMENT_SOLID: - return @"SDL_Solid_fragment"; - case SDL_METAL_FRAGMENT_COPY: - return @"SDL_Copy_fragment"; - case SDL_METAL_FRAGMENT_YUV: - return @"SDL_YUV_fragment"; - case SDL_METAL_FRAGMENT_NV12: - return @"SDL_NV12_fragment"; - case SDL_METAL_FRAGMENT_NV21: - return @"SDL_NV21_fragment"; - default: - return nil; + case SDL_METAL_FRAGMENT_SOLID: return @"SDL_Solid_fragment"; + case SDL_METAL_FRAGMENT_COPY: return @"SDL_Copy_fragment"; + case SDL_METAL_FRAGMENT_YUV: return @"SDL_YUV_fragment"; + case SDL_METAL_FRAGMENT_NV12: return @"SDL_NV12_fragment"; + case SDL_METAL_FRAGMENT_NV21: return @"SDL_NV21_fragment"; + default: return nil; } } -static id MakePipelineState(METAL_RenderData *data, METAL_PipelineCache *cache, - NSString *blendlabel, SDL_BlendMode blendmode) +static id +MakePipelineState(METAL_RenderData *data, METAL_PipelineCache *cache, + NSString *blendlabel, SDL_BlendMode blendmode) { MTLRenderPipelineDescriptor *mtlpipedesc; MTLVertexDescriptor *vertdesc; @@ -277,37 +257,37 @@ static id MakePipelineState(METAL_RenderData *data, META vertdesc = [MTLVertexDescriptor vertexDescriptor]; switch (cache->vertexFunction) { - case SDL_METAL_VERTEX_SOLID: - /* position (float2), color (uchar4normalized) */ - vertdesc.layouts[0].stride = sizeof(float) * 2 + sizeof(int); - vertdesc.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex; + case SDL_METAL_VERTEX_SOLID: + /* position (float2), color (uchar4normalized) */ + vertdesc.layouts[0].stride = sizeof(float) * 2 + sizeof (int); + vertdesc.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex; - vertdesc.attributes[0].format = MTLVertexFormatFloat2; - vertdesc.attributes[0].offset = 0; - vertdesc.attributes[0].bufferIndex = 0; + vertdesc.attributes[0].format = MTLVertexFormatFloat2; + vertdesc.attributes[0].offset = 0; + vertdesc.attributes[0].bufferIndex = 0; - vertdesc.attributes[1].format = MTLVertexFormatUChar4Normalized; - vertdesc.attributes[1].offset = sizeof(float) * 2; - vertdesc.attributes[1].bufferIndex = 0; + vertdesc.attributes[1].format = MTLVertexFormatUChar4Normalized; + vertdesc.attributes[1].offset = sizeof (float) * 2; + vertdesc.attributes[1].bufferIndex = 0; - break; - case SDL_METAL_VERTEX_COPY: - /* position (float2), color (uchar4normalized), texcoord (float2) */ - vertdesc.layouts[0].stride = sizeof(float) * 2 + sizeof(int) + sizeof(float) * 2; - vertdesc.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex; + break; + case SDL_METAL_VERTEX_COPY: + /* position (float2), color (uchar4normalized), texcoord (float2) */ + vertdesc.layouts[0].stride = sizeof(float) * 2 + sizeof (int) + sizeof (float) * 2; + vertdesc.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex; - vertdesc.attributes[0].format = MTLVertexFormatFloat2; - vertdesc.attributes[0].offset = 0; - vertdesc.attributes[0].bufferIndex = 0; + vertdesc.attributes[0].format = MTLVertexFormatFloat2; + vertdesc.attributes[0].offset = 0; + vertdesc.attributes[0].bufferIndex = 0; - vertdesc.attributes[1].format = MTLVertexFormatUChar4Normalized; - vertdesc.attributes[1].offset = sizeof(float) * 2; - vertdesc.attributes[1].bufferIndex = 0; + vertdesc.attributes[1].format = MTLVertexFormatUChar4Normalized; + vertdesc.attributes[1].offset = sizeof (float) * 2; + vertdesc.attributes[1].bufferIndex = 0; - vertdesc.attributes[2].format = MTLVertexFormatFloat2; - vertdesc.attributes[2].offset = sizeof(float) * 2 + sizeof(int); - vertdesc.attributes[2].bufferIndex = 0; - break; + vertdesc.attributes[2].format = MTLVertexFormatFloat2; + vertdesc.attributes[2].offset = sizeof(float) * 2 + sizeof (int); + vertdesc.attributes[2].bufferIndex = 0; + break; } mtlpipedesc.vertexDescriptor = vertdesc; @@ -348,8 +328,9 @@ static id MakePipelineState(METAL_RenderData *data, META } } -static void MakePipelineCache(METAL_RenderData *data, METAL_PipelineCache *cache, const char *label, - MTLPixelFormat rtformat, SDL_MetalVertexFunction vertfn, SDL_MetalFragmentFunction fragfn) +static void +MakePipelineCache(METAL_RenderData *data, METAL_PipelineCache *cache, const char *label, + MTLPixelFormat rtformat, SDL_MetalVertexFunction vertfn, SDL_MetalFragmentFunction fragfn) { SDL_zerop(cache); @@ -367,7 +348,8 @@ static void MakePipelineCache(METAL_RenderData *data, METAL_PipelineCache *cache MakePipelineState(data, cache, @" (blend=mul)", SDL_BLENDMODE_MUL); } -static void DestroyPipelineCache(METAL_PipelineCache *cache) +static void +DestroyPipelineCache(METAL_PipelineCache *cache) { if (cache != NULL) { for (int i = 0; i < cache->count; i++) { @@ -378,7 +360,8 @@ static void DestroyPipelineCache(METAL_PipelineCache *cache) } } -void MakeShaderPipelines(METAL_RenderData *data, METAL_ShaderPipelines *pipelines, MTLPixelFormat rtformat) +void +MakeShaderPipelines(METAL_RenderData *data, METAL_ShaderPipelines *pipelines, MTLPixelFormat rtformat) { SDL_zerop(pipelines); @@ -391,7 +374,8 @@ void MakeShaderPipelines(METAL_RenderData *data, METAL_ShaderPipelines *pipeline MakePipelineCache(data, &pipelines->caches[SDL_METAL_FRAGMENT_NV21], "SDL NV21 pipeline", rtformat, SDL_METAL_VERTEX_COPY, SDL_METAL_FRAGMENT_NV21); } -static METAL_ShaderPipelines *ChooseShaderPipelines(METAL_RenderData *data, MTLPixelFormat rtformat) +static METAL_ShaderPipelines * +ChooseShaderPipelines(METAL_RenderData *data, MTLPixelFormat rtformat) { METAL_ShaderPipelines *allpipelines = data.allpipelines; int count = data.pipelinescount; @@ -417,7 +401,8 @@ static METAL_ShaderPipelines *ChooseShaderPipelines(METAL_RenderData *data, MTLP return &data.allpipelines[count]; } -static void DestroyAllPipelines(METAL_ShaderPipelines *allpipelines, int count) +static void +DestroyAllPipelines(METAL_ShaderPipelines *allpipelines, int count) { if (allpipelines != NULL) { for (int i = 0; i < count; i++) { @@ -430,7 +415,8 @@ static void DestroyAllPipelines(METAL_ShaderPipelines *allpipelines, int count) } } -static inline id ChoosePipelineState(METAL_RenderData *data, METAL_ShaderPipelines *pipelines, SDL_MetalFragmentFunction fragfn, SDL_BlendMode blendmode) +static inline id +ChoosePipelineState(METAL_RenderData *data, METAL_ShaderPipelines *pipelines, SDL_MetalFragmentFunction fragfn, SDL_BlendMode blendmode) { METAL_PipelineCache *cache = &pipelines->caches[fragfn]; @@ -443,9 +429,10 @@ static inline id ChoosePipelineState(METAL_RenderData *d return MakePipelineState(data, cache, [NSString stringWithFormat:@" (blend=custom 0x%x)", blendmode], blendmode); } -static SDL_bool METAL_ActivateRenderCommandEncoder(SDL_Renderer *renderer, MTLLoadAction load, MTLClearColor *clear_color, id vertex_buffer) +static SDL_bool +METAL_ActivateRenderCommandEncoder(SDL_Renderer * renderer, MTLLoadAction load, MTLClearColor *clear_color, id vertex_buffer) { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; /* Our SetRenderTarget just signals that the next render operation should * set up a new render pass. This is where that work happens. */ @@ -510,25 +497,26 @@ static SDL_bool METAL_ActivateRenderCommandEncoder(SDL_Renderer *renderer, MTLLo return SDL_TRUE; } -static void METAL_WindowEvent(SDL_Renderer *renderer, const SDL_WindowEvent *event) +static void +METAL_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event) { } -static int METAL_GetOutputSize(SDL_Renderer *renderer, int *w, int *h) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - if (w) { - *w = (int)data.mtllayer.drawableSize.width; - } - if (h) { - *h = (int)data.mtllayer.drawableSize.height; - } - return 0; +static int +METAL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + if (w) { + *w = (int)data.mtllayer.drawableSize.width; } -} + if (h) { + *h = (int)data.mtllayer.drawableSize.height; + } + return 0; +}} -static SDL_bool METAL_SupportsBlendMode(SDL_Renderer *renderer, SDL_BlendMode blendMode) +static SDL_bool +METAL_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode) { SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode); SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode); @@ -548,17 +536,17 @@ static SDL_bool METAL_SupportsBlendMode(SDL_Renderer *renderer, SDL_BlendMode bl return SDL_TRUE; } -static int METAL_CreateTexture(SDL_Renderer *renderer, SDL_Texture *texture) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - MTLPixelFormat pixfmt; - MTLTextureDescriptor *mtltexdesc; - id mtltexture, mtltexture_uv; - BOOL yuv, nv12; - METAL_TextureData *texturedata; +static int +METAL_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + MTLPixelFormat pixfmt; + MTLTextureDescriptor *mtltexdesc; + id mtltexture, mtltexture_uv; + BOOL yuv, nv12; + METAL_TextureData *texturedata; - switch (texture->format) { + switch (texture->format) { case SDL_PIXELFORMAT_ABGR8888: pixfmt = MTLPixelFormatRGBA8Unorm; break; @@ -573,103 +561,93 @@ static int METAL_CreateTexture(SDL_Renderer *renderer, SDL_Texture *texture) break; default: return SDL_SetError("Texture format %s not supported by Metal", SDL_GetPixelFormatName(texture->format)); + } + + mtltexdesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixfmt + width:(NSUInteger)texture->w height:(NSUInteger)texture->h mipmapped:NO]; + + /* Not available in iOS 8. */ + if ([mtltexdesc respondsToSelector:@selector(usage)]) { + if (texture->access == SDL_TEXTUREACCESS_TARGET) { + mtltexdesc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget; + } else { + mtltexdesc.usage = MTLTextureUsageShaderRead; } + } - mtltexdesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:pixfmt - width:(NSUInteger)texture->w - height:(NSUInteger)texture->h - mipmapped:NO]; + mtltexture = [data.mtldevice newTextureWithDescriptor:mtltexdesc]; + if (mtltexture == nil) { + return SDL_SetError("Texture allocation failed"); + } - /* Not available in iOS 8. */ - if ([mtltexdesc respondsToSelector:@selector(usage)]) { - if (texture->access == SDL_TEXTUREACCESS_TARGET) { - mtltexdesc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget; - } else { - mtltexdesc.usage = MTLTextureUsageShaderRead; - } - } + mtltexture_uv = nil; +#if SDL_HAVE_YUV + yuv = (texture->format == SDL_PIXELFORMAT_IYUV) || (texture->format == SDL_PIXELFORMAT_YV12); + nv12 = (texture->format == SDL_PIXELFORMAT_NV12) || (texture->format == SDL_PIXELFORMAT_NV21); - mtltexture = [data.mtldevice newTextureWithDescriptor:mtltexdesc]; - if (mtltexture == nil) { + if (yuv) { + mtltexdesc.pixelFormat = MTLPixelFormatR8Unorm; + mtltexdesc.width = (texture->w + 1) / 2; + mtltexdesc.height = (texture->h + 1) / 2; + mtltexdesc.textureType = MTLTextureType2DArray; + mtltexdesc.arrayLength = 2; + } else if (nv12) { + mtltexdesc.pixelFormat = MTLPixelFormatRG8Unorm; + mtltexdesc.width = (texture->w + 1) / 2; + mtltexdesc.height = (texture->h + 1) / 2; + } + + if (yuv || nv12) { + mtltexture_uv = [data.mtldevice newTextureWithDescriptor:mtltexdesc]; + if (mtltexture_uv == nil) { return SDL_SetError("Texture allocation failed"); } - - mtltexture_uv = nil; -#if SDL_HAVE_YUV - yuv = (texture->format == SDL_PIXELFORMAT_IYUV) || (texture->format == SDL_PIXELFORMAT_YV12); - nv12 = (texture->format == SDL_PIXELFORMAT_NV12) || (texture->format == SDL_PIXELFORMAT_NV21); - - if (yuv) { - mtltexdesc.pixelFormat = MTLPixelFormatR8Unorm; - mtltexdesc.width = (texture->w + 1) / 2; - mtltexdesc.height = (texture->h + 1) / 2; - mtltexdesc.textureType = MTLTextureType2DArray; - mtltexdesc.arrayLength = 2; - } else if (nv12) { - mtltexdesc.pixelFormat = MTLPixelFormatRG8Unorm; - mtltexdesc.width = (texture->w + 1) / 2; - mtltexdesc.height = (texture->h + 1) / 2; - } - - if (yuv || nv12) { - mtltexture_uv = [data.mtldevice newTextureWithDescriptor:mtltexdesc]; - if (mtltexture_uv == nil) { - return SDL_SetError("Texture allocation failed"); - } - } -#endif /* SDL_HAVE_YUV */ - texturedata = [[METAL_TextureData alloc] init]; - if (texture->scaleMode == SDL_ScaleModeNearest) { - texturedata.mtlsampler = data.mtlsamplernearest; - } else { - texturedata.mtlsampler = data.mtlsamplerlinear; - } - texturedata.mtltexture = mtltexture; - texturedata.mtltexture_uv = mtltexture_uv; -#if SDL_HAVE_YUV - texturedata.yuv = yuv; - texturedata.nv12 = nv12; - - if (yuv) { - texturedata.fragmentFunction = SDL_METAL_FRAGMENT_YUV; - } else if (texture->format == SDL_PIXELFORMAT_NV12) { - texturedata.fragmentFunction = SDL_METAL_FRAGMENT_NV12; - } else if (texture->format == SDL_PIXELFORMAT_NV21) { - texturedata.fragmentFunction = SDL_METAL_FRAGMENT_NV21; - } else -#endif - { - texturedata.fragmentFunction = SDL_METAL_FRAGMENT_COPY; - } -#if SDL_HAVE_YUV - if (yuv || nv12) { - size_t offset = 0; - SDL_YUV_CONVERSION_MODE mode = SDL_GetYUVConversionModeForResolution(texture->w, texture->h); - switch (mode) { - case SDL_YUV_CONVERSION_JPEG: - offset = CONSTANTS_OFFSET_DECODE_JPEG; - break; - case SDL_YUV_CONVERSION_BT601: - offset = CONSTANTS_OFFSET_DECODE_BT601; - break; - case SDL_YUV_CONVERSION_BT709: - offset = CONSTANTS_OFFSET_DECODE_BT709; - break; - default: - offset = 0; - break; - } - texturedata.conversionBufferOffset = offset; - } -#endif - texture->driverdata = (void *)CFBridgingRetain(texturedata); - - return 0; } -} +#endif /* SDL_HAVE_YUV */ + texturedata = [[METAL_TextureData alloc] init]; + if (texture->scaleMode == SDL_ScaleModeNearest) { + texturedata.mtlsampler = data.mtlsamplernearest; + } else { + texturedata.mtlsampler = data.mtlsamplerlinear; + } + texturedata.mtltexture = mtltexture; + texturedata.mtltexture_uv = mtltexture_uv; +#if SDL_HAVE_YUV + texturedata.yuv = yuv; + texturedata.nv12 = nv12; -static void METAL_UploadTextureData(id texture, SDL_Rect rect, int slice, - const void *pixels, int pitch) + if (yuv) { + texturedata.fragmentFunction = SDL_METAL_FRAGMENT_YUV; + } else if (texture->format == SDL_PIXELFORMAT_NV12) { + texturedata.fragmentFunction = SDL_METAL_FRAGMENT_NV12; + } else if (texture->format == SDL_PIXELFORMAT_NV21) { + texturedata.fragmentFunction = SDL_METAL_FRAGMENT_NV21; + } else +#endif + { + texturedata.fragmentFunction = SDL_METAL_FRAGMENT_COPY; + } +#if SDL_HAVE_YUV + if (yuv || nv12) { + size_t offset = 0; + SDL_YUV_CONVERSION_MODE mode = SDL_GetYUVConversionModeForResolution(texture->w, texture->h); + switch (mode) { + case SDL_YUV_CONVERSION_JPEG: offset = CONSTANTS_OFFSET_DECODE_JPEG; break; + case SDL_YUV_CONVERSION_BT601: offset = CONSTANTS_OFFSET_DECODE_BT601; break; + case SDL_YUV_CONVERSION_BT709: offset = CONSTANTS_OFFSET_DECODE_BT709; break; + default: offset = 0; break; + } + texturedata.conversionBufferOffset = offset; + } +#endif + texture->driverdata = (void*)CFBridgingRetain(texturedata); + + return 0; +}} + +static void +METAL_UploadTextureData(id texture, SDL_Rect rect, int slice, + const void * pixels, int pitch) { [texture replaceRegion:MTLRegionMake2D(rect.x, rect.y, rect.w, rect.h) mipmapLevel:0 @@ -679,7 +657,8 @@ static void METAL_UploadTextureData(id texture, SDL_Rect rect, int s bytesPerImage:0]; } -static MTLStorageMode METAL_GetStorageMode(id resource) +static MTLStorageMode +METAL_GetStorageMode(id resource) { /* iOS 8 does not have this method. */ if ([resource respondsToSelector:@selector(storageMode)]) { @@ -688,12 +667,13 @@ static MTLStorageMode METAL_GetStorageMode(id resource) return MTLStorageModeShared; } -static int METAL_UpdateTextureInternal(SDL_Renderer *renderer, METAL_TextureData *texturedata, - id texture, SDL_Rect rect, int slice, - const void *pixels, int pitch) +static int +METAL_UpdateTextureInternal(SDL_Renderer * renderer, METAL_TextureData *texturedata, + id texture, SDL_Rect rect, int slice, + const void * pixels, int pitch) { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - SDL_Rect stagingrect = { 0, 0, rect.w, rect.h }; + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + SDL_Rect stagingrect = {0, 0, rect.w, rect.h}; MTLTextureDescriptor *desc; id stagingtex; id blitcmd; @@ -756,279 +736,274 @@ static int METAL_UpdateTextureInternal(SDL_Renderer *renderer, METAL_TextureData return 0; } -static int METAL_UpdateTexture(SDL_Renderer *renderer, SDL_Texture *texture, - const SDL_Rect *rect, const void *pixels, int pitch) -{ - @autoreleasepool { - METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; +static int +METAL_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, const void *pixels, int pitch) +{ @autoreleasepool { + METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, pixels, pitch) < 0) { + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, pixels, pitch) < 0) { + return -1; + } +#if SDL_HAVE_YUV + if (texturedata.yuv) { + int Uslice = texture->format == SDL_PIXELFORMAT_YV12 ? 1 : 0; + int Vslice = texture->format == SDL_PIXELFORMAT_YV12 ? 0 : 1; + int UVpitch = (pitch + 1) / 2; + SDL_Rect UVrect = {rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2}; + + /* Skip to the correct offset into the next texture */ + pixels = (const void*)((const Uint8*)pixels + rect->h * pitch); + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Uslice, pixels, UVpitch) < 0) { return -1; } -#if SDL_HAVE_YUV - if (texturedata.yuv) { - int Uslice = texture->format == SDL_PIXELFORMAT_YV12 ? 1 : 0; - int Vslice = texture->format == SDL_PIXELFORMAT_YV12 ? 0 : 1; - int UVpitch = (pitch + 1) / 2; - SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 }; - /* Skip to the correct offset into the next texture */ - pixels = (const void *)((const Uint8 *)pixels + rect->h * pitch); - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Uslice, pixels, UVpitch) < 0) { - return -1; - } - - /* Skip to the correct offset into the next texture */ - pixels = (const void *)((const Uint8 *)pixels + UVrect.h * UVpitch); - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Vslice, pixels, UVpitch) < 0) { - return -1; - } + /* Skip to the correct offset into the next texture */ + pixels = (const void*)((const Uint8*)pixels + UVrect.h * UVpitch); + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Vslice, pixels, UVpitch) < 0) { + return -1; } - - if (texturedata.nv12) { - SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 }; - int UVpitch = 2 * ((pitch + 1) / 2); - - /* Skip to the correct offset into the next texture */ - pixels = (const void *)((const Uint8 *)pixels + rect->h * pitch); - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, 0, pixels, UVpitch) < 0) { - return -1; - } - } -#endif - texturedata.hasdata = YES; - - return 0; } -} + + if (texturedata.nv12) { + SDL_Rect UVrect = {rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2}; + int UVpitch = 2 * ((pitch + 1) / 2); + + /* Skip to the correct offset into the next texture */ + pixels = (const void*)((const Uint8*)pixels + rect->h * pitch); + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, 0, pixels, UVpitch) < 0) { + return -1; + } + } +#endif + texturedata.hasdata = YES; + + return 0; +}} #if SDL_HAVE_YUV -static int METAL_UpdateTextureYUV(SDL_Renderer *renderer, SDL_Texture *texture, - const SDL_Rect *rect, - const Uint8 *Yplane, int Ypitch, - const Uint8 *Uplane, int Upitch, - const Uint8 *Vplane, int Vpitch) -{ - @autoreleasepool { - METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; - const int Uslice = 0; - const int Vslice = 1; - SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 }; - - /* Bail out if we're supposed to update an empty rectangle */ - if (rect->w <= 0 || rect->h <= 0) { - return 0; - } - - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, Yplane, Ypitch) < 0) { - return -1; - } - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Uslice, Uplane, Upitch)) { - return -1; - } - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Vslice, Vplane, Vpitch)) { - return -1; - } - - texturedata.hasdata = YES; +static int +METAL_UpdateTextureYUV(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, + const Uint8 *Yplane, int Ypitch, + const Uint8 *Uplane, int Upitch, + const Uint8 *Vplane, int Vpitch) +{ @autoreleasepool { + METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; + const int Uslice = 0; + const int Vslice = 1; + SDL_Rect UVrect = {rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2}; + /* Bail out if we're supposed to update an empty rectangle */ + if (rect->w <= 0 || rect->h <= 0) { return 0; } -} -static int METAL_UpdateTextureNV(SDL_Renderer *renderer, SDL_Texture *texture, - const SDL_Rect *rect, - const Uint8 *Yplane, int Ypitch, - const Uint8 *UVplane, int UVpitch) -{ - @autoreleasepool { - METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; - SDL_Rect UVrect = { rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2 }; + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, Yplane, Ypitch) < 0) { + return -1; + } + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Uslice, Uplane, Upitch)) { + return -1; + } + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, Vslice, Vplane, Vpitch)) { + return -1; + } - /* Bail out if we're supposed to update an empty rectangle */ - if (rect->w <= 0 || rect->h <= 0) { - return 0; - } + texturedata.hasdata = YES; - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, Yplane, Ypitch) < 0) { - return -1; - } + return 0; +}} - if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, 0, UVplane, UVpitch) < 0) { - return -1; - } - - texturedata.hasdata = YES; +static int +METAL_UpdateTextureNV(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, + const Uint8 *Yplane, int Ypitch, + const Uint8 *UVplane, int UVpitch) +{ @autoreleasepool { + METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; + SDL_Rect UVrect = {rect->x / 2, rect->y / 2, (rect->w + 1) / 2, (rect->h + 1) / 2}; + /* Bail out if we're supposed to update an empty rectangle */ + if (rect->w <= 0 || rect->h <= 0) { return 0; } -} + + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture, *rect, 0, Yplane, Ypitch) < 0) { + return -1; + } + + if (METAL_UpdateTextureInternal(renderer, texturedata, texturedata.mtltexture_uv, UVrect, 0, UVplane, UVpitch) < 0) { + return -1; + } + + texturedata.hasdata = YES; + + return 0; +}} #endif -static int METAL_LockTexture(SDL_Renderer *renderer, SDL_Texture *texture, - const SDL_Rect *rect, void **pixels, int *pitch) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; - int buffersize = 0; - id lockedbuffer = nil; +static int +METAL_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture, + const SDL_Rect * rect, void **pixels, int *pitch) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; + int buffersize = 0; + id lockedbuffer = nil; - if (rect->w <= 0 || rect->h <= 0) { - return SDL_SetError("Invalid rectangle dimensions for LockTexture."); - } + if (rect->w <= 0 || rect->h <= 0) { + return SDL_SetError("Invalid rectangle dimensions for LockTexture."); + } - *pitch = SDL_BYTESPERPIXEL(texture->format) * rect->w; + *pitch = SDL_BYTESPERPIXEL(texture->format) * rect->w; #if SDL_HAVE_YUV - if (texturedata.yuv || texturedata.nv12) { - buffersize = ((*pitch) * rect->h) + (2 * (*pitch + 1) / 2) * ((rect->h + 1) / 2); - } else + if (texturedata.yuv || texturedata.nv12) { + buffersize = ((*pitch) * rect->h) + (2 * (*pitch + 1) / 2) * ((rect->h + 1) / 2); + } else #endif - { - buffersize = (*pitch) * rect->h; - } - - lockedbuffer = [data.mtldevice newBufferWithLength:buffersize options:MTLResourceStorageModeShared]; - if (lockedbuffer == nil) { - return SDL_OutOfMemory(); - } - - texturedata.lockedrect = *rect; - texturedata.lockedbuffer = lockedbuffer; - *pixels = [lockedbuffer contents]; - - return 0; + { + buffersize = (*pitch) * rect->h; } -} -static void METAL_UnlockTexture(SDL_Renderer *renderer, SDL_Texture *texture) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; - id blitcmd; - SDL_Rect rect = texturedata.lockedrect; - int pitch = SDL_BYTESPERPIXEL(texture->format) * rect.w; - SDL_Rect UVrect = { rect.x / 2, rect.y / 2, (rect.w + 1) / 2, (rect.h + 1) / 2 }; + lockedbuffer = [data.mtldevice newBufferWithLength:buffersize options:MTLResourceStorageModeShared]; + if (lockedbuffer == nil) { + return SDL_OutOfMemory(); + } - if (texturedata.lockedbuffer == nil) { - return; - } + texturedata.lockedrect = *rect; + texturedata.lockedbuffer = lockedbuffer; + *pixels = [lockedbuffer contents]; - if (data.mtlcmdencoder != nil) { - [data.mtlcmdencoder endEncoding]; - data.mtlcmdencoder = nil; - } + return 0; +}} - if (data.mtlcmdbuffer == nil) { - data.mtlcmdbuffer = [data.mtlcmdqueue commandBuffer]; - } +static void +METAL_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; + id blitcmd; + SDL_Rect rect = texturedata.lockedrect; + int pitch = SDL_BYTESPERPIXEL(texture->format) * rect.w; + SDL_Rect UVrect = {rect.x / 2, rect.y / 2, (rect.w + 1) / 2, (rect.h + 1) / 2}; - blitcmd = [data.mtlcmdbuffer blitCommandEncoder]; + if (texturedata.lockedbuffer == nil) { + return; + } + + if (data.mtlcmdencoder != nil) { + [data.mtlcmdencoder endEncoding]; + data.mtlcmdencoder = nil; + } + + if (data.mtlcmdbuffer == nil) { + data.mtlcmdbuffer = [data.mtlcmdqueue commandBuffer]; + } + + blitcmd = [data.mtlcmdbuffer blitCommandEncoder]; + + [blitcmd copyFromBuffer:texturedata.lockedbuffer + sourceOffset:0 + sourceBytesPerRow:pitch + sourceBytesPerImage:0 + sourceSize:MTLSizeMake(rect.w, rect.h, 1) + toTexture:texturedata.mtltexture + destinationSlice:0 + destinationLevel:0 + destinationOrigin:MTLOriginMake(rect.x, rect.y, 0)]; +#if SDL_HAVE_YUV + if (texturedata.yuv) { + int Uslice = texture->format == SDL_PIXELFORMAT_YV12 ? 1 : 0; + int Vslice = texture->format == SDL_PIXELFORMAT_YV12 ? 0 : 1; + int UVpitch = (pitch + 1) / 2; [blitcmd copyFromBuffer:texturedata.lockedbuffer - sourceOffset:0 - sourceBytesPerRow:pitch + sourceOffset:rect.h * pitch + sourceBytesPerRow:UVpitch + sourceBytesPerImage:UVpitch * UVrect.h + sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1) + toTexture:texturedata.mtltexture_uv + destinationSlice:Uslice + destinationLevel:0 + destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)]; + + [blitcmd copyFromBuffer:texturedata.lockedbuffer + sourceOffset:(rect.h * pitch) + UVrect.h * UVpitch + sourceBytesPerRow:UVpitch + sourceBytesPerImage:UVpitch * UVrect.h + sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1) + toTexture:texturedata.mtltexture_uv + destinationSlice:Vslice + destinationLevel:0 + destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)]; + } + + if (texturedata.nv12) { + int UVpitch = 2 * ((pitch + 1) / 2); + + [blitcmd copyFromBuffer:texturedata.lockedbuffer + sourceOffset:rect.h * pitch + sourceBytesPerRow:UVpitch sourceBytesPerImage:0 - sourceSize:MTLSizeMake(rect.w, rect.h, 1) - toTexture:texturedata.mtltexture + sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1) + toTexture:texturedata.mtltexture_uv destinationSlice:0 destinationLevel:0 - destinationOrigin:MTLOriginMake(rect.x, rect.y, 0)]; -#if SDL_HAVE_YUV - if (texturedata.yuv) { - int Uslice = texture->format == SDL_PIXELFORMAT_YV12 ? 1 : 0; - int Vslice = texture->format == SDL_PIXELFORMAT_YV12 ? 0 : 1; - int UVpitch = (pitch + 1) / 2; - - [blitcmd copyFromBuffer:texturedata.lockedbuffer - sourceOffset:rect.h * pitch - sourceBytesPerRow:UVpitch - sourceBytesPerImage:UVpitch * UVrect.h - sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1) - toTexture:texturedata.mtltexture_uv - destinationSlice:Uslice - destinationLevel:0 - destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)]; - - [blitcmd copyFromBuffer:texturedata.lockedbuffer - sourceOffset:(rect.h * pitch) + UVrect.h * UVpitch - sourceBytesPerRow:UVpitch - sourceBytesPerImage:UVpitch * UVrect.h - sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1) - toTexture:texturedata.mtltexture_uv - destinationSlice:Vslice - destinationLevel:0 - destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)]; - } - - if (texturedata.nv12) { - int UVpitch = 2 * ((pitch + 1) / 2); - - [blitcmd copyFromBuffer:texturedata.lockedbuffer - sourceOffset:rect.h * pitch - sourceBytesPerRow:UVpitch - sourceBytesPerImage:0 - sourceSize:MTLSizeMake(UVrect.w, UVrect.h, 1) - toTexture:texturedata.mtltexture_uv - destinationSlice:0 - destinationLevel:0 - destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)]; - } + destinationOrigin:MTLOriginMake(UVrect.x, UVrect.y, 0)]; + } #endif - [blitcmd endEncoding]; + [blitcmd endEncoding]; + [data.mtlcmdbuffer commit]; + data.mtlcmdbuffer = nil; + + texturedata.lockedbuffer = nil; /* Retained property, so it calls release. */ + texturedata.hasdata = YES; +}} + +static void +METAL_SetTextureScaleMode(SDL_Renderer * renderer, SDL_Texture * texture, SDL_ScaleMode scaleMode) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; + + if (scaleMode == SDL_ScaleModeNearest) { + texturedata.mtlsampler = data.mtlsamplernearest; + } else { + texturedata.mtlsampler = data.mtlsamplerlinear; + } +}} + +static int +METAL_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + + if (data.mtlcmdencoder) { + /* End encoding for the previous render target so we can set up a new + * render pass for this one. */ + [data.mtlcmdencoder endEncoding]; [data.mtlcmdbuffer commit]; + + data.mtlcmdencoder = nil; data.mtlcmdbuffer = nil; - - texturedata.lockedbuffer = nil; /* Retained property, so it calls release. */ - texturedata.hasdata = YES; } -} -static void METAL_SetTextureScaleMode(SDL_Renderer *renderer, SDL_Texture *texture, SDL_ScaleMode scaleMode) + /* We don't begin a new render pass right away - we delay it until an actual + * draw or clear happens. That way we can use hardware clears when possible, + * which are only available when beginning a new render pass. */ + return 0; +}} + + +static int +METAL_QueueSetViewport(SDL_Renderer * renderer, SDL_RenderCommand *cmd) { - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; - - if (scaleMode == SDL_ScaleModeNearest) { - texturedata.mtlsampler = data.mtlsamplernearest; - } else { - texturedata.mtlsampler = data.mtlsamplerlinear; - } - } -} - -static int METAL_SetRenderTarget(SDL_Renderer *renderer, SDL_Texture *texture) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - - if (data.mtlcmdencoder) { - /* End encoding for the previous render target so we can set up a new - * render pass for this one. */ - [data.mtlcmdencoder endEncoding]; - [data.mtlcmdbuffer commit]; - - data.mtlcmdencoder = nil; - data.mtlcmdbuffer = nil; - } - - /* We don't begin a new render pass right away - we delay it until an actual - * draw or clear happens. That way we can use hardware clears when possible, - * which are only available when beginning a new render pass. */ - return 0; - } -} - -static int METAL_QueueSetViewport(SDL_Renderer *renderer, SDL_RenderCommand *cmd) -{ - float projection[4][4]; /* Prepare an orthographic projection */ + float projection[4][4]; /* Prepare an orthographic projection */ const int w = cmd->data.viewport.rect.w; const int h = cmd->data.viewport.rect.h; - const size_t matrixlen = sizeof(projection); - float *matrix = (float *)SDL_AllocateRenderVertices(renderer, matrixlen, CONSTANT_ALIGN(16), &cmd->data.viewport.first); + const size_t matrixlen = sizeof (projection); + float *matrix = (float *) SDL_AllocateRenderVertices(renderer, matrixlen, CONSTANT_ALIGN(16), &cmd->data.viewport.first); if (!matrix) { return -1; } @@ -1046,25 +1021,27 @@ static int METAL_QueueSetViewport(SDL_Renderer *renderer, SDL_RenderCommand *cmd return 0; } -static int METAL_QueueSetDrawColor(SDL_Renderer *renderer, SDL_RenderCommand *cmd) +static int +METAL_QueueSetDrawColor(SDL_Renderer *renderer, SDL_RenderCommand *cmd) { - const size_t vertlen = sizeof(float) * 4; - float *verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(16), &cmd->data.color.first); + const size_t vertlen = sizeof (float) * 4; + float *verts = (float *) SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(16), &cmd->data.color.first); if (!verts) { return -1; } /* - * FIXME: not needed anymore, some cleanup to do + * FIXME: not needed anymore, some cleanup to do * - *(verts++) = ((float)cmd->data.color.r) / 255.0f; - *(verts++) = ((float)cmd->data.color.g) / 255.0f; - *(verts++) = ((float)cmd->data.color.b) / 255.0f; - *(verts++) = ((float)cmd->data.color.a) / 255.0f; - */ + *(verts++) = ((float)cmd->data.color.r) / 255.0f; + *(verts++) = ((float)cmd->data.color.g) / 255.0f; + *(verts++) = ((float)cmd->data.color.b) / 255.0f; + *(verts++) = ((float)cmd->data.color.a) / 255.0f; + */ return 0; } -static int METAL_QueueDrawPoints(SDL_Renderer *renderer, SDL_RenderCommand *cmd, const SDL_FPoint *points, int count) +static int +METAL_QueueDrawPoints(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FPoint * points, int count) { const SDL_Color color = { cmd->data.draw.r, @@ -1073,8 +1050,8 @@ static int METAL_QueueDrawPoints(SDL_Renderer *renderer, SDL_RenderCommand *cmd, cmd->data.draw.a }; - const size_t vertlen = (2 * sizeof(float) + sizeof(SDL_Color)) * count; - float *verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first); + const size_t vertlen = (2 * sizeof (float) + sizeof (SDL_Color)) * count; + float *verts = (float *) SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first); if (!verts) { return -1; } @@ -1088,7 +1065,8 @@ static int METAL_QueueDrawPoints(SDL_Renderer *renderer, SDL_RenderCommand *cmd, return 0; } -static int METAL_QueueDrawLines(SDL_Renderer *renderer, SDL_RenderCommand *cmd, const SDL_FPoint *points, int count) +static int +METAL_QueueDrawLines(SDL_Renderer * renderer, SDL_RenderCommand *cmd, const SDL_FPoint * points, int count) { const SDL_Color color = { cmd->data.draw.r, @@ -1099,10 +1077,10 @@ static int METAL_QueueDrawLines(SDL_Renderer *renderer, SDL_RenderCommand *cmd, size_t vertlen; float *verts; - SDL_assert(count >= 2); /* should have been checked at the higher level. */ + SDL_assert(count >= 2); /* should have been checked at the higher level. */ - vertlen = (2 * sizeof(float) + sizeof(SDL_Color)) * count; - verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first); + vertlen = (2 * sizeof (float) + sizeof (SDL_Color)) * count; + verts = (float *) SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first); if (!verts) { return -1; } @@ -1122,7 +1100,7 @@ static int METAL_QueueDrawLines(SDL_Renderer *renderer, SDL_RenderCommand *cmd, that are missing a pixel that frames something and not arbitrary angles. Maybe !!! FIXME for later, though. */ - points -= 2; /* update the last line. */ + points -= 2; /* update the last line. */ verts -= 2 + 1; { @@ -1131,9 +1109,9 @@ static int METAL_QueueDrawLines(SDL_Renderer *renderer, SDL_RenderCommand *cmd, const float xend = points[1].x; const float yend = points[1].y; - if (ystart == yend) { /* horizontal line */ + if (ystart == yend) { /* horizontal line */ verts[0] += (xend > xstart) ? 1.0f : -1.0f; - } else if (xstart == xend) { /* vertical line */ + } else if (xstart == xend) { /* vertical line */ verts[1] += (yend > ystart) ? 1.0f : -1.0f; } } @@ -1141,14 +1119,15 @@ static int METAL_QueueDrawLines(SDL_Renderer *renderer, SDL_RenderCommand *cmd, return 0; } -static int METAL_QueueGeometry(SDL_Renderer *renderer, SDL_RenderCommand *cmd, SDL_Texture *texture, - const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, - int num_vertices, const void *indices, int num_indices, int size_indices, - float scale_x, float scale_y) +static int +METAL_QueueGeometry(SDL_Renderer *renderer, SDL_RenderCommand *cmd, SDL_Texture *texture, + const float *xy, int xy_stride, const SDL_Color *color, int color_stride, const float *uv, int uv_stride, + int num_vertices, const void *indices, int num_indices, int size_indices, + float scale_x, float scale_y) { int count = indices ? num_indices : num_vertices; - const size_t vertlen = (2 * sizeof(float) + sizeof(int) + (texture ? 2 : 0) * sizeof(float)) * count; - float *verts = (float *)SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first); + const size_t vertlen = (2 * sizeof (float) + sizeof (int) + (texture ? 2 : 0) * sizeof (float)) * count; + float *verts = (float *) SDL_AllocateRenderVertices(renderer, vertlen, DEVICE_ALIGN(8), &cmd->data.draw.first); if (!verts) { return -1; } @@ -1169,15 +1148,15 @@ static int METAL_QueueGeometry(SDL_Renderer *renderer, SDL_RenderCommand *cmd, S j = i; } - xy_ = (float *)((char *)xy + j * xy_stride); + xy_ = (float *)((char*)xy + j * xy_stride); *(verts++) = xy_[0] * scale_x; *(verts++) = xy_[1] * scale_y; - *((SDL_Color *)verts++) = *(SDL_Color *)((char *)color + j * color_stride); + *((SDL_Color *)verts++) = *(SDL_Color *)((char*)color + j * color_stride); if (texture) { - float *uv_ = (float *)((char *)uv + j * uv_stride); + float *uv_ = (float *)((char*)uv + j * uv_stride); *(verts++) = uv_[0]; *(verts++) = uv_[1]; } @@ -1202,10 +1181,11 @@ typedef struct size_t color_offset; } METAL_DrawStateCache; -static SDL_bool SetDrawState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, const SDL_MetalFragmentFunction shader, - const size_t constants_offset, id mtlbufvertex, METAL_DrawStateCache *statecache) +static SDL_bool +SetDrawState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, const SDL_MetalFragmentFunction shader, + const size_t constants_offset, id mtlbufvertex, METAL_DrawStateCache *statecache) { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; const SDL_BlendMode blend = cmd->data.draw.blend; size_t first = cmd->data.draw.first; id newpipeline; @@ -1223,7 +1203,7 @@ static SDL_bool SetDrawState(SDL_Renderer *renderer, const SDL_RenderCommand *cm viewport.znear = 0.0; viewport.zfar = 1.0; [data.mtlcmdencoder setViewport:viewport]; - [data.mtlcmdencoder setVertexBuffer:mtlbufvertex offset:statecache->projection_offset atIndex:2]; // projection + [data.mtlcmdencoder setVertexBuffer:mtlbufvertex offset:statecache->projection_offset atIndex:2]; // projection statecache->viewport_dirty = SDL_FALSE; } @@ -1282,10 +1262,11 @@ static SDL_bool SetDrawState(SDL_Renderer *renderer, const SDL_RenderCommand *cm return SDL_TRUE; } -static SDL_bool SetCopyState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, const size_t constants_offset, - id mtlbufvertex, METAL_DrawStateCache *statecache) +static SDL_bool +SetCopyState(SDL_Renderer *renderer, const SDL_RenderCommand *cmd, const size_t constants_offset, + id mtlbufvertex, METAL_DrawStateCache *statecache) { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; SDL_Texture *texture = cmd->data.draw.texture; METAL_TextureData *texturedata = (__bridge METAL_TextureData *)texture->driverdata; @@ -1296,7 +1277,7 @@ static SDL_bool SetCopyState(SDL_Renderer *renderer, const SDL_RenderCommand *cm if (texture != statecache->texture) { METAL_TextureData *oldtexturedata = NULL; if (statecache->texture) { - oldtexturedata = (__bridge METAL_TextureData *)statecache->texture->driverdata; + oldtexturedata = (__bridge METAL_TextureData *) statecache->texture->driverdata; } if (!oldtexturedata || (texturedata.mtlsampler != oldtexturedata.mtlsampler)) { [data.mtlcmdencoder setFragmentSamplerState:texturedata.mtlsampler atIndex:0]; @@ -1314,74 +1295,70 @@ static SDL_bool SetCopyState(SDL_Renderer *renderer, const SDL_RenderCommand *cm return SDL_TRUE; } -static int METAL_RunCommandQueue(SDL_Renderer *renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - id mtlbufvertex = nil; - METAL_DrawStateCache statecache; - SDL_zero(statecache); +static int +METAL_RunCommandQueue(SDL_Renderer * renderer, SDL_RenderCommand *cmd, void *vertices, size_t vertsize) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + id mtlbufvertex = nil; + METAL_DrawStateCache statecache; + SDL_zero(statecache); - statecache.pipeline = nil; - statecache.vertex_buffer = nil; - statecache.constants_offset = CONSTANTS_OFFSET_INVALID; - statecache.texture = NULL; - statecache.color_dirty = SDL_TRUE; - statecache.cliprect_dirty = SDL_TRUE; - statecache.viewport_dirty = SDL_TRUE; - statecache.projection_offset = 0; - statecache.color_offset = 0; + statecache.pipeline = nil; + statecache.vertex_buffer = nil; + statecache.constants_offset = CONSTANTS_OFFSET_INVALID; + statecache.texture = NULL; + statecache.color_dirty = SDL_TRUE; + statecache.cliprect_dirty = SDL_TRUE; + statecache.viewport_dirty = SDL_TRUE; + statecache.projection_offset = 0; + statecache.color_offset = 0; - // !!! FIXME: have a ring of pre-made MTLBuffers we cycle through? How expensive is creation? - if (vertsize > 0) { - /* We can memcpy to a shared buffer from the CPU and read it from the GPU - * without any extra copying. It's a bit slower on macOS to read shared - * data from the GPU than to read managed/private data, but we avoid the - * cost of copying the data and the code's simpler. Apple's best - * practices guide recommends this approach for streamed vertex data. - * TODO: this buffer is also used for constants. Is performance still - * good for those, or should we have a managed buffer for them? */ - mtlbufvertex = [data.mtldevice newBufferWithLength:vertsize options:MTLResourceStorageModeShared]; - mtlbufvertex.label = @"SDL vertex data"; - SDL_memcpy([mtlbufvertex contents], vertices, vertsize); + // !!! FIXME: have a ring of pre-made MTLBuffers we cycle through? How expensive is creation? + if (vertsize > 0) { + /* We can memcpy to a shared buffer from the CPU and read it from the GPU + * without any extra copying. It's a bit slower on macOS to read shared + * data from the GPU than to read managed/private data, but we avoid the + * cost of copying the data and the code's simpler. Apple's best + * practices guide recommends this approach for streamed vertex data. + * TODO: this buffer is also used for constants. Is performance still + * good for those, or should we have a managed buffer for them? */ + mtlbufvertex = [data.mtldevice newBufferWithLength:vertsize options:MTLResourceStorageModeShared]; + mtlbufvertex.label = @"SDL vertex data"; + SDL_memcpy([mtlbufvertex contents], vertices, vertsize); - statecache.vertex_buffer = mtlbufvertex; - } + statecache.vertex_buffer = mtlbufvertex; + } - // If there's a command buffer here unexpectedly (app requested one?). Commit it so we can start fresh. - [data.mtlcmdencoder endEncoding]; - [data.mtlcmdbuffer commit]; - data.mtlcmdencoder = nil; - data.mtlcmdbuffer = nil; + // If there's a command buffer here unexpectedly (app requested one?). Commit it so we can start fresh. + [data.mtlcmdencoder endEncoding]; + [data.mtlcmdbuffer commit]; + data.mtlcmdencoder = nil; + data.mtlcmdbuffer = nil; - while (cmd) { - switch (cmd->command) { - case SDL_RENDERCMD_SETVIEWPORT: - { - SDL_memcpy(&statecache.viewport, &cmd->data.viewport.rect, sizeof(statecache.viewport)); + while (cmd) { + switch (cmd->command) { + case SDL_RENDERCMD_SETVIEWPORT: { + SDL_memcpy(&statecache.viewport, &cmd->data.viewport.rect, sizeof (statecache.viewport)); statecache.projection_offset = cmd->data.viewport.first; statecache.viewport_dirty = SDL_TRUE; statecache.cliprect_dirty = SDL_TRUE; break; } - case SDL_RENDERCMD_SETCLIPRECT: - { - SDL_memcpy(&statecache.cliprect, &cmd->data.cliprect.rect, sizeof(statecache.cliprect)); + case SDL_RENDERCMD_SETCLIPRECT: { + SDL_memcpy(&statecache.cliprect, &cmd->data.cliprect.rect, sizeof (statecache.cliprect)); statecache.cliprect_enabled = cmd->data.cliprect.enabled; statecache.cliprect_dirty = SDL_TRUE; break; } - case SDL_RENDERCMD_SETDRAWCOLOR: - { + case SDL_RENDERCMD_SETDRAWCOLOR: { statecache.color_offset = cmd->data.color.first; statecache.color_dirty = SDL_TRUE; break; } - case SDL_RENDERCMD_CLEAR: - { + case SDL_RENDERCMD_CLEAR: { /* If we're already encoding a command buffer, dump it without committing it. We'd just clear all its work anyhow, and starting a new encoder will let us use a hardware clear operation via MTLLoadActionClear. */ @@ -1417,8 +1394,7 @@ static int METAL_RunCommandQueue(SDL_Renderer *renderer, SDL_RenderCommand *cmd, } case SDL_RENDERCMD_DRAW_POINTS: - case SDL_RENDERCMD_DRAW_LINES: - { + case SDL_RENDERCMD_DRAW_LINES: { const size_t count = cmd->data.draw.count; const MTLPrimitiveType primtype = (cmd->command == SDL_RENDERCMD_DRAW_POINTS) ? MTLPrimitiveTypePoint : MTLPrimitiveTypeLineStrip; if (SetDrawState(renderer, cmd, SDL_METAL_FRAGMENT_SOLID, CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM, mtlbufvertex, &statecache)) { @@ -1436,8 +1412,7 @@ static int METAL_RunCommandQueue(SDL_Renderer *renderer, SDL_RenderCommand *cmd, case SDL_RENDERCMD_COPY_EX: /* unused */ break; - case SDL_RENDERCMD_GEOMETRY: - { + case SDL_RENDERCMD_GEOMETRY: { const size_t count = cmd->data.draw.count; SDL_Texture *texture = cmd->data.draw.texture; @@ -1455,30 +1430,29 @@ static int METAL_RunCommandQueue(SDL_Renderer *renderer, SDL_RenderCommand *cmd, case SDL_RENDERCMD_NO_OP: break; - } - cmd = cmd->next; } - - return 0; + cmd = cmd->next; } -} -static int METAL_RenderReadPixels(SDL_Renderer *renderer, const SDL_Rect *rect, - Uint32 pixel_format, void *pixels, int pitch) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - id mtltexture; - MTLRegion mtlregion; - int temp_pitch, status; - Uint32 temp_format; - void *temp_pixels; - if (!METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil)) { - return SDL_SetError("Failed to activate render command encoder (is your window in the background?"); - } + return 0; +}} - [data.mtlcmdencoder endEncoding]; - mtltexture = data.mtlpassdesc.colorAttachments[0].texture; +static int +METAL_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect, + Uint32 pixel_format, void * pixels, int pitch) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + id mtltexture; + MTLRegion mtlregion; + int temp_pitch, status; + Uint32 temp_format; + void *temp_pixels; + if (!METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil)) { + return SDL_SetError("Failed to activate render command encoder (is your window in the background?"); + } + + [data.mtlcmdencoder endEncoding]; + mtltexture = data.mtlpassdesc.colorAttachments[0].texture; #ifdef __MACOSX__ /* on macOS with managed-storage textures, we need to tell the driver to @@ -1492,127 +1466,122 @@ static int METAL_RenderReadPixels(SDL_Renderer *renderer, const SDL_Rect *rect, } #endif - /* Commit the current command buffer and wait until it's completed, to make - * sure the GPU has finished rendering to it by the time we read it. */ - [data.mtlcmdbuffer commit]; - [data.mtlcmdbuffer waitUntilCompleted]; - data.mtlcmdencoder = nil; - data.mtlcmdbuffer = nil; + /* Commit the current command buffer and wait until it's completed, to make + * sure the GPU has finished rendering to it by the time we read it. */ + [data.mtlcmdbuffer commit]; + [data.mtlcmdbuffer waitUntilCompleted]; + data.mtlcmdencoder = nil; + data.mtlcmdbuffer = nil; - mtlregion = MTLRegionMake2D(rect->x, rect->y, rect->w, rect->h); + mtlregion = MTLRegionMake2D(rect->x, rect->y, rect->w, rect->h); - // we only do BGRA8 or RGBA8 at the moment, so 4 will do. - temp_pitch = rect->w * 4; - temp_pixels = SDL_malloc(temp_pitch * rect->h); - if (!temp_pixels) { - return SDL_OutOfMemory(); + // we only do BGRA8 or RGBA8 at the moment, so 4 will do. + temp_pitch = rect->w * 4; + temp_pixels = SDL_malloc(temp_pitch * rect->h); + if (!temp_pixels) { + return SDL_OutOfMemory(); + } + + [mtltexture getBytes:temp_pixels bytesPerRow:temp_pitch fromRegion:mtlregion mipmapLevel:0]; + + temp_format = (mtltexture.pixelFormat == MTLPixelFormatBGRA8Unorm) ? SDL_PIXELFORMAT_ARGB8888 : SDL_PIXELFORMAT_ABGR8888; + status = SDL_ConvertPixels(rect->w, rect->h, temp_format, temp_pixels, temp_pitch, pixel_format, pixels, pitch); + SDL_free(temp_pixels); + return status; +}} + +static int +METAL_RenderPresent(SDL_Renderer * renderer) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + SDL_bool ready = SDL_TRUE; + + // If we don't have a command buffer, we can't present, so activate to get one. + if (data.mtlcmdencoder == nil) { + // We haven't even gotten a backbuffer yet? Clear it to black. Otherwise, load the existing data. + if (data.mtlbackbuffer == nil) { + MTLClearColor color = MTLClearColorMake(0.0f, 0.0f, 0.0f, 1.0f); + ready = METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionClear, &color, nil); + } else { + ready = METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil); + } + } + + [data.mtlcmdencoder endEncoding]; + + // If we don't have a drawable to present, don't try to present it. + // But we'll still try to commit the command buffer in case it was already enqueued. + if (ready) { + SDL_assert(data.mtlbackbuffer != nil); + [data.mtlcmdbuffer presentDrawable:data.mtlbackbuffer]; + } + + [data.mtlcmdbuffer commit]; + + data.mtlcmdencoder = nil; + data.mtlcmdbuffer = nil; + data.mtlbackbuffer = nil; + + if (renderer->hidden || !ready) { + return -1; + } + return 0; +}} + +static void +METAL_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture) +{ @autoreleasepool { + CFBridgingRelease(texture->driverdata); + texture->driverdata = NULL; +}} + +static void +METAL_DestroyRenderer(SDL_Renderer * renderer) +{ @autoreleasepool { + if (renderer->driverdata) { + METAL_RenderData *data = CFBridgingRelease(renderer->driverdata); + + if (data.mtlcmdencoder != nil) { + [data.mtlcmdencoder endEncoding]; } - [mtltexture getBytes:temp_pixels bytesPerRow:temp_pitch fromRegion:mtlregion mipmapLevel:0]; + DestroyAllPipelines(data.allpipelines, data.pipelinescount); - temp_format = (mtltexture.pixelFormat == MTLPixelFormatBGRA8Unorm) ? SDL_PIXELFORMAT_ARGB8888 : SDL_PIXELFORMAT_ABGR8888; - status = SDL_ConvertPixels(rect->w, rect->h, temp_format, temp_pixels, temp_pitch, pixel_format, pixels, pitch); - SDL_free(temp_pixels); - return status; + /* Release the metal view instead of destroying it, + in case we want to use it later (recreating the renderer) + */ + /* SDL_Metal_DestroyView(data.mtlview); */ + CFBridgingRelease(data.mtlview); } -} -static int METAL_RenderPresent(SDL_Renderer *renderer) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - SDL_bool ready = SDL_TRUE; + SDL_free(renderer); +}} - // If we don't have a command buffer, we can't present, so activate to get one. - if (data.mtlcmdencoder == nil) { - // We haven't even gotten a backbuffer yet? Clear it to black. Otherwise, load the existing data. - if (data.mtlbackbuffer == nil) { - MTLClearColor color = MTLClearColorMake(0.0f, 0.0f, 0.0f, 1.0f); - ready = METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionClear, &color, nil); - } else { - ready = METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil); - } - } +static void * +METAL_GetMetalLayer(SDL_Renderer * renderer) +{ @autoreleasepool { + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; + return (__bridge void*)data.mtllayer; +}} - [data.mtlcmdencoder endEncoding]; +static void * +METAL_GetMetalCommandEncoder(SDL_Renderer * renderer) +{ @autoreleasepool { + // note that data.mtlcmdencoder can be nil if METAL_ActivateRenderCommandEncoder fails. + // Before SDL 2.0.18, it might have returned a non-nil encoding that might not have been + // usable for presentation. Check your return values! + METAL_RenderData *data; + METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil); + data = (__bridge METAL_RenderData *) renderer->driverdata; + return (__bridge void*)data.mtlcmdencoder; +}} - // If we don't have a drawable to present, don't try to present it. - // But we'll still try to commit the command buffer in case it was already enqueued. - if (ready) { - SDL_assert(data.mtlbackbuffer != nil); - [data.mtlcmdbuffer presentDrawable:data.mtlbackbuffer]; - } - - [data.mtlcmdbuffer commit]; - - data.mtlcmdencoder = nil; - data.mtlcmdbuffer = nil; - data.mtlbackbuffer = nil; - - if (renderer->hidden || !ready) { - return -1; - } - return 0; - } -} - -static void METAL_DestroyTexture(SDL_Renderer *renderer, SDL_Texture *texture) -{ - @autoreleasepool { - CFBridgingRelease(texture->driverdata); - texture->driverdata = NULL; - } -} - -static void METAL_DestroyRenderer(SDL_Renderer *renderer) -{ - @autoreleasepool { - if (renderer->driverdata) { - METAL_RenderData *data = CFBridgingRelease(renderer->driverdata); - - if (data.mtlcmdencoder != nil) { - [data.mtlcmdencoder endEncoding]; - } - - DestroyAllPipelines(data.allpipelines, data.pipelinescount); - - /* Release the metal view instead of destroying it, - in case we want to use it later (recreating the renderer) - */ - /* SDL_Metal_DestroyView(data.mtlview); */ - CFBridgingRelease(data.mtlview); - } - - SDL_free(renderer); - } -} - -static void *METAL_GetMetalLayer(SDL_Renderer *renderer) -{ - @autoreleasepool { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; - return (__bridge void *)data.mtllayer; - } -} - -static void *METAL_GetMetalCommandEncoder(SDL_Renderer *renderer) -{ - @autoreleasepool { - // note that data.mtlcmdencoder can be nil if METAL_ActivateRenderCommandEncoder fails. - // Before SDL 2.0.18, it might have returned a non-nil encoding that might not have been - // usable for presentation. Check your return values! - METAL_RenderData *data; - METAL_ActivateRenderCommandEncoder(renderer, MTLLoadActionLoad, NULL, nil); - data = (__bridge METAL_RenderData *)renderer->driverdata; - return (__bridge void *)data.mtlcmdencoder; - } -} - -static int METAL_SetVSync(SDL_Renderer *renderer, const int vsync) +static int +METAL_SetVSync(SDL_Renderer * renderer, const int vsync) { #if (defined(__MACOSX__) && defined(MAC_OS_X_VERSION_10_13)) || TARGET_OS_MACCATALYST if (@available(macOS 10.13, *)) { - METAL_RenderData *data = (__bridge METAL_RenderData *)renderer->driverdata; + METAL_RenderData *data = (__bridge METAL_RenderData *) renderer->driverdata; if (vsync) { data.mtllayer.displaySyncEnabled = YES; renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; @@ -1654,263 +1623,238 @@ static SDL_MetalView GetWindowView(SDL_Window *window) return nil; } -static SDL_Renderer *METAL_CreateRenderer(SDL_Window *window, Uint32 flags) -{ - @autoreleasepool { - SDL_Renderer *renderer = NULL; - METAL_RenderData *data = NULL; - id mtldevice = nil; - SDL_MetalView view = NULL; - CAMetalLayer *layer = nil; - SDL_SysWMinfo syswm; - NSError *err = nil; - dispatch_data_t mtllibdata; - char *constantdata; - int maxtexsize, quadcount = UINT16_MAX / 4; - UInt16 *indexdata; - size_t indicessize = sizeof(UInt16) * quadcount * 6; - MTLSamplerDescriptor *samplerdesc; - id mtlcmdqueue; - id mtllibrary; - id mtlsamplernearest, mtlsamplerlinear; - id mtlbufconstantstaging, mtlbufquadindicesstaging, mtlbufconstants, mtlbufquadindices; - id cmdbuffer; - id blitcmd; +static SDL_Renderer * +METAL_CreateRenderer(SDL_Window * window, Uint32 flags) +{ @autoreleasepool { + SDL_Renderer *renderer = NULL; + METAL_RenderData *data = NULL; + id mtldevice = nil; + SDL_MetalView view = NULL; + CAMetalLayer *layer = nil; + SDL_SysWMinfo syswm; + NSError *err = nil; + dispatch_data_t mtllibdata; + char *constantdata; + int maxtexsize, quadcount = UINT16_MAX / 4; + UInt16 *indexdata; + size_t indicessize = sizeof(UInt16) * quadcount * 6; + MTLSamplerDescriptor *samplerdesc; + id mtlcmdqueue; + id mtllibrary; + id mtlsamplernearest, mtlsamplerlinear; + id mtlbufconstantstaging, mtlbufquadindicesstaging, mtlbufconstants, mtlbufquadindices; + id cmdbuffer; + id blitcmd; - /* Note: matrices are column major. */ - float identitytransform[16] = { - 1.0f, - 0.0f, - 0.0f, - 0.0f, - 0.0f, - 1.0f, - 0.0f, - 0.0f, - 0.0f, - 0.0f, - 1.0f, - 0.0f, - 0.0f, - 0.0f, - 0.0f, - 1.0f, - }; + /* Note: matrices are column major. */ + float identitytransform[16] = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f, + }; - float halfpixeltransform[16] = { - 1.0f, - 0.0f, - 0.0f, - 0.0f, - 0.0f, - 1.0f, - 0.0f, - 0.0f, - 0.0f, - 0.0f, - 1.0f, - 0.0f, - 0.5f, - 0.5f, - 0.0f, - 1.0f, - }; + float halfpixeltransform[16] = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.0f, 1.0f, + }; - /* Metal pads float3s to 16 bytes. */ - float decodetransformJPEG[4 * 4] = { - 0.0, -0.501960814, -0.501960814, 0.0, /* offset */ - 1.0000, 0.0000, 1.4020, 0.0, /* Rcoeff */ - 1.0000, -0.3441, -0.7141, 0.0, /* Gcoeff */ - 1.0000, 1.7720, 0.0000, 0.0, /* Bcoeff */ - }; + /* Metal pads float3s to 16 bytes. */ + float decodetransformJPEG[4*4] = { + 0.0, -0.501960814, -0.501960814, 0.0, /* offset */ + 1.0000, 0.0000, 1.4020, 0.0, /* Rcoeff */ + 1.0000, -0.3441, -0.7141, 0.0, /* Gcoeff */ + 1.0000, 1.7720, 0.0000, 0.0, /* Bcoeff */ + }; - float decodetransformBT601[4 * 4] = { - -0.0627451017, -0.501960814, -0.501960814, 0.0, /* offset */ - 1.1644, 0.0000, 1.5960, 0.0, /* Rcoeff */ - 1.1644, -0.3918, -0.8130, 0.0, /* Gcoeff */ - 1.1644, 2.0172, 0.0000, 0.0, /* Bcoeff */ - }; + float decodetransformBT601[4*4] = { + -0.0627451017, -0.501960814, -0.501960814, 0.0, /* offset */ + 1.1644, 0.0000, 1.5960, 0.0, /* Rcoeff */ + 1.1644, -0.3918, -0.8130, 0.0, /* Gcoeff */ + 1.1644, 2.0172, 0.0000, 0.0, /* Bcoeff */ + }; - float decodetransformBT709[4 * 4] = { - 0.0, -0.501960814, -0.501960814, 0.0, /* offset */ - 1.0000, 0.0000, 1.4020, 0.0, /* Rcoeff */ - 1.0000, -0.3441, -0.7141, 0.0, /* Gcoeff */ - 1.0000, 1.7720, 0.0000, 0.0, /* Bcoeff */ - }; + float decodetransformBT709[4*4] = { + 0.0, -0.501960814, -0.501960814, 0.0, /* offset */ + 1.0000, 0.0000, 1.4020, 0.0, /* Rcoeff */ + 1.0000, -0.3441, -0.7141, 0.0, /* Gcoeff */ + 1.0000, 1.7720, 0.0000, 0.0, /* Bcoeff */ + }; SDL_VERSION(&syswm.version); if (!SDL_GetWindowWMInfo(window, &syswm)) { return NULL; } - if (IsMetalAvailable(&syswm) == -1) { - return NULL; - } + if (IsMetalAvailable(&syswm) == -1) { + return NULL; + } - renderer = (SDL_Renderer *)SDL_calloc(1, sizeof(*renderer)); - if (!renderer) { - SDL_OutOfMemory(); - return NULL; - } + renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer)); + if (!renderer) { + SDL_OutOfMemory(); + return NULL; + } - // !!! FIXME: MTLCopyAllDevices() can find other GPUs on macOS... - mtldevice = MTLCreateSystemDefaultDevice(); + // !!! FIXME: MTLCopyAllDevices() can find other GPUs on macOS... + mtldevice = MTLCreateSystemDefaultDevice(); - if (mtldevice == nil) { - SDL_free(renderer); - SDL_SetError("Failed to obtain Metal device"); - return NULL; - } + if (mtldevice == nil) { + SDL_free(renderer); + SDL_SetError("Failed to obtain Metal device"); + return NULL; + } - view = GetWindowView(window); - if (view == nil) { - view = SDL_Metal_CreateView(window); - } + view = GetWindowView(window); + if (view == nil) { + view = SDL_Metal_CreateView(window); + } - if (view == NULL) { - SDL_free(renderer); - return NULL; - } + if (view == NULL) { + SDL_free(renderer); + return NULL; + } - // !!! FIXME: error checking on all of this. - data = [[METAL_RenderData alloc] init]; + // !!! FIXME: error checking on all of this. + data = [[METAL_RenderData alloc] init]; - if (data == nil) { - /* Release the metal view instead of destroying it, - in case we want to use it later (recreating the renderer) - */ - /* SDL_Metal_DestroyView(view); */ - CFBridgingRelease(view); - SDL_free(renderer); - return NULL; - } + if (data == nil) { + /* Release the metal view instead of destroying it, + in case we want to use it later (recreating the renderer) + */ + /* SDL_Metal_DestroyView(view); */ + CFBridgingRelease(view); + SDL_free(renderer); + return NULL; + } - renderer->driverdata = (void *)CFBridgingRetain(data); - renderer->window = window; + renderer->driverdata = (void*)CFBridgingRetain(data); + renderer->window = window; - data.mtlview = view; + data.mtlview = view; #ifdef __MACOSX__ layer = (CAMetalLayer *)[(__bridge NSView *)view layer]; #else - layer = (CAMetalLayer *)[(__bridge UIView *)view layer]; + layer = (CAMetalLayer *)[(__bridge UIView *)view layer]; #endif - layer.device = mtldevice; + layer.device = mtldevice; - /* Necessary for RenderReadPixels. */ - layer.framebufferOnly = NO; + /* Necessary for RenderReadPixels. */ + layer.framebufferOnly = NO; - data.mtldevice = layer.device; - data.mtllayer = layer; - mtlcmdqueue = [data.mtldevice newCommandQueue]; - data.mtlcmdqueue = mtlcmdqueue; - data.mtlcmdqueue.label = @"SDL Metal Renderer"; - data.mtlpassdesc = [MTLRenderPassDescriptor renderPassDescriptor]; + data.mtldevice = layer.device; + data.mtllayer = layer; + mtlcmdqueue = [data.mtldevice newCommandQueue]; + data.mtlcmdqueue = mtlcmdqueue; + data.mtlcmdqueue.label = @"SDL Metal Renderer"; + data.mtlpassdesc = [MTLRenderPassDescriptor renderPassDescriptor]; - // The compiled .metallib is embedded in a static array in a header file - // but the original shader source code is in SDL_shaders_metal.metal. - mtllibdata = dispatch_data_create(sdl_metallib, sdl_metallib_len, dispatch_get_global_queue(0, 0), ^{ - }); - mtllibrary = [data.mtldevice newLibraryWithData:mtllibdata error:&err]; - data.mtllibrary = mtllibrary; - SDL_assert(err == nil); - data.mtllibrary.label = @"SDL Metal renderer shader library"; + // The compiled .metallib is embedded in a static array in a header file + // but the original shader source code is in SDL_shaders_metal.metal. + mtllibdata = dispatch_data_create(sdl_metallib, sdl_metallib_len, dispatch_get_global_queue(0, 0), ^{}); + mtllibrary = [data.mtldevice newLibraryWithData:mtllibdata error:&err]; + data.mtllibrary = mtllibrary; + SDL_assert(err == nil); + data.mtllibrary.label = @"SDL Metal renderer shader library"; - /* Do some shader pipeline state loading up-front rather than on demand. */ - data.pipelinescount = 0; - data.allpipelines = NULL; - ChooseShaderPipelines(data, MTLPixelFormatBGRA8Unorm); + /* Do some shader pipeline state loading up-front rather than on demand. */ + data.pipelinescount = 0; + data.allpipelines = NULL; + ChooseShaderPipelines(data, MTLPixelFormatBGRA8Unorm); - samplerdesc = [[MTLSamplerDescriptor alloc] init]; + samplerdesc = [[MTLSamplerDescriptor alloc] init]; - samplerdesc.minFilter = MTLSamplerMinMagFilterNearest; - samplerdesc.magFilter = MTLSamplerMinMagFilterNearest; - mtlsamplernearest = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc]; - data.mtlsamplernearest = mtlsamplernearest; + samplerdesc.minFilter = MTLSamplerMinMagFilterNearest; + samplerdesc.magFilter = MTLSamplerMinMagFilterNearest; + mtlsamplernearest = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc]; + data.mtlsamplernearest = mtlsamplernearest; - samplerdesc.minFilter = MTLSamplerMinMagFilterLinear; - samplerdesc.magFilter = MTLSamplerMinMagFilterLinear; - mtlsamplerlinear = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc]; - data.mtlsamplerlinear = mtlsamplerlinear; + samplerdesc.minFilter = MTLSamplerMinMagFilterLinear; + samplerdesc.magFilter = MTLSamplerMinMagFilterLinear; + mtlsamplerlinear = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc]; + data.mtlsamplerlinear = mtlsamplerlinear; - mtlbufconstantstaging = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModeShared]; + mtlbufconstantstaging = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModeShared]; - constantdata = [mtlbufconstantstaging contents]; - SDL_memcpy(constantdata + CONSTANTS_OFFSET_IDENTITY, identitytransform, sizeof(identitytransform)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM, halfpixeltransform, sizeof(halfpixeltransform)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_JPEG, decodetransformJPEG, sizeof(decodetransformJPEG)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT601, decodetransformBT601, sizeof(decodetransformBT601)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT709, decodetransformBT709, sizeof(decodetransformBT709)); + constantdata = [mtlbufconstantstaging contents]; + SDL_memcpy(constantdata + CONSTANTS_OFFSET_IDENTITY, identitytransform, sizeof(identitytransform)); + SDL_memcpy(constantdata + CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM, halfpixeltransform, sizeof(halfpixeltransform)); + SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_JPEG, decodetransformJPEG, sizeof(decodetransformJPEG)); + SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT601, decodetransformBT601, sizeof(decodetransformBT601)); + SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT709, decodetransformBT709, sizeof(decodetransformBT709)); - mtlbufquadindicesstaging = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModeShared]; + mtlbufquadindicesstaging = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModeShared]; - /* Quads in the following vertex order (matches the FillRects vertices): - * 1---3 - * | \ | - * 0---2 - */ - indexdata = [mtlbufquadindicesstaging contents]; - for (int i = 0; i < quadcount; i++) { - indexdata[i * 6 + 0] = i * 4 + 0; - indexdata[i * 6 + 1] = i * 4 + 1; - indexdata[i * 6 + 2] = i * 4 + 2; + /* Quads in the following vertex order (matches the FillRects vertices): + * 1---3 + * | \ | + * 0---2 + */ + indexdata = [mtlbufquadindicesstaging contents]; + for (int i = 0; i < quadcount; i++) { + indexdata[i * 6 + 0] = i * 4 + 0; + indexdata[i * 6 + 1] = i * 4 + 1; + indexdata[i * 6 + 2] = i * 4 + 2; - indexdata[i * 6 + 3] = i * 4 + 2; - indexdata[i * 6 + 4] = i * 4 + 1; - indexdata[i * 6 + 5] = i * 4 + 3; - } + indexdata[i * 6 + 3] = i * 4 + 2; + indexdata[i * 6 + 4] = i * 4 + 1; + indexdata[i * 6 + 5] = i * 4 + 3; + } - mtlbufconstants = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModePrivate]; - data.mtlbufconstants = mtlbufconstants; - data.mtlbufconstants.label = @"SDL constant data"; + mtlbufconstants = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModePrivate]; + data.mtlbufconstants = mtlbufconstants; + data.mtlbufconstants.label = @"SDL constant data"; - mtlbufquadindices = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModePrivate]; - data.mtlbufquadindices = mtlbufquadindices; - data.mtlbufquadindices.label = @"SDL quad index buffer"; + mtlbufquadindices = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModePrivate]; + data.mtlbufquadindices = mtlbufquadindices; + data.mtlbufquadindices.label = @"SDL quad index buffer"; - cmdbuffer = [data.mtlcmdqueue commandBuffer]; - blitcmd = [cmdbuffer blitCommandEncoder]; + cmdbuffer = [data.mtlcmdqueue commandBuffer]; + blitcmd = [cmdbuffer blitCommandEncoder]; - [blitcmd copyFromBuffer:mtlbufconstantstaging sourceOffset:0 toBuffer:mtlbufconstants destinationOffset:0 size:CONSTANTS_LENGTH]; - [blitcmd copyFromBuffer:mtlbufquadindicesstaging sourceOffset:0 toBuffer:mtlbufquadindices destinationOffset:0 size:indicessize]; + [blitcmd copyFromBuffer:mtlbufconstantstaging sourceOffset:0 toBuffer:mtlbufconstants destinationOffset:0 size:CONSTANTS_LENGTH]; + [blitcmd copyFromBuffer:mtlbufquadindicesstaging sourceOffset:0 toBuffer:mtlbufquadindices destinationOffset:0 size:indicessize]; - [blitcmd endEncoding]; - [cmdbuffer commit]; + [blitcmd endEncoding]; + [cmdbuffer commit]; - // !!! FIXME: force more clears here so all the drawables are sane to start, and our static buffers are definitely flushed. + // !!! FIXME: force more clears here so all the drawables are sane to start, and our static buffers are definitely flushed. - renderer->WindowEvent = METAL_WindowEvent; - renderer->GetOutputSize = METAL_GetOutputSize; - renderer->SupportsBlendMode = METAL_SupportsBlendMode; - renderer->CreateTexture = METAL_CreateTexture; - renderer->UpdateTexture = METAL_UpdateTexture; + renderer->WindowEvent = METAL_WindowEvent; + renderer->GetOutputSize = METAL_GetOutputSize; + renderer->SupportsBlendMode = METAL_SupportsBlendMode; + renderer->CreateTexture = METAL_CreateTexture; + renderer->UpdateTexture = METAL_UpdateTexture; #if SDL_HAVE_YUV - renderer->UpdateTextureYUV = METAL_UpdateTextureYUV; - renderer->UpdateTextureNV = METAL_UpdateTextureNV; + renderer->UpdateTextureYUV = METAL_UpdateTextureYUV; + renderer->UpdateTextureNV = METAL_UpdateTextureNV; #endif - renderer->LockTexture = METAL_LockTexture; - renderer->UnlockTexture = METAL_UnlockTexture; - renderer->SetTextureScaleMode = METAL_SetTextureScaleMode; - renderer->SetRenderTarget = METAL_SetRenderTarget; - renderer->QueueSetViewport = METAL_QueueSetViewport; - renderer->QueueSetDrawColor = METAL_QueueSetDrawColor; - renderer->QueueDrawPoints = METAL_QueueDrawPoints; - renderer->QueueDrawLines = METAL_QueueDrawLines; - renderer->QueueGeometry = METAL_QueueGeometry; - renderer->RunCommandQueue = METAL_RunCommandQueue; - renderer->RenderReadPixels = METAL_RenderReadPixels; - renderer->RenderPresent = METAL_RenderPresent; - renderer->DestroyTexture = METAL_DestroyTexture; - renderer->DestroyRenderer = METAL_DestroyRenderer; - renderer->SetVSync = METAL_SetVSync; - renderer->GetMetalLayer = METAL_GetMetalLayer; - renderer->GetMetalCommandEncoder = METAL_GetMetalCommandEncoder; + renderer->LockTexture = METAL_LockTexture; + renderer->UnlockTexture = METAL_UnlockTexture; + renderer->SetTextureScaleMode = METAL_SetTextureScaleMode; + renderer->SetRenderTarget = METAL_SetRenderTarget; + renderer->QueueSetViewport = METAL_QueueSetViewport; + renderer->QueueSetDrawColor = METAL_QueueSetDrawColor; + renderer->QueueDrawPoints = METAL_QueueDrawPoints; + renderer->QueueDrawLines = METAL_QueueDrawLines; + renderer->QueueGeometry = METAL_QueueGeometry; + renderer->RunCommandQueue = METAL_RunCommandQueue; + renderer->RenderReadPixels = METAL_RenderReadPixels; + renderer->RenderPresent = METAL_RenderPresent; + renderer->DestroyTexture = METAL_DestroyTexture; + renderer->DestroyRenderer = METAL_DestroyRenderer; + renderer->SetVSync = METAL_SetVSync; + renderer->GetMetalLayer = METAL_GetMetalLayer; + renderer->GetMetalCommandEncoder = METAL_GetMetalCommandEncoder; - renderer->info = METAL_RenderDriver.info; - renderer->info.flags = (SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE); + renderer->info = METAL_RenderDriver.info; + renderer->info.flags = (SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE); - renderer->always_batch = SDL_TRUE; + renderer->always_batch = SDL_TRUE; #if (defined(__MACOSX__) && defined(MAC_OS_X_VERSION_10_13)) || TARGET_OS_MACCATALYST if (@available(macOS 10.13, *)) { @@ -1918,47 +1862,51 @@ static SDL_Renderer *METAL_CreateRenderer(SDL_Window *window, Uint32 flags) if (data.mtllayer.displaySyncEnabled) { renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; } + } else +#endif + { + renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; + } /* https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf */ maxtexsize = 4096; #if defined(__MACOSX__) || TARGET_OS_MACCATALYST maxtexsize = 16384; #elif defined(__TVOS__) - maxtexsize = 8192; + maxtexsize = 8192; #ifdef __TVOS_11_0 - if (@available(tvOS 11.0, *)) { - if ([mtldevice supportsFeatureSet:MTLFeatureSet_tvOS_GPUFamily2_v1]) { - maxtexsize = 16384; - } + if (@available(tvOS 11.0, *)) { + if ([mtldevice supportsFeatureSet:MTLFeatureSet_tvOS_GPUFamily2_v1]) { + maxtexsize = 16384; } + } #endif #else #ifdef __IPHONE_11_0 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" - if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily4_v1]) { - maxtexsize = 16384; - } else + if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily4_v1]) { + maxtexsize = 16384; + } else #pragma clang diagnostic pop #endif #ifdef __IPHONE_10_0 - if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) { - maxtexsize = 16384; - } else + if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) { + maxtexsize = 16384; + } else #endif - if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v2] || [mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily1_v2]) { - maxtexsize = 8192; - } else { - maxtexsize = 4096; - } -#endif - - renderer->info.max_texture_width = maxtexsize; - renderer->info.max_texture_height = maxtexsize; - - return renderer; + if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v2] || [mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily1_v2]) { + maxtexsize = 8192; + } else { + maxtexsize = 4096; } -} +#endif + + renderer->info.max_texture_width = maxtexsize; + renderer->info.max_texture_height = maxtexsize; + + return renderer; +}} SDL_RenderDriver METAL_RenderDriver = { METAL_CreateRenderer, @@ -1966,14 +1914,15 @@ SDL_RenderDriver METAL_RenderDriver = { "metal", (SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE), 6, - { SDL_PIXELFORMAT_ARGB8888, - SDL_PIXELFORMAT_ABGR8888, - SDL_PIXELFORMAT_YV12, - SDL_PIXELFORMAT_IYUV, - SDL_PIXELFORMAT_NV12, - SDL_PIXELFORMAT_NV21 }, - 0, - 0, + { + SDL_PIXELFORMAT_ARGB8888, + SDL_PIXELFORMAT_ABGR8888, + SDL_PIXELFORMAT_YV12, + SDL_PIXELFORMAT_IYUV, + SDL_PIXELFORMAT_NV12, + SDL_PIXELFORMAT_NV21 + }, + 0, 0, } }; diff --git a/src/video/cocoa/SDL_cocoaclipboard.h b/src/video/cocoa/SDL_cocoaclipboard.h index 30f588043..c8c4d6808 100644 --- a/src/video/cocoa/SDL_cocoaclipboard.h +++ b/src/video/cocoa/SDL_cocoaclipboard.h @@ -29,7 +29,7 @@ extern int Cocoa_SetClipboardText(_THIS, const char *text); extern char *Cocoa_GetClipboardText(_THIS); extern SDL_bool Cocoa_HasClipboardText(_THIS); -extern void Cocoa_CheckClipboardUpdate(SDL_VideoData *data); +extern void Cocoa_CheckClipboardUpdate(SDL_VideoData * data); #endif /* SDL_cocoaclipboard_h_ */ diff --git a/src/video/cocoa/SDL_cocoaclipboard.m b/src/video/cocoa/SDL_cocoaclipboard.m index 98fc48d1b..e3878ce8f 100644 --- a/src/video/cocoa/SDL_cocoaclipboard.m +++ b/src/video/cocoa/SDL_cocoaclipboard.m @@ -25,54 +25,53 @@ #include "SDL_cocoavideo.h" #include "../../events/SDL_clipboardevents_c.h" -int Cocoa_SetClipboardText(_THIS, const char *text) +int +Cocoa_SetClipboardText(_THIS, const char *text) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; - NSPasteboard *pasteboard; - NSString *format = NSPasteboardTypeString; - NSString *nsstr = [NSString stringWithUTF8String:text]; - if (nsstr == nil) { - return SDL_SetError("Couldn't create NSString; is your string data in UTF-8 format?"); - } - - pasteboard = [NSPasteboard generalPasteboard]; - data.clipboard_count = [pasteboard declareTypes:[NSArray arrayWithObject:format] owner:nil]; - [pasteboard setString:nsstr forType:format]; - - return 0; + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; + NSPasteboard *pasteboard; + NSString *format = NSPasteboardTypeString; + NSString *nsstr = [NSString stringWithUTF8String:text]; + if (nsstr == nil) { + return SDL_SetError("Couldn't create NSString; is your string data in UTF-8 format?"); } -} + + pasteboard = [NSPasteboard generalPasteboard]; + data.clipboard_count = [pasteboard declareTypes:[NSArray arrayWithObject:format] owner:nil]; + [pasteboard setString:nsstr forType:format]; + + return 0; +}} char * Cocoa_GetClipboardText(_THIS) +{ @autoreleasepool { - @autoreleasepool { - NSPasteboard *pasteboard; - NSString *format = NSPasteboardTypeString; - NSString *available; - char *text; + NSPasteboard *pasteboard; + NSString *format = NSPasteboardTypeString; + NSString *available; + char *text; - pasteboard = [NSPasteboard generalPasteboard]; - available = [pasteboard availableTypeFromArray:[NSArray arrayWithObject:format]]; - if ([available isEqualToString:format]) { - NSString *string; - const char *utf8; + pasteboard = [NSPasteboard generalPasteboard]; + available = [pasteboard availableTypeFromArray:[NSArray arrayWithObject:format]]; + if ([available isEqualToString:format]) { + NSString* string; + const char *utf8; - string = [pasteboard stringForType:format]; - if (string == nil) { - utf8 = ""; - } else { - utf8 = [string UTF8String]; - } - text = SDL_strdup(utf8 ? utf8 : ""); + string = [pasteboard stringForType:format]; + if (string == nil) { + utf8 = ""; } else { - text = SDL_strdup(""); + utf8 = [string UTF8String]; } - - return text; + text = SDL_strdup(utf8 ? utf8 : ""); + } else { + text = SDL_strdup(""); } -} + + return text; +}} SDL_bool Cocoa_HasClipboardText(_THIS) @@ -86,22 +85,22 @@ Cocoa_HasClipboardText(_THIS) return result; } -void Cocoa_CheckClipboardUpdate(SDL_VideoData *data) +void +Cocoa_CheckClipboardUpdate(SDL_VideoData * data) +{ @autoreleasepool { - @autoreleasepool { - NSPasteboard *pasteboard; - NSInteger count; + NSPasteboard *pasteboard; + NSInteger count; - pasteboard = [NSPasteboard generalPasteboard]; - count = [pasteboard changeCount]; - if (count != data.clipboard_count) { - if (data.clipboard_count) { - SDL_SendClipboardUpdate(); - } - data.clipboard_count = count; + pasteboard = [NSPasteboard generalPasteboard]; + count = [pasteboard changeCount]; + if (count != data.clipboard_count) { + if (data.clipboard_count) { + SDL_SendClipboardUpdate(); } + data.clipboard_count = count; } -} +}} #endif /* SDL_VIDEO_DRIVER_COCOA */ diff --git a/src/video/cocoa/SDL_cocoaevents.h b/src/video/cocoa/SDL_cocoaevents.h index 7187ce43f..ae49be099 100644 --- a/src/video/cocoa/SDL_cocoaevents.h +++ b/src/video/cocoa/SDL_cocoaevents.h @@ -25,7 +25,7 @@ extern void Cocoa_RegisterApp(void); extern void Cocoa_PumpEvents(_THIS); -extern int Cocoa_WaitEventTimeout(_THIS, int timeout); +extern int Cocoa_WaitEventTimeout(_THIS, int timeout); extern void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window); extern void Cocoa_SuspendScreenSaver(_THIS); diff --git a/src/video/cocoa/SDL_cocoaevents.m b/src/video/cocoa/SDL_cocoaevents.m index a959cebca..ed2aaa6c6 100644 --- a/src/video/cocoa/SDL_cocoaevents.m +++ b/src/video/cocoa/SDL_cocoaevents.m @@ -45,7 +45,7 @@ static SDL_Window *FindSDLWindowForNSWindow(NSWindow *win) SDL_VideoDevice *device = SDL_GetVideoDevice(); if (device && device->windows) { for (sdlwindow = device->windows; sdlwindow; sdlwindow = sdlwindow->next) { - NSWindow *nswindow = ((__bridge SDL_WindowData *)sdlwindow->driverdata).nswindow; + NSWindow *nswindow = ((__bridge SDL_WindowData *) sdlwindow->driverdata).nswindow; if (win == nswindow) return sdlwindow; } @@ -78,26 +78,26 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent) SDL_VideoDevice *_this = SDL_GetVideoDevice(); switch ([theEvent type]) { - case NSEventTypeLeftMouseDown: - case NSEventTypeOtherMouseDown: - case NSEventTypeRightMouseDown: - case NSEventTypeLeftMouseUp: - case NSEventTypeOtherMouseUp: - case NSEventTypeRightMouseUp: - case NSEventTypeLeftMouseDragged: - case NSEventTypeRightMouseDragged: - case NSEventTypeOtherMouseDragged: /* usually middle mouse dragged */ - case NSEventTypeMouseMoved: - case NSEventTypeScrollWheel: - Cocoa_HandleMouseEvent(_this, theEvent); - break; - case NSEventTypeKeyDown: - case NSEventTypeKeyUp: - case NSEventTypeFlagsChanged: - Cocoa_HandleKeyEvent(_this, theEvent); - break; - default: - break; + case NSEventTypeLeftMouseDown: + case NSEventTypeOtherMouseDown: + case NSEventTypeRightMouseDown: + case NSEventTypeLeftMouseUp: + case NSEventTypeOtherMouseUp: + case NSEventTypeRightMouseUp: + case NSEventTypeLeftMouseDragged: + case NSEventTypeRightMouseDragged: + case NSEventTypeOtherMouseDragged: /* usually middle mouse dragged */ + case NSEventTypeMouseMoved: + case NSEventTypeScrollWheel: + Cocoa_HandleMouseEvent(_this, theEvent); + break; + case NSEventTypeKeyDown: + case NSEventTypeKeyUp: + case NSEventTypeFlagsChanged: + Cocoa_HandleKeyEvent(_this, theEvent); + break; + default: + break; } } @@ -116,23 +116,22 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent) + (void)registerUserDefaults { NSDictionary *appDefaults = [[NSDictionary alloc] initWithObjectsAndKeys: - [NSNumber numberWithBool:NO], @"AppleMomentumScrollSupported", - [NSNumber numberWithBool:NO], @"ApplePressAndHoldEnabled", - [NSNumber numberWithBool:YES], @"ApplePersistenceIgnoreState", - nil]; + [NSNumber numberWithBool:NO], @"AppleMomentumScrollSupported", + [NSNumber numberWithBool:NO], @"ApplePressAndHoldEnabled", + [NSNumber numberWithBool:YES], @"ApplePersistenceIgnoreState", + nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; } @end // SDLApplication /* setAppleMenu disappeared from the headers in 10.4 */ -@interface NSApplication (NSAppleMenu) +@interface NSApplication(NSAppleMenu) - (void)setAppleMenu:(NSMenu *)menu; @end -@interface SDLAppDelegate : NSObject -{ - @public +@interface SDLAppDelegate : NSObject { +@public BOOL seenFirstActivate; } @@ -186,7 +185,7 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent) - (void)windowWillClose:(NSNotification *)notification; { - NSWindow *win = (NSWindow *)[notification object]; + NSWindow *win = (NSWindow*)[notification object]; if (![win isKeyWindow]) { return; @@ -293,7 +292,7 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent) [i activateWithOptions:NSApplicationActivateIgnoringOtherApps]; break; } - SDL_Delay(300); /* !!! FIXME: this isn't right. */ + SDL_Delay(300); /* !!! FIXME: this isn't right. */ [NSApp activateIgnoringOtherApps:YES]; } @@ -304,7 +303,7 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent) - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { - NSString *path = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; + NSString* path = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; SDL_SendDropFile(NULL, [path UTF8String]); SDL_SendDropComplete(NULL); } @@ -313,7 +312,8 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent) static SDLAppDelegate *appDelegate = nil; -static NSString *GetApplicationName(void) +static NSString * +GetApplicationName(void) { NSString *appName; @@ -330,7 +330,8 @@ static NSString *GetApplicationName(void) return appName; } -static bool LoadMainMenuNibIfAvailable(void) +static bool +LoadMainMenuNibIfAvailable(void) { #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 NSDictionary *infoDict; @@ -343,19 +344,20 @@ static bool LoadMainMenuNibIfAvailable(void) infoDict = [[NSBundle mainBundle] infoDictionary]; if (infoDict) { mainNibFileName = [infoDict valueForKey:@"NSMainNibFile"]; - + if (mainNibFileName) { success = [[NSBundle mainBundle] loadNibNamed:mainNibFileName owner:[NSApplication sharedApplication] topLevelObjects:nil]; } } - + return success; #else return false; #endif } -static void CreateApplicationMenus(void) +static void +CreateApplicationMenus(void) { NSString *appName; NSString *title; @@ -368,7 +370,7 @@ static void CreateApplicationMenus(void) if (NSApp == nil) { return; } - + mainMenu = [[NSMenu alloc] init]; /* Create the main menu bar */ @@ -400,7 +402,7 @@ static void CreateApplicationMenus(void) [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; - [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)]; + [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; @@ -426,7 +428,7 @@ static void CreateApplicationMenus(void) [windowMenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [windowMenu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""]; - + /* Add the fullscreen toggle menu option. */ /* Cocoa should update the title to Enter or Exit Full Screen automatically. * But if not, then just fallback to Toggle Full Screen. @@ -444,70 +446,71 @@ static void CreateApplicationMenus(void) [NSApp setWindowsMenu:windowMenu]; } -void Cocoa_RegisterApp(void) +void +Cocoa_RegisterApp(void) +{ @autoreleasepool { - @autoreleasepool { - /* This can get called more than once! Be careful what you initialize! */ + /* This can get called more than once! Be careful what you initialize! */ - if (NSApp == nil) { - [SDLApplication sharedApplication]; - SDL_assert(NSApp != nil); + if (NSApp == nil) { + [SDLApplication sharedApplication]; + SDL_assert(NSApp != nil); - s_bShouldHandleEventsInSDLApplication = SDL_TRUE; + s_bShouldHandleEventsInSDLApplication = SDL_TRUE; - if (!SDL_GetHintBoolean(SDL_HINT_MAC_BACKGROUND_APP, SDL_FALSE)) { - [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - } + if (!SDL_GetHintBoolean(SDL_HINT_MAC_BACKGROUND_APP, SDL_FALSE)) { + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + } - /* If there aren't already menus in place, look to see if there's - * a nib we should use. If not, then manually create the basic - * menus we meed. - */ - if ([NSApp mainMenu] == nil) { - bool nibLoaded; - - nibLoaded = LoadMainMenuNibIfAvailable(); - if (!nibLoaded) { - CreateApplicationMenus(); - } - } - [NSApp finishLaunching]; - if ([NSApp delegate]) { - /* The SDL app delegate calls this in didFinishLaunching if it's - * attached to the NSApp, otherwise we need to call it manually. - */ - [SDLApplication registerUserDefaults]; + /* If there aren't already menus in place, look to see if there's + * a nib we should use. If not, then manually create the basic + * menus we meed. + */ + if ([NSApp mainMenu] == nil) { + bool nibLoaded; + + nibLoaded = LoadMainMenuNibIfAvailable(); + if (!nibLoaded) { + CreateApplicationMenus(); } } - if (NSApp && !appDelegate) { - appDelegate = [[SDLAppDelegate alloc] init]; - - /* If someone else has an app delegate, it means we can't turn a - * termination into SDL_Quit, and we can't handle application:openFile: + [NSApp finishLaunching]; + if ([NSApp delegate]) { + /* The SDL app delegate calls this in didFinishLaunching if it's + * attached to the NSApp, otherwise we need to call it manually. */ - if (![NSApp delegate]) { - /* Only register the URL event handler if we are being set as the - * app delegate to avoid replacing any existing event handler. - */ - [[NSAppleEventManager sharedAppleEventManager] - setEventHandler:appDelegate - andSelector:@selector(handleURLEvent:withReplyEvent:) - forEventClass:kInternetEventClass - andEventID:kAEGetURL]; - - [(NSApplication *)NSApp setDelegate:appDelegate]; - } else { - appDelegate->seenFirstActivate = YES; - } + [SDLApplication registerUserDefaults]; } } -} + if (NSApp && !appDelegate) { + appDelegate = [[SDLAppDelegate alloc] init]; -int Cocoa_PumpEventsUntilDate(_THIS, NSDate *expiration, bool accumulate) + /* If someone else has an app delegate, it means we can't turn a + * termination into SDL_Quit, and we can't handle application:openFile: + */ + if (![NSApp delegate]) { + /* Only register the URL event handler if we are being set as the + * app delegate to avoid replacing any existing event handler. + */ + [[NSAppleEventManager sharedAppleEventManager] + setEventHandler:appDelegate + andSelector:@selector(handleURLEvent:withReplyEvent:) + forEventClass:kInternetEventClass + andEventID:kAEGetURL]; + + [(NSApplication *)NSApp setDelegate:appDelegate]; + } else { + appDelegate->seenFirstActivate = YES; + } + } +}} + +int +Cocoa_PumpEventsUntilDate(_THIS, NSDate *expiration, bool accumulate) { - for (;;) { - NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:expiration inMode:NSDefaultRunLoopMode dequeue:YES]; - if (event == nil) { + for ( ; ; ) { + NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:expiration inMode:NSDefaultRunLoopMode dequeue:YES ]; + if ( event == nil ) { return 0; } @@ -517,62 +520,62 @@ int Cocoa_PumpEventsUntilDate(_THIS, NSDate *expiration, bool accumulate) // Pass events down to SDLApplication to be handled in sendEvent: [NSApp sendEvent:event]; - if (!accumulate) { + if ( !accumulate) { break; } } return 1; } -int Cocoa_WaitEventTimeout(_THIS, int timeout) +int +Cocoa_WaitEventTimeout(_THIS, int timeout) +{ @autoreleasepool { - @autoreleasepool { - if (timeout > 0) { - NSDate *limitDate = [NSDate dateWithTimeIntervalSinceNow:(double)timeout / 1000.0]; - return Cocoa_PumpEventsUntilDate(_this, limitDate, false); - } else if (timeout == 0) { - return Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], false); - } else { - while (Cocoa_PumpEventsUntilDate(_this, [NSDate distantFuture], false) == 0) { - } + if (timeout > 0) { + NSDate *limitDate = [NSDate dateWithTimeIntervalSinceNow: (double) timeout / 1000.0]; + return Cocoa_PumpEventsUntilDate(_this, limitDate, false); + } else if (timeout == 0) { + return Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], false); + } else { + while (Cocoa_PumpEventsUntilDate(_this, [NSDate distantFuture], false) == 0) { } - return 1; } -} + return 1; +}} -void Cocoa_PumpEvents(_THIS) +void +Cocoa_PumpEvents(_THIS) +{ @autoreleasepool { - @autoreleasepool { - Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], true); - } -} + Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], true); +}} void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window) +{ @autoreleasepool { - @autoreleasepool { - NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined - location:NSMakePoint(0, 0) - modifierFlags:0 - timestamp:0.0 - windowNumber:((__bridge SDL_WindowData *)window->driverdata).window_number - context:nil - subtype:0 - data1:0 - data2:0]; + NSEvent* event = [NSEvent otherEventWithType: NSEventTypeApplicationDefined + location: NSMakePoint(0,0) + modifierFlags: 0 + timestamp: 0.0 + windowNumber: ((__bridge SDL_WindowData *) window->driverdata).window_number + context: nil + subtype: 0 + data1: 0 + data2: 0]; - [NSApp postEvent:event atStart:YES]; + [NSApp postEvent: event atStart: YES]; +}} + +void +Cocoa_SuspendScreenSaver(_THIS) +{ @autoreleasepool +{ + SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; + + if (data.screensaver_assertion) { + IOPMAssertionRelease(data.screensaver_assertion); + data.screensaver_assertion = kIOPMNullAssertionID; } -} - -void Cocoa_SuspendScreenSaver(_THIS) -{ - @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; - - if (data.screensaver_assertion) { - IOPMAssertionRelease(data.screensaver_assertion); - data.screensaver_assertion = kIOPMNullAssertionID; - } if (_this->suspend_screensaver) { /* FIXME: this should ideally describe the real reason why the game @@ -588,7 +591,7 @@ void Cocoa_SuspendScreenSaver(_THIS) &assertion); data.screensaver_assertion = assertion; } -} +}} #endif /* SDL_VIDEO_DRIVER_COCOA */ diff --git a/src/video/cocoa/SDL_cocoakeyboard.h b/src/video/cocoa/SDL_cocoakeyboard.h index 8d068151f..e3b8460b7 100644 --- a/src/video/cocoa/SDL_cocoakeyboard.h +++ b/src/video/cocoa/SDL_cocoakeyboard.h @@ -24,14 +24,14 @@ #define SDL_cocoakeyboard_h_ extern void Cocoa_InitKeyboard(_THIS); -extern void Cocoa_HandleKeyEvent(_THIS, NSEvent *event); +extern void Cocoa_HandleKeyEvent(_THIS, NSEvent * event); extern void Cocoa_QuitKeyboard(_THIS); extern void Cocoa_StartTextInput(_THIS); extern void Cocoa_StopTextInput(_THIS); extern void Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect); -extern void Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window *window, SDL_bool grabbed); +extern void Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window * window, SDL_bool grabbed); #endif /* SDL_cocoakeyboard_h_ */ diff --git a/src/video/cocoa/SDL_cocoakeyboard.m b/src/video/cocoa/SDL_cocoakeyboard.m index 43e3c9696..096b71a4c 100644 --- a/src/video/cocoa/SDL_cocoakeyboard.m +++ b/src/video/cocoa/SDL_cocoakeyboard.m @@ -33,12 +33,11 @@ /*#define DEBUG_IME NSLog */ #define DEBUG_IME(...) -@interface SDLTranslatorResponder : NSView -{ +@interface SDLTranslatorResponder : NSView { NSString *_markedText; - NSRange _markedRange; - NSRange _selectedRange; - SDL_Rect _inputRect; + NSRange _markedRange; + NSRange _selectedRange; + SDL_Rect _inputRect; } - (void)doCommandBySelector:(SEL)myselector; - (void)setInputRect:(const SDL_Rect *)rect; @@ -61,7 +60,7 @@ /* Could be NSString or NSAttributedString, so we have * to test and convert it before return as SDL event */ - if ([aString isKindOfClass:[NSAttributedString class]]) { + if ([aString isKindOfClass: [NSAttributedString class]]) { str = [[aString string] UTF8String]; } else { str = [aString UTF8String]; @@ -117,10 +116,10 @@ _markedRange = NSMakeRange(0, [aString length]); SDL_SendEditingText([aString UTF8String], - (int)selectedRange.location, (int)selectedRange.length); + (int) selectedRange.location, (int) selectedRange.length); DEBUG_IME(@"setMarkedText: %@, (%d, %d)", _markedText, - selectedRange.location, selectedRange.length); + selectedRange.location, selectedRange.length); } - (void)unmarkText @@ -143,8 +142,8 @@ } DEBUG_IME(@"firstRectForCharacterRange: (%d, %d): windowHeight = %g, rect = %@", - aRange.location, aRange.length, windowHeight, - NSStringFromRect(rect)); + aRange.location, aRange.length, windowHeight, + NSStringFromRect(rect)); rect = [window convertRectToScreen:rect]; @@ -159,7 +158,7 @@ - (NSInteger)conversationIdentifier { - return (NSInteger)self; + return (NSInteger) self; } /* This method returns the index for character that is @@ -183,42 +182,43 @@ @end -static void HandleModifiers(_THIS, unsigned short scancode, unsigned int modifierFlags) +static void +HandleModifiers(_THIS, unsigned short scancode, unsigned int modifierFlags) { SDL_Scancode code = darwin_scancode_table[scancode]; - const SDL_Scancode codes[] = { - SDL_SCANCODE_LSHIFT, - SDL_SCANCODE_LCTRL, - SDL_SCANCODE_LALT, - SDL_SCANCODE_LGUI, - SDL_SCANCODE_RSHIFT, - SDL_SCANCODE_RCTRL, - SDL_SCANCODE_RALT, - SDL_SCANCODE_RGUI, - SDL_SCANCODE_LSHIFT, - SDL_SCANCODE_LCTRL, - SDL_SCANCODE_LALT, - SDL_SCANCODE_LGUI, - }; + const SDL_Scancode codes[] = { + SDL_SCANCODE_LSHIFT, + SDL_SCANCODE_LCTRL, + SDL_SCANCODE_LALT, + SDL_SCANCODE_LGUI, + SDL_SCANCODE_RSHIFT, + SDL_SCANCODE_RCTRL, + SDL_SCANCODE_RALT, + SDL_SCANCODE_RGUI, + SDL_SCANCODE_LSHIFT, + SDL_SCANCODE_LCTRL, + SDL_SCANCODE_LALT, + SDL_SCANCODE_LGUI, }; - const unsigned int modifiers[] = { - NX_DEVICELSHIFTKEYMASK, - NX_DEVICELCTLKEYMASK, - NX_DEVICELALTKEYMASK, - NX_DEVICELCMDKEYMASK, - NX_DEVICERSHIFTKEYMASK, - NX_DEVICERCTLKEYMASK, - NX_DEVICERALTKEYMASK, + const unsigned int modifiers[] = { + NX_DEVICELSHIFTKEYMASK, + NX_DEVICELCTLKEYMASK, + NX_DEVICELALTKEYMASK, + NX_DEVICELCMDKEYMASK, + NX_DEVICERSHIFTKEYMASK, + NX_DEVICERCTLKEYMASK, + NX_DEVICERALTKEYMASK, NX_DEVICERCMDKEYMASK, NX_SHIFTMASK, - NX_CONTROLMASK, + NX_CONTROLMASK, NX_ALTERNATEMASK, - NX_COMMANDMASK - }; + NX_COMMANDMASK }; - for (int i = 0; i < 12; i++) { - if (code == codes[i]) { + for (int i = 0; i < 12; i++) + { + if (code == codes[i]) + { if (modifierFlags & modifiers[i]) SDL_SendKeyboardKey(SDL_PRESSED, code); else @@ -227,7 +227,8 @@ static void HandleModifiers(_THIS, unsigned short scancode, unsigned int modifie } } -static void UpdateKeymap(SDL_VideoData *data, SDL_bool send_event) +static void +UpdateKeymap(SDL_VideoData *data, SDL_bool send_event) { TISInputSourceRef key_layout; const void *chr_data; @@ -270,11 +271,11 @@ static void UpdateKeymap(SDL_VideoData *data, SDL_bool send_event) } dead_key_state = 0; - err = UCKeyTranslate((UCKeyboardLayout *)chr_data, - i, kUCKeyActionDown, - 0, keyboard_type, - kUCKeyTranslateNoDeadKeysMask, - &dead_key_state, 8, &len, s); + err = UCKeyTranslate ((UCKeyboardLayout *) chr_data, + i, kUCKeyActionDown, + 0, keyboard_type, + kUCKeyTranslateNoDeadKeysMask, + &dead_key_state, 8, &len, s); if (err != noErr) { continue; } @@ -291,9 +292,10 @@ cleanup: CFRelease(key_layout); } -void Cocoa_InitKeyboard(_THIS) +void +Cocoa_InitKeyboard(_THIS) { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; UpdateKeymap(data, SDL_FALSE); @@ -309,53 +311,54 @@ void Cocoa_InitKeyboard(_THIS) SDL_ToggleModState(KMOD_CAPS, (data.modifierFlags & NSEventModifierFlagCapsLock) != 0); } -void Cocoa_StartTextInput(_THIS) +void +Cocoa_StartTextInput(_THIS) +{ @autoreleasepool { - @autoreleasepool { - NSView *parentView; - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; - SDL_Window *window = SDL_GetKeyboardFocus(); - NSWindow *nswindow = nil; - if (window) { - nswindow = ((__bridge SDL_WindowData *)window->driverdata).nswindow; - } - - parentView = [nswindow contentView]; - - /* We only keep one field editor per process, since only the front most - * window can receive text input events, so it make no sense to keep more - * than one copy. When we switched to another window and requesting for - * text input, simply remove the field editor from its superview then add - * it to the front most window's content view */ - if (!data.fieldEdit) { - data.fieldEdit = - [[SDLTranslatorResponder alloc] initWithFrame:NSMakeRect(0.0, 0.0, 0.0, 0.0)]; - } - - if (![[data.fieldEdit superview] isEqual:parentView]) { - /* DEBUG_IME(@"add fieldEdit to window contentView"); */ - [data.fieldEdit removeFromSuperview]; - [parentView addSubview:data.fieldEdit]; - [nswindow makeFirstResponder:data.fieldEdit]; - } + NSView *parentView; + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; + SDL_Window *window = SDL_GetKeyboardFocus(); + NSWindow *nswindow = nil; + if (window) { + nswindow = ((__bridge SDL_WindowData*)window->driverdata).nswindow; } -} -void Cocoa_StopTextInput(_THIS) -{ - @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; + parentView = [nswindow contentView]; - if (data && data.fieldEdit) { - [data.fieldEdit removeFromSuperview]; - data.fieldEdit = nil; - } + /* We only keep one field editor per process, since only the front most + * window can receive text input events, so it make no sense to keep more + * than one copy. When we switched to another window and requesting for + * text input, simply remove the field editor from its superview then add + * it to the front most window's content view */ + if (!data.fieldEdit) { + data.fieldEdit = + [[SDLTranslatorResponder alloc] initWithFrame: NSMakeRect(0.0, 0.0, 0.0, 0.0)]; } -} -void Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect) + if (![[data.fieldEdit superview] isEqual:parentView]) { + /* DEBUG_IME(@"add fieldEdit to window contentView"); */ + [data.fieldEdit removeFromSuperview]; + [parentView addSubview: data.fieldEdit]; + [nswindow makeFirstResponder: data.fieldEdit]; + } +}} + +void +Cocoa_StopTextInput(_THIS) +{ @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; + + if (data && data.fieldEdit) { + [data.fieldEdit removeFromSuperview]; + data.fieldEdit = nil; + } +}} + +void +Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect) +{ + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; if (!rect) { SDL_InvalidParamError("rect"); @@ -365,13 +368,14 @@ void Cocoa_SetTextInputRect(_THIS, const SDL_Rect *rect) [data.fieldEdit setInputRect:rect]; } -void Cocoa_HandleKeyEvent(_THIS, NSEvent *event) +void +Cocoa_HandleKeyEvent(_THIS, NSEvent *event) { unsigned short scancode; SDL_Scancode code; - SDL_VideoData *data = _this ? ((__bridge SDL_VideoData *)_this->driverdata) : nil; + SDL_VideoData *data = _this ? ((__bridge SDL_VideoData *) _this->driverdata) : nil; if (!data) { - return; /* can happen when returning from fullscreen Space on shutdown */ + return; /* can happen when returning from fullscreen Space on shutdown */ } scancode = [event keyCode]; @@ -420,20 +424,20 @@ void Cocoa_HandleKeyEvent(_THIS, NSEvent *event) SDL_SendKeyboardKey(SDL_RELEASED, code); break; case NSEventTypeFlagsChanged: - HandleModifiers(_this, scancode, (unsigned int)[event modifierFlags]); + HandleModifiers(_this, scancode, (unsigned int)[event modifierFlags]); break; default: /* just to avoid compiler warnings */ break; } } -void Cocoa_QuitKeyboard(_THIS) +void +Cocoa_QuitKeyboard(_THIS) { } typedef int CGSConnection; -typedef enum -{ +typedef enum { CGSGlobalHotKeyEnable = 0, CGSGlobalHotKeyDisable = 1, } CGSGlobalHotKeyOperatingMode; @@ -441,7 +445,8 @@ typedef enum extern CGSConnection _CGSDefaultConnection(void); extern CGError CGSSetGlobalHotKeyOperatingMode(CGSConnection connection, CGSGlobalHotKeyOperatingMode mode); -void Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window *window, SDL_bool grabbed) +void +Cocoa_SetWindowKeyboardGrab(_THIS, SDL_Window * window, SDL_bool grabbed) { #if SDL_MAC_NO_SANDBOX CGSSetGlobalHotKeyOperatingMode(_CGSDefaultConnection(), grabbed ? CGSGlobalHotKeyDisable : CGSGlobalHotKeyEnable); diff --git a/src/video/cocoa/SDL_cocoamessagebox.m b/src/video/cocoa/SDL_cocoamessagebox.m index 1a3d622dd..1f8eddc3a 100644 --- a/src/video/cocoa/SDL_cocoamessagebox.m +++ b/src/video/cocoa/SDL_cocoamessagebox.m @@ -27,18 +27,17 @@ #include "SDL_messagebox.h" #include "SDL_cocoavideo.h" -@interface SDLMessageBoxPresenter : NSObject -{ - @public +@interface SDLMessageBoxPresenter : NSObject { +@public NSInteger clicked; NSWindow *nswindow; } -- (id)initWithParentWindow:(SDL_Window *)window; -- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; +- (id) initWithParentWindow:(SDL_Window *)window; +- (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; @end @implementation SDLMessageBoxPresenter -- (id)initWithParentWindow:(SDL_Window *)window +- (id) initWithParentWindow:(SDL_Window *)window { self = [super init]; if (self) { @@ -46,7 +45,7 @@ /* Retain the NSWindow because we'll show the alert later on the main thread */ if (window) { - nswindow = ((__bridge SDL_WindowData *)window->driverdata).nswindow; + nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow; } else { nswindow = nil; } @@ -55,23 +54,19 @@ return self; } -- (void)showAlert:(NSAlert *)alert +- (void)showAlert:(NSAlert*)alert { if (nswindow) { #ifdef MAC_OS_X_VERSION_10_9 if ([alert respondsToSelector:@selector(beginSheetModalForWindow:completionHandler:)]) { - [alert beginSheetModalForWindow:nswindow - completionHandler:^(NSModalResponse returnCode) { - self->clicked = returnCode; - }]; + [alert beginSheetModalForWindow:nswindow completionHandler:^(NSModalResponse returnCode) { + self->clicked = returnCode; + }]; } else #endif { #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090 - [alert beginSheetModalForWindow:nswindow - modalDelegate:self - didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) - contextInfo:nil]; + [alert beginSheetModalForWindow:nswindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil]; #endif } @@ -86,18 +81,20 @@ } } -- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo +- (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo { clicked = returnCode; } @end -static void Cocoa_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue) + +static void +Cocoa_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue) { - NSAlert *alert; + NSAlert* alert; const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons; - SDLMessageBoxPresenter *presenter; + SDLMessageBoxPresenter* presenter; NSInteger clicked; int i; Cocoa_RegisterApp(); @@ -153,21 +150,19 @@ static void Cocoa_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, i } /* Display a Cocoa message box */ -int Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) +int +Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) +{ @autoreleasepool { - @autoreleasepool { - __block int returnValue = 0; + __block int returnValue = 0; - if ([NSThread isMainThread]) { - Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); - } else { - dispatch_sync(dispatch_get_main_queue(), ^{ - Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); - }); - } - return returnValue; + if ([NSThread isMainThread]) { + Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); + } else { + dispatch_sync(dispatch_get_main_queue(), ^{ Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); }); } -} + return returnValue; +}} #endif /* SDL_VIDEO_DRIVER_COCOA */ diff --git a/src/video/cocoa/SDL_cocoametalview.h b/src/video/cocoa/SDL_cocoametalview.h index cbbc55bce..326c6a3ce 100644 --- a/src/video/cocoa/SDL_cocoametalview.h +++ b/src/video/cocoa/SDL_cocoametalview.h @@ -39,6 +39,7 @@ #import #import + @interface SDL_cocoametalview : NSView - (instancetype)initWithFrame:(NSRect)frame @@ -49,20 +50,21 @@ - (NSView *)hitTest:(NSPoint)point; /* Override superclass tag so this class can set it. */ -@property(assign, readonly) NSInteger tag; +@property (assign, readonly) NSInteger tag; -@property(nonatomic) BOOL highDPI; -@property(nonatomic) Uint32 sdlWindowID; +@property (nonatomic) BOOL highDPI; +@property (nonatomic) Uint32 sdlWindowID; @end -SDL_MetalView Cocoa_Metal_CreateView(_THIS, SDL_Window *window); +SDL_MetalView Cocoa_Metal_CreateView(_THIS, SDL_Window * window); void Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view); void *Cocoa_Metal_GetLayer(_THIS, SDL_MetalView view); -void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h); +void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h); #endif /* SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */ #endif /* SDL_cocoametalview_h_ */ /* vi: set ts=4 sw=4 expandtab: */ + diff --git a/src/video/cocoa/SDL_cocoametalview.m b/src/video/cocoa/SDL_cocoametalview.m index 2badd33f8..7c424ba19 100644 --- a/src/video/cocoa/SDL_cocoametalview.m +++ b/src/video/cocoa/SDL_cocoametalview.m @@ -33,7 +33,9 @@ #include "SDL_events.h" #include "SDL_syswm.h" -static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event) + +static int SDLCALL +SDL_MetalViewEventWatch(void *userdata, SDL_Event *event) { /* Update the drawable size when SDL receives a size changed event for * the window that contains the metal view. It would be nice to use @@ -70,7 +72,7 @@ static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event) /* When the wantsLayer property is set to YES, this method will be invoked to * return a layer instance. */ -- (CALayer *)makeBackingLayer +- (CALayer*)makeBackingLayer { return [self.class.layerClass layer]; } @@ -91,7 +93,7 @@ static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event) [self updateDrawableSize]; } - + return self; } @@ -122,78 +124,71 @@ static int SDLCALL SDL_MetalViewEventWatch(void *userdata, SDL_Event *event) metalLayer.drawableSize = NSSizeToCGSize(backingSize); } -- (NSView *)hitTest:(NSPoint)point -{ +- (NSView *)hitTest:(NSPoint)point { return nil; } @end SDL_MetalView -Cocoa_Metal_CreateView(_THIS, SDL_Window *window) -{ - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - NSView *view = data.nswindow.contentView; - BOOL highDPI = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; - Uint32 windowID = SDL_GetWindowID(window); - SDL_cocoametalview *newview; - SDL_MetalView metalview; +Cocoa_Metal_CreateView(_THIS, SDL_Window * window) +{ @autoreleasepool { + SDL_WindowData* data = (__bridge SDL_WindowData *)window->driverdata; + NSView *view = data.nswindow.contentView; + BOOL highDPI = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; + Uint32 windowID = SDL_GetWindowID(window); + SDL_cocoametalview *newview; + SDL_MetalView metalview; - newview = [[SDL_cocoametalview alloc] initWithFrame:view.frame - highDPI:highDPI - windowID:windowID]; - if (newview == nil) { - SDL_OutOfMemory(); - return NULL; - } - - [view addSubview:newview]; - - metalview = (SDL_MetalView)CFBridgingRetain(newview); - - return metalview; + newview = [[SDL_cocoametalview alloc] initWithFrame:view.frame + highDPI:highDPI + windowID:windowID]; + if (newview == nil) { + SDL_OutOfMemory(); + return NULL; } -} -void Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view) -{ - @autoreleasepool { - SDL_cocoametalview *metalview = CFBridgingRelease(view); - [metalview removeFromSuperview]; - } -} + [view addSubview:newview]; + + metalview = (SDL_MetalView)CFBridgingRetain(newview); + + return metalview; +}} + +void +Cocoa_Metal_DestroyView(_THIS, SDL_MetalView view) +{ @autoreleasepool { + SDL_cocoametalview *metalview = CFBridgingRelease(view); + [metalview removeFromSuperview]; +}} void * Cocoa_Metal_GetLayer(_THIS, SDL_MetalView view) -{ - @autoreleasepool { - SDL_cocoametalview *cocoaview = (__bridge SDL_cocoametalview *)view; - return (__bridge void *)cocoaview.layer; - } -} +{ @autoreleasepool { + SDL_cocoametalview *cocoaview = (__bridge SDL_cocoametalview *)view; + return (__bridge void *)cocoaview.layer; +}} -void Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h) -{ - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - NSView *contentView = data.sdlContentView; - SDL_cocoametalview *metalview = [contentView viewWithTag:SDL_METALVIEW_TAG]; - if (metalview) { - CAMetalLayer *layer = (CAMetalLayer *)metalview.layer; - SDL_assert(layer != NULL); - if (w) { - *w = layer.drawableSize.width; - } - if (h) { - *h = layer.drawableSize.height; - } - } else { - /* Fall back to the viewport size. */ - SDL_GetWindowSizeInPixels(window, w, h); +void +Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) +{ @autoreleasepool { + SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + NSView *contentView = data.sdlContentView; + SDL_cocoametalview* metalview = [contentView viewWithTag:SDL_METALVIEW_TAG]; + if (metalview) { + CAMetalLayer *layer = (CAMetalLayer*)metalview.layer; + SDL_assert(layer != NULL); + if (w) { + *w = layer.drawableSize.width; } + if (h) { + *h = layer.drawableSize.height; + } + } else { + /* Fall back to the viewport size. */ + SDL_GetWindowSizeInPixels(window, w, h); } -} +}} #endif /* SDL_VIDEO_DRIVER_COCOA && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */ diff --git a/src/video/cocoa/SDL_cocoamodes.h b/src/video/cocoa/SDL_cocoamodes.h index ee1f95109..a4176dee8 100644 --- a/src/video/cocoa/SDL_cocoamodes.h +++ b/src/video/cocoa/SDL_cocoamodes.h @@ -34,11 +34,11 @@ typedef struct } SDL_DisplayModeData; extern void Cocoa_InitModes(_THIS); -extern int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect); -extern int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect); -extern void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display); -extern int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hpdi, float *vdpi); -extern int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode); +extern int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); +extern int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); +extern void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display); +extern int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hpdi, float * vdpi); +extern int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); extern void Cocoa_QuitModes(_THIS); #endif /* SDL_cocoamodes_h_ */ diff --git a/src/video/cocoa/SDL_cocoamodes.m b/src/video/cocoa/SDL_cocoamodes.m index d91bf9f9e..072afc8e7 100644 --- a/src/video/cocoa/SDL_cocoamodes.m +++ b/src/video/cocoa/SDL_cocoamodes.m @@ -41,7 +41,9 @@ #define kDisplayModeNativeFlag 0x02000000 #endif -static int CG_SetError(const char *prefix, CGDisplayErr result) + +static int +CG_SetError(const char *prefix, CGDisplayErr result) { const char *error; @@ -83,22 +85,24 @@ static int CG_SetError(const char *prefix, CGDisplayErr result) return SDL_SetError("%s: %s", prefix, error); } -static int GetDisplayModeRefreshRate(CGDisplayModeRef vidmode, CVDisplayLinkRef link) +static int +GetDisplayModeRefreshRate(CGDisplayModeRef vidmode, CVDisplayLinkRef link) { - int refreshRate = (int)(CGDisplayModeGetRefreshRate(vidmode) + 0.5); + int refreshRate = (int) (CGDisplayModeGetRefreshRate(vidmode) + 0.5); /* CGDisplayModeGetRefreshRate can return 0 (eg for built-in displays). */ if (refreshRate == 0 && link != NULL) { CVTime time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link); if ((time.flags & kCVTimeIsIndefinite) == 0 && time.timeValue != 0) { - refreshRate = (int)((time.timeScale / (double)time.timeValue) + 0.5); + refreshRate = (int) ((time.timeScale / (double) time.timeValue) + 0.5); } } return refreshRate; } -static SDL_bool HasValidDisplayModeFlags(CGDisplayModeRef vidmode) +static SDL_bool +HasValidDisplayModeFlags(CGDisplayModeRef vidmode) { uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode); @@ -115,7 +119,8 @@ static SDL_bool HasValidDisplayModeFlags(CGDisplayModeRef vidmode) return SDL_TRUE; } -static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode) +static Uint32 +GetDisplayModePixelFormat(CGDisplayModeRef vidmode) { /* This API is deprecated in 10.11 with no good replacement (as of 10.15). */ CFStringRef fmt = CGDisplayModeCopyPixelEncoding(vidmode); @@ -125,10 +130,10 @@ static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode) kCFCompareCaseInsensitive) == kCFCompareEqualTo) { pixelformat = SDL_PIXELFORMAT_ARGB8888; } else if (CFStringCompare(fmt, CFSTR(IO16BitDirectPixels), - kCFCompareCaseInsensitive) == kCFCompareEqualTo) { + kCFCompareCaseInsensitive) == kCFCompareEqualTo) { pixelformat = SDL_PIXELFORMAT_ARGB1555; } else if (CFStringCompare(fmt, CFSTR(kIO30BitDirectPixels), - kCFCompareCaseInsensitive) == kCFCompareEqualTo) { + kCFCompareCaseInsensitive) == kCFCompareEqualTo) { pixelformat = SDL_PIXELFORMAT_ARGB2101010; } else { /* ignore 8-bit and such for now. */ @@ -139,12 +144,13 @@ static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode) return pixelformat; } -static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmodeCurrent, CFArrayRef modelist, CVDisplayLinkRef link, SDL_DisplayMode *mode) +static SDL_bool +GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmodeCurrent, CFArrayRef modelist, CVDisplayLinkRef link, SDL_DisplayMode *mode) { SDL_DisplayModeData *data; bool usableForGUI = CGDisplayModeIsUsableForDesktopGUI(vidmode); - int width = (int)CGDisplayModeGetWidth(vidmode); - int height = (int)CGDisplayModeGetHeight(vidmode); + int width = (int) CGDisplayModeGetWidth(vidmode); + int height = (int) CGDisplayModeGetHeight(vidmode); uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode); int refreshrate = GetDisplayModeRefreshRate(vidmode, link); Uint32 format = GetDisplayModePixelFormat(vidmode); @@ -172,17 +178,17 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode * CGDisplayModeGetPixelWidth and friends are only available in 10.8+. */ #ifdef MAC_OS_X_VERSION_10_8 if (modelist != NULL && floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) { - int pixelW = (int)CGDisplayModeGetPixelWidth(vidmode); - int pixelH = (int)CGDisplayModeGetPixelHeight(vidmode); + int pixelW = (int) CGDisplayModeGetPixelWidth(vidmode); + int pixelH = (int) CGDisplayModeGetPixelHeight(vidmode); CFIndex modescount = CFArrayGetCount(modelist); - int i; + int i; for (i = 0; i < modescount; i++) { int otherW, otherH, otherpixelW, otherpixelH, otherrefresh; Uint32 otherformat; bool otherGUI; - CGDisplayModeRef othermode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modelist, i); + CGDisplayModeRef othermode = (CGDisplayModeRef) CFArrayGetValueAtIndex(modelist, i); uint32_t otherioflags = CGDisplayModeGetIOFlags(othermode); if (CFEqual(vidmode, othermode)) { @@ -193,10 +199,10 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode continue; } - otherW = (int)CGDisplayModeGetWidth(othermode); - otherH = (int)CGDisplayModeGetHeight(othermode); - otherpixelW = (int)CGDisplayModeGetPixelWidth(othermode); - otherpixelH = (int)CGDisplayModeGetPixelHeight(othermode); + otherW = (int) CGDisplayModeGetWidth(othermode); + otherH = (int) CGDisplayModeGetHeight(othermode); + otherpixelW = (int) CGDisplayModeGetPixelWidth(othermode); + otherpixelH = (int) CGDisplayModeGetPixelHeight(othermode); otherrefresh = GetDisplayModeRefreshRate(othermode, link); otherformat = GetDisplayModePixelFormat(othermode); otherGUI = CGDisplayModeIsUsableForDesktopGUI(othermode); @@ -204,7 +210,10 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode /* Ignore this mode if it's low-dpi (@1x) and we have a high-dpi * mode in the list with the same size in points. */ - if (width == pixelW && height == pixelH && width == otherW && height == otherH && refreshrate == otherrefresh && format == otherformat && (otherpixelW != otherW || otherpixelH != otherH)) { + if (width == pixelW && height == pixelH + && width == otherW && height == otherH + && refreshrate == otherrefresh && format == otherformat + && (otherpixelW != otherW || otherpixelH != otherH)) { CFRelease(modes); return SDL_FALSE; } @@ -212,7 +221,10 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode /* Ignore this mode if it's interlaced and there's a non-interlaced * mode in the list with the same properties. */ - if (interlaced && ((otherioflags & kDisplayModeInterlacedFlag) == 0) && width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && refreshrate == otherrefresh && format == otherformat && usableForGUI == otherGUI) { + if (interlaced && ((otherioflags & kDisplayModeInterlacedFlag) == 0) + && width == otherW && height == otherH && pixelW == otherpixelW + && pixelH == otherpixelH && refreshrate == otherrefresh + && format == otherformat && usableForGUI == otherGUI) { CFRelease(modes); return SDL_FALSE; } @@ -220,7 +232,9 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode /* Ignore this mode if it's not usable for desktop UI and its * properties are equal to another GUI-capable mode in the list. */ - if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && !usableForGUI && otherGUI && refreshrate == otherrefresh && format == otherformat) { + if (width == otherW && height == otherH && pixelW == otherpixelW + && pixelH == otherpixelH && !usableForGUI && otherGUI + && refreshrate == otherrefresh && format == otherformat) { CFRelease(modes); return SDL_FALSE; } @@ -246,14 +260,16 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode * correct but it being filtered out by SDL_AddDisplayMode as being * a duplicate. */ - if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && usableForGUI == otherGUI && refreshrate == otherrefresh && format == otherformat) { + if (width == otherW && height == otherH && pixelW == otherpixelW + && pixelH == otherpixelH && usableForGUI == otherGUI + && refreshrate == otherrefresh && format == otherformat) { CFArrayAppendValue(modes, othermode); } } } #endif - data = (SDL_DisplayModeData *)SDL_malloc(sizeof(*data)); + data = (SDL_DisplayModeData *) SDL_malloc(sizeof(*data)); if (!data) { CFRelease(modes); return SDL_FALSE; @@ -267,13 +283,14 @@ static SDL_bool GetDisplayMode(_THIS, CGDisplayModeRef vidmode, SDL_bool vidmode return SDL_TRUE; } -static const char *Cocoa_GetDisplayName(CGDirectDisplayID displayID) +static const char * +Cocoa_GetDisplayName(CGDirectDisplayID displayID) { /* This API is deprecated in 10.9 with no good replacement (as of 10.15). */ io_service_t servicePort = CGDisplayIOServicePort(displayID); CFDictionaryRef deviceInfo = IODisplayCreateInfoDictionary(servicePort, kIODisplayOnlyPreferredName); NSDictionary *localizedNames = [(__bridge NSDictionary *)deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]]; - const char *displayName = NULL; + const char* displayName = NULL; if ([localizedNames count] > 0) { displayName = SDL_strdup([[localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]] UTF8String]); @@ -282,94 +299,95 @@ static const char *Cocoa_GetDisplayName(CGDirectDisplayID displayID) return displayName; } -void Cocoa_InitModes(_THIS) +void +Cocoa_InitModes(_THIS) +{ @autoreleasepool { - @autoreleasepool { - CGDisplayErr result; - CGDirectDisplayID *displays; - CGDisplayCount numDisplays; - SDL_bool isstack; - int pass, i; + CGDisplayErr result; + CGDirectDisplayID *displays; + CGDisplayCount numDisplays; + SDL_bool isstack; + int pass, i; - result = CGGetOnlineDisplayList(0, NULL, &numDisplays); - if (result != kCGErrorSuccess) { - CG_SetError("CGGetOnlineDisplayList()", result); - return; - } - displays = SDL_small_alloc(CGDirectDisplayID, numDisplays, &isstack); - result = CGGetOnlineDisplayList(numDisplays, displays, &numDisplays); - if (result != kCGErrorSuccess) { - CG_SetError("CGGetOnlineDisplayList()", result); - SDL_small_free(displays, isstack); - return; - } + result = CGGetOnlineDisplayList(0, NULL, &numDisplays); + if (result != kCGErrorSuccess) { + CG_SetError("CGGetOnlineDisplayList()", result); + return; + } + displays = SDL_small_alloc(CGDirectDisplayID, numDisplays, &isstack); + result = CGGetOnlineDisplayList(numDisplays, displays, &numDisplays); + if (result != kCGErrorSuccess) { + CG_SetError("CGGetOnlineDisplayList()", result); + SDL_small_free(displays, isstack); + return; + } - /* Pick up the primary display in the first pass, then get the rest */ - for (pass = 0; pass < 2; ++pass) { - for (i = 0; i < numDisplays; ++i) { - SDL_VideoDisplay display; - SDL_DisplayData *displaydata; - SDL_DisplayMode mode; - CGDisplayModeRef moderef = NULL; - CVDisplayLinkRef link = NULL; + /* Pick up the primary display in the first pass, then get the rest */ + for (pass = 0; pass < 2; ++pass) { + for (i = 0; i < numDisplays; ++i) { + SDL_VideoDisplay display; + SDL_DisplayData *displaydata; + SDL_DisplayMode mode; + CGDisplayModeRef moderef = NULL; + CVDisplayLinkRef link = NULL; - if (pass == 0) { - if (!CGDisplayIsMain(displays[i])) { - continue; - } - } else { - if (CGDisplayIsMain(displays[i])) { - continue; - } - } - - if (CGDisplayMirrorsDisplay(displays[i]) != kCGNullDirectDisplay) { + if (pass == 0) { + if (!CGDisplayIsMain(displays[i])) { continue; } - - moderef = CGDisplayCopyDisplayMode(displays[i]); - - if (!moderef) { + } else { + if (CGDisplayIsMain(displays[i])) { continue; } + } - displaydata = (SDL_DisplayData *)SDL_malloc(sizeof(*displaydata)); - if (!displaydata) { - CGDisplayModeRelease(moderef); - continue; - } - displaydata->display = displays[i]; + if (CGDisplayMirrorsDisplay(displays[i]) != kCGNullDirectDisplay) { + continue; + } - CVDisplayLinkCreateWithCGDisplay(displays[i], &link); + moderef = CGDisplayCopyDisplayMode(displays[i]); - SDL_zero(display); - /* this returns a stddup'ed string */ - display.name = (char *)Cocoa_GetDisplayName(displays[i]); - if (!GetDisplayMode(_this, moderef, SDL_TRUE, NULL, link, &mode)) { - CVDisplayLinkRelease(link); - CGDisplayModeRelease(moderef); - SDL_free(display.name); - SDL_free(displaydata); - continue; - } + if (!moderef) { + continue; + } + displaydata = (SDL_DisplayData *) SDL_malloc(sizeof(*displaydata)); + if (!displaydata) { + CGDisplayModeRelease(moderef); + continue; + } + displaydata->display = displays[i]; + + CVDisplayLinkCreateWithCGDisplay(displays[i], &link); + + SDL_zero(display); + /* this returns a stddup'ed string */ + display.name = (char *)Cocoa_GetDisplayName(displays[i]); + if (!GetDisplayMode(_this, moderef, SDL_TRUE, NULL, link, &mode)) { CVDisplayLinkRelease(link); CGDisplayModeRelease(moderef); - - display.desktop_mode = mode; - display.current_mode = mode; - display.driverdata = displaydata; - SDL_AddVideoDisplay(&display, SDL_FALSE); SDL_free(display.name); + SDL_free(displaydata); + continue; } - } - SDL_small_free(displays, isstack); - } -} -int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect) + CVDisplayLinkRelease(link); + CGDisplayModeRelease(moderef); + + display.desktop_mode = mode; + display.current_mode = mode; + display.driverdata = displaydata; + SDL_AddVideoDisplay(&display, SDL_FALSE); + SDL_free(display.name); + } + } + SDL_small_free(displays, isstack); +}} + +int +Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { - SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata; + SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; CGRect cgrect; cgrect = CGDisplayBounds(displaydata->display); @@ -380,23 +398,24 @@ int Cocoa_GetDisplayBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect) return 0; } -int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect) +int +Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { - SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata; + SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; const CGDirectDisplayID cgdisplay = displaydata->display; NSArray *screens = [NSScreen screens]; NSScreen *screen = nil; /* !!! FIXME: maybe track the NSScreen in SDL_DisplayData? */ for (NSScreen *i in screens) { - const CGDirectDisplayID thisDisplay = (CGDirectDisplayID)[[[i deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; + const CGDirectDisplayID thisDisplay = (CGDirectDisplayID) [[[i deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; if (thisDisplay == cgdisplay) { screen = i; break; } } - SDL_assert(screen != nil); /* didn't find it?! */ + SDL_assert(screen != nil); /* didn't find it?! */ if (screen == nil) { return -1; } @@ -412,88 +431,89 @@ int Cocoa_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rec return 0; } -int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi) +int +Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi) +{ @autoreleasepool { - @autoreleasepool { - const float MM_IN_INCH = 25.4f; + const float MM_IN_INCH = 25.4f; - SDL_DisplayData *data = (SDL_DisplayData *)display->driverdata; + SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata; - /* we need the backingScaleFactor for Retina displays, which is only exposed through NSScreen, not CGDisplay, afaik, so find our screen... */ - CGFloat scaleFactor = 1.0f; - NSArray *screens = [NSScreen screens]; - NSSize displayNativeSize; - displayNativeSize.width = (int)CGDisplayPixelsWide(data->display); - displayNativeSize.height = (int)CGDisplayPixelsHigh(data->display); - - for (NSScreen *screen in screens) { - const CGDirectDisplayID dpyid = (const CGDirectDisplayID)[[[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; - if (dpyid == data->display) { + /* we need the backingScaleFactor for Retina displays, which is only exposed through NSScreen, not CGDisplay, afaik, so find our screen... */ + CGFloat scaleFactor = 1.0f; + NSArray *screens = [NSScreen screens]; + NSSize displayNativeSize; + displayNativeSize.width = (int) CGDisplayPixelsWide(data->display); + displayNativeSize.height = (int) CGDisplayPixelsHigh(data->display); + + for (NSScreen *screen in screens) { + const CGDirectDisplayID dpyid = (const CGDirectDisplayID ) [[[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; + if (dpyid == data->display) { #ifdef MAC_OS_X_VERSION_10_8 - /* Neither CGDisplayScreenSize(description's NSScreenNumber) nor [NSScreen backingScaleFactor] can calculate the correct dpi in macOS. E.g. backingScaleFactor is always 2 in all display modes for rMBP 16" */ - if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) { - CFStringRef dmKeys[1] = { kCGDisplayShowDuplicateLowResolutionModes }; - CFBooleanRef dmValues[1] = { kCFBooleanTrue }; - CFDictionaryRef dmOptions = CFDictionaryCreate(kCFAllocatorDefault, (const void **)dmKeys, (const void **)dmValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFArrayRef allDisplayModes = CGDisplayCopyAllDisplayModes(dpyid, dmOptions); - CFIndex n = CFArrayGetCount(allDisplayModes); - for (CFIndex i = 0; i < n; ++i) { - CGDisplayModeRef m = (CGDisplayModeRef)CFArrayGetValueAtIndex(allDisplayModes, i); - CGFloat width = CGDisplayModeGetPixelWidth(m); - CGFloat height = CGDisplayModeGetPixelHeight(m); - CGFloat HiDPIWidth = CGDisplayModeGetWidth(m); - - // Only check 1x mode - if (width == HiDPIWidth) { - if (CGDisplayModeGetIOFlags(m) & kDisplayModeNativeFlag) { - displayNativeSize.width = width; - displayNativeSize.height = height; - break; - } - - // Get the largest size even if kDisplayModeNativeFlag is not present e.g. iMac 27-Inch with 5K Retina - if (width > displayNativeSize.width) { - displayNativeSize.width = width; - displayNativeSize.height = height; - } + /* Neither CGDisplayScreenSize(description's NSScreenNumber) nor [NSScreen backingScaleFactor] can calculate the correct dpi in macOS. E.g. backingScaleFactor is always 2 in all display modes for rMBP 16" */ + if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) { + CFStringRef dmKeys[1] = { kCGDisplayShowDuplicateLowResolutionModes }; + CFBooleanRef dmValues[1] = { kCFBooleanTrue }; + CFDictionaryRef dmOptions = CFDictionaryCreate(kCFAllocatorDefault, (const void**) dmKeys, (const void**) dmValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks ); + CFArrayRef allDisplayModes = CGDisplayCopyAllDisplayModes(dpyid, dmOptions); + CFIndex n = CFArrayGetCount(allDisplayModes); + for(CFIndex i = 0; i < n; ++i) { + CGDisplayModeRef m = (CGDisplayModeRef)CFArrayGetValueAtIndex(allDisplayModes, i); + CGFloat width = CGDisplayModeGetPixelWidth(m); + CGFloat height = CGDisplayModeGetPixelHeight(m); + CGFloat HiDPIWidth = CGDisplayModeGetWidth(m); + + //Only check 1x mode + if(width == HiDPIWidth) { + if (CGDisplayModeGetIOFlags(m) & kDisplayModeNativeFlag) { + displayNativeSize.width = width; + displayNativeSize.height = height; + break; + } + + //Get the largest size even if kDisplayModeNativeFlag is not present e.g. iMac 27-Inch with 5K Retina + if(width > displayNativeSize.width) { + displayNativeSize.width = width; + displayNativeSize.height = height; } } - CFRelease(allDisplayModes); - CFRelease(dmOptions); - } else -#endif - { - // fallback for 10.7 - scaleFactor = [screen backingScaleFactor]; - displayNativeSize.width = displayNativeSize.width * scaleFactor; - displayNativeSize.height = displayNativeSize.height * scaleFactor; - break; } + CFRelease(allDisplayModes); + CFRelease(dmOptions); + } else +#endif + { + // fallback for 10.7 + scaleFactor = [screen backingScaleFactor]; + displayNativeSize.width = displayNativeSize.width * scaleFactor; + displayNativeSize.height = displayNativeSize.height * scaleFactor; + break; } } - - { - const CGSize displaySize = CGDisplayScreenSize(data->display); - const int pixelWidth = displayNativeSize.width; - const int pixelHeight = displayNativeSize.height; - - if (ddpi) { - *ddpi = (SDL_ComputeDiagonalDPI(pixelWidth, pixelHeight, displaySize.width / MM_IN_INCH, displaySize.height / MM_IN_INCH)); - } - if (hdpi) { - *hdpi = (pixelWidth * MM_IN_INCH / displaySize.width); - } - if (vdpi) { - *vdpi = (pixelHeight * MM_IN_INCH / displaySize.height); - } - } - return 0; } -} -void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display) + { + const CGSize displaySize = CGDisplayScreenSize(data->display); + const int pixelWidth = displayNativeSize.width; + const int pixelHeight = displayNativeSize.height; + + if (ddpi) { + *ddpi = (SDL_ComputeDiagonalDPI(pixelWidth, pixelHeight, displaySize.width / MM_IN_INCH, displaySize.height / MM_IN_INCH)); + } + if (hdpi) { + *hdpi = (pixelWidth * MM_IN_INCH / displaySize.width); + } + if (vdpi) { + *vdpi = (pixelHeight * MM_IN_INCH / displaySize.height); + } + } + return 0; +}} + +void +Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { - SDL_DisplayData *data = (SDL_DisplayData *)display->driverdata; + SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata; CVDisplayLinkRef link = NULL; CGDisplayModeRef desktopmoderef; SDL_DisplayMode desktopmode; @@ -512,7 +532,7 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display) */ if (desktopmoderef && GetDisplayMode(_this, desktopmoderef, SDL_TRUE, NULL, link, &desktopmode)) { if (!SDL_AddDisplayMode(display, &desktopmode)) { - CFRelease(((SDL_DisplayModeData *)desktopmode.driverdata)->modes); + CFRelease(((SDL_DisplayModeData*)desktopmode.driverdata)->modes); SDL_free(desktopmode.driverdata); } } @@ -532,8 +552,8 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display) */ #ifdef MAC_OS_X_VERSION_10_8 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) { - const CFStringRef dictkeys[] = { kCGDisplayShowDuplicateLowResolutionModes }; - const CFBooleanRef dictvalues[] = { kCFBooleanTrue }; + const CFStringRef dictkeys[] = {kCGDisplayShowDuplicateLowResolutionModes}; + const CFBooleanRef dictvalues[] = {kCFBooleanTrue}; dict = CFDictionaryCreate(NULL, (const void **)dictkeys, (const void **)dictvalues, @@ -554,12 +574,12 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display) const CFIndex count = CFArrayGetCount(modes); for (i = 0; i < count; i++) { - CGDisplayModeRef moderef = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i); + CGDisplayModeRef moderef = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i); SDL_DisplayMode mode; if (GetDisplayMode(_this, moderef, SDL_FALSE, modes, link, &mode)) { if (!SDL_AddDisplayMode(display, &mode)) { - CFRelease(((SDL_DisplayModeData *)mode.driverdata)->modes); + CFRelease(((SDL_DisplayModeData*)mode.driverdata)->modes); SDL_free(mode.driverdata); } } @@ -571,7 +591,8 @@ void Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay *display) CVDisplayLinkRelease(link); } -static CGError SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayModeData *data) +static CGError +SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayModeData *data) { /* SDL_DisplayModeData can contain multiple CGDisplayModes to try (with * identical properties), some of which might not work. See GetDisplayMode. @@ -589,10 +610,11 @@ static CGError SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayMo return result; } -int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode) +int +Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { - SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata; - SDL_DisplayModeData *data = (SDL_DisplayModeData *)mode->driverdata; + SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata; + SDL_DisplayModeData *data = (SDL_DisplayModeData *) mode->driverdata; CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken; CGError result; @@ -624,7 +646,7 @@ int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode } /* Do the physical switch */ - result = SetDisplayModeForDisplay(displaydata->display, data); + result = SetDisplayModeForDisplay(displaydata->display, data); if (result != kCGErrorSuccess) { CG_SetError("CGDisplaySwitchToMode()", result); goto ERR_NO_SWITCH; @@ -648,13 +670,14 @@ ERR_NO_SWITCH: } ERR_NO_CAPTURE: if (fade_token != kCGDisplayFadeReservationInvalidToken) { - CGDisplayFade(fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); + CGDisplayFade (fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE); CGReleaseDisplayFadeReservation(fade_token); } return -1; } -void Cocoa_QuitModes(_THIS) +void +Cocoa_QuitModes(_THIS) { int i, j; @@ -666,11 +689,11 @@ void Cocoa_QuitModes(_THIS) Cocoa_SetDisplayMode(_this, display, &display->desktop_mode); } - mode = (SDL_DisplayModeData *)display->desktop_mode.driverdata; + mode = (SDL_DisplayModeData *) display->desktop_mode.driverdata; CFRelease(mode->modes); for (j = 0; j < display->num_display_modes; j++) { - mode = (SDL_DisplayModeData *)display->display_modes[j].driverdata; + mode = (SDL_DisplayModeData*) display->display_modes[j].driverdata; CFRelease(mode->modes); } } diff --git a/src/video/cocoa/SDL_cocoamouse.h b/src/video/cocoa/SDL_cocoamouse.h index c1fab08c6..f6dcdc045 100644 --- a/src/video/cocoa/SDL_cocoamouse.h +++ b/src/video/cocoa/SDL_cocoamouse.h @@ -26,13 +26,12 @@ #include "SDL_cocoavideo.h" extern int Cocoa_InitMouse(_THIS); -extern void Cocoa_HandleMouseEvent(_THIS, NSEvent *event); -extern void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event); +extern void Cocoa_HandleMouseEvent(_THIS, NSEvent * event); +extern void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent * event); extern void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y); extern void Cocoa_QuitMouse(_THIS); -typedef struct -{ +typedef struct { /* Whether we've seen a cursor warp since the last move event. */ SDL_bool seenWarp; /* What location our last cursor warp was to. */ diff --git a/src/video/cocoa/SDL_cocoamouse.m b/src/video/cocoa/SDL_cocoamouse.m index 090f01de3..da5ffac69 100644 --- a/src/video/cocoa/SDL_cocoamouse.m +++ b/src/video/cocoa/SDL_cocoamouse.m @@ -33,9 +33,7 @@ #ifdef DEBUG_COCOAMOUSE #define DLog(fmt, ...) printf("%s: " fmt "\n", __func__, ##__VA_ARGS__) #else -#define DLog(...) \ - do { \ - } while (0) +#define DLog(...) do { } while (0) #endif @implementation NSCursor (InvisibleCursor) @@ -64,52 +62,54 @@ } @end -static SDL_Cursor *Cocoa_CreateDefaultCursor() + +static SDL_Cursor * +Cocoa_CreateDefaultCursor() +{ @autoreleasepool { - @autoreleasepool { - NSCursor *nscursor; - SDL_Cursor *cursor = NULL; + NSCursor *nscursor; + SDL_Cursor *cursor = NULL; - nscursor = [NSCursor arrowCursor]; + nscursor = [NSCursor arrowCursor]; - if (nscursor) { - cursor = SDL_calloc(1, sizeof(*cursor)); - if (cursor) { - cursor->driverdata = (void *)CFBridgingRetain(nscursor); - } + if (nscursor) { + cursor = SDL_calloc(1, sizeof(*cursor)); + if (cursor) { + cursor->driverdata = (void *)CFBridgingRetain(nscursor); } - - return cursor; } -} -static SDL_Cursor *Cocoa_CreateCursor(SDL_Surface *surface, int hot_x, int hot_y) + return cursor; +}} + +static SDL_Cursor * +Cocoa_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y) +{ @autoreleasepool { - @autoreleasepool { - NSImage *nsimage; - NSCursor *nscursor = NULL; - SDL_Cursor *cursor = NULL; + NSImage *nsimage; + NSCursor *nscursor = NULL; + SDL_Cursor *cursor = NULL; - nsimage = Cocoa_CreateImage(surface); - if (nsimage) { - nscursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(hot_x, hot_y)]; - } - - if (nscursor) { - cursor = SDL_calloc(1, sizeof(*cursor)); - if (cursor) { - cursor->driverdata = (void *)CFBridgingRetain(nscursor); - } - } - - return cursor; + nsimage = Cocoa_CreateImage(surface); + if (nsimage) { + nscursor = [[NSCursor alloc] initWithImage: nsimage hotSpot: NSMakePoint(hot_x, hot_y)]; } -} + + if (nscursor) { + cursor = SDL_calloc(1, sizeof(*cursor)); + if (cursor) { + cursor->driverdata = (void *)CFBridgingRetain(nscursor); + } + } + + return cursor; +}} /* there are .pdf files of some of the cursors we need, installed by default on macOS, but not available through NSCursor. If we can load them ourselves, use them, otherwise fallback to something standard but not super-great. Since these are under /System, they should be available even to sandboxed apps. */ -static NSCursor *LoadHiddenSystemCursor(NSString *cursorName, SEL fallback) +static NSCursor * +LoadHiddenSystemCursor(NSString *cursorName, SEL fallback) { NSString *cursorPath = [@"/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors" stringByAppendingPathComponent:cursorName]; NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:[cursorPath stringByAppendingPathComponent:@"info.plist"]]; @@ -122,12 +122,12 @@ static NSCursor *LoadHiddenSystemCursor(NSString *cursorName, SEL fallback) } if (frames > 1) { -#ifdef MAC_OS_VERSION_12_0 /* same value as deprecated symbol. */ + #ifdef MAC_OS_VERSION_12_0 /* same value as deprecated symbol. */ const NSCompositingOperation operation = NSCompositingOperationCopy; -#else + #else const NSCompositingOperation operation = NSCompositeCopy; -#endif - const NSSize cropped_size = NSMakeSize(image.size.width, (int)(image.size.height / frames)); + #endif + const NSSize cropped_size = NSMakeSize(image.size.width, (int) (image.size.height / frames)); NSImage *cropped = [[NSImage alloc] initWithSize:cropped_size]; if (cropped == nil) { return [NSCursor performSelector:fallback]; @@ -146,92 +146,93 @@ static NSCursor *LoadHiddenSystemCursor(NSString *cursorName, SEL fallback) return cursor; } -static SDL_Cursor *Cocoa_CreateSystemCursor(SDL_SystemCursor id) +static SDL_Cursor * +Cocoa_CreateSystemCursor(SDL_SystemCursor id) +{ @autoreleasepool { - @autoreleasepool { - NSCursor *nscursor = NULL; - SDL_Cursor *cursor = NULL; + NSCursor *nscursor = NULL; + SDL_Cursor *cursor = NULL; - switch (id) { - case SDL_SYSTEM_CURSOR_ARROW: - nscursor = [NSCursor arrowCursor]; - break; - case SDL_SYSTEM_CURSOR_IBEAM: - nscursor = [NSCursor IBeamCursor]; - break; - case SDL_SYSTEM_CURSOR_CROSSHAIR: - nscursor = [NSCursor crosshairCursor]; - break; - case SDL_SYSTEM_CURSOR_WAIT: /* !!! FIXME: this is more like WAITARROW */ - nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor)); - break; - case SDL_SYSTEM_CURSOR_WAITARROW: /* !!! FIXME: this is meant to be animated */ - nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor)); - break; - case SDL_SYSTEM_CURSOR_SIZENWSE: - nscursor = LoadHiddenSystemCursor(@"resizenorthwestsoutheast", @selector(closedHandCursor)); - break; - case SDL_SYSTEM_CURSOR_SIZENESW: - nscursor = LoadHiddenSystemCursor(@"resizenortheastsouthwest", @selector(closedHandCursor)); - break; - case SDL_SYSTEM_CURSOR_SIZEWE: - nscursor = LoadHiddenSystemCursor(@"resizeeastwest", @selector(resizeLeftRightCursor)); - break; - case SDL_SYSTEM_CURSOR_SIZENS: - nscursor = LoadHiddenSystemCursor(@"resizenorthsouth", @selector(resizeUpDownCursor)); - break; - case SDL_SYSTEM_CURSOR_SIZEALL: - nscursor = LoadHiddenSystemCursor(@"move", @selector(closedHandCursor)); - break; - case SDL_SYSTEM_CURSOR_NO: - nscursor = [NSCursor operationNotAllowedCursor]; - break; - case SDL_SYSTEM_CURSOR_HAND: - nscursor = [NSCursor pointingHandCursor]; - break; - default: - SDL_assert(!"Unknown system cursor"); - return NULL; - } - - if (nscursor) { - cursor = SDL_calloc(1, sizeof(*cursor)); - if (cursor) { - /* We'll free it later, so retain it here */ - cursor->driverdata = (void *)CFBridgingRetain(nscursor); - } - } - - return cursor; + switch(id) { + case SDL_SYSTEM_CURSOR_ARROW: + nscursor = [NSCursor arrowCursor]; + break; + case SDL_SYSTEM_CURSOR_IBEAM: + nscursor = [NSCursor IBeamCursor]; + break; + case SDL_SYSTEM_CURSOR_CROSSHAIR: + nscursor = [NSCursor crosshairCursor]; + break; + case SDL_SYSTEM_CURSOR_WAIT: /* !!! FIXME: this is more like WAITARROW */ + nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor)); + break; + case SDL_SYSTEM_CURSOR_WAITARROW: /* !!! FIXME: this is meant to be animated */ + nscursor = LoadHiddenSystemCursor(@"busybutclickable", @selector(arrowCursor)); + break; + case SDL_SYSTEM_CURSOR_SIZENWSE: + nscursor = LoadHiddenSystemCursor(@"resizenorthwestsoutheast", @selector(closedHandCursor)); + break; + case SDL_SYSTEM_CURSOR_SIZENESW: + nscursor = LoadHiddenSystemCursor(@"resizenortheastsouthwest", @selector(closedHandCursor)); + break; + case SDL_SYSTEM_CURSOR_SIZEWE: + nscursor = LoadHiddenSystemCursor(@"resizeeastwest", @selector(resizeLeftRightCursor)); + break; + case SDL_SYSTEM_CURSOR_SIZENS: + nscursor = LoadHiddenSystemCursor(@"resizenorthsouth", @selector(resizeUpDownCursor)); + break; + case SDL_SYSTEM_CURSOR_SIZEALL: + nscursor = LoadHiddenSystemCursor(@"move", @selector(closedHandCursor)); + break; + case SDL_SYSTEM_CURSOR_NO: + nscursor = [NSCursor operationNotAllowedCursor]; + break; + case SDL_SYSTEM_CURSOR_HAND: + nscursor = [NSCursor pointingHandCursor]; + break; + default: + SDL_assert(!"Unknown system cursor"); + return NULL; } -} -static void Cocoa_FreeCursor(SDL_Cursor *cursor) + if (nscursor) { + cursor = SDL_calloc(1, sizeof(*cursor)); + if (cursor) { + /* We'll free it later, so retain it here */ + cursor->driverdata = (void *)CFBridgingRetain(nscursor); + } + } + + return cursor; +}} + +static void +Cocoa_FreeCursor(SDL_Cursor * cursor) +{ @autoreleasepool { - @autoreleasepool { - CFBridgingRelease(cursor->driverdata); - SDL_free(cursor); - } -} + CFBridgingRelease(cursor->driverdata); + SDL_free(cursor); +}} -static int Cocoa_ShowCursor(SDL_Cursor *cursor) +static int +Cocoa_ShowCursor(SDL_Cursor * cursor) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoDevice *device = SDL_GetVideoDevice(); - SDL_Window *window = (device ? device->windows : NULL); - for (; window != NULL; window = window->next) { - SDL_WindowData *driverdata = (__bridge SDL_WindowData *)window->driverdata; - if (driverdata) { - [driverdata.nswindow performSelectorOnMainThread:@selector(invalidateCursorRectsForView:) - withObject:[driverdata.nswindow contentView] - waitUntilDone:NO]; - } + SDL_VideoDevice *device = SDL_GetVideoDevice(); + SDL_Window *window = (device ? device->windows : NULL); + for (; window != NULL; window = window->next) { + SDL_WindowData *driverdata = (__bridge SDL_WindowData *)window->driverdata; + if (driverdata) { + [driverdata.nswindow performSelectorOnMainThread:@selector(invalidateCursorRectsForView:) + withObject:[driverdata.nswindow contentView] + waitUntilDone:NO]; } - return 0; } -} + return 0; +}} -static SDL_Window *SDL_FindWindowAtPoint(const int x, const int y) +static SDL_Window * +SDL_FindWindowAtPoint(const int x, const int y) { const SDL_Point pt = { x, y }; SDL_Window *i; @@ -245,12 +246,13 @@ static SDL_Window *SDL_FindWindowAtPoint(const int x, const int y) return NULL; } -static int Cocoa_WarpMouseGlobal(int x, int y) +static int +Cocoa_WarpMouseGlobal(int x, int y) { CGPoint point; SDL_Mouse *mouse = SDL_GetMouse(); if (mouse->focus) { - SDL_WindowData *data = (__bridge SDL_WindowData *)mouse->focus->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) mouse->focus->driverdata; if ([data.listener isMovingOrFocusClickPending]) { DLog("Postponing warp, window being moved or focused."); [data.listener setPendingMoveX:x Y:y]; @@ -286,12 +288,14 @@ static int Cocoa_WarpMouseGlobal(int x, int y) return 0; } -static void Cocoa_WarpMouse(SDL_Window *window, int x, int y) +static void +Cocoa_WarpMouse(SDL_Window * window, int x, int y) { Cocoa_WarpMouseGlobal(window->x + x, window->y + y); } -static int Cocoa_SetRelativeMouseMode(SDL_bool enabled) +static int +Cocoa_SetRelativeMouseMode(SDL_bool enabled) { CGError result; SDL_Window *window; @@ -318,7 +322,7 @@ static int Cocoa_SetRelativeMouseMode(SDL_bool enabled) /* We will re-apply the non-relative mode when the window finishes being moved, * if it is being moved right now. */ - data = (__bridge SDL_WindowData *)window->driverdata; + data = (__bridge SDL_WindowData *) window->driverdata; if ([data.listener isMovingOrFocusClickPending]) { return 0; } @@ -334,21 +338,23 @@ static int Cocoa_SetRelativeMouseMode(SDL_bool enabled) return 0; } -static int Cocoa_CaptureMouse(SDL_Window *window) +static int +Cocoa_CaptureMouse(SDL_Window *window) { /* our Cocoa event code already tracks the mouse outside the window, so all we have to do here is say "okay" and do what we always do. */ return 0; } -static Uint32 Cocoa_GetGlobalMouseState(int *x, int *y) +static Uint32 +Cocoa_GetGlobalMouseState(int *x, int *y) { const NSUInteger cocoaButtons = [NSEvent pressedMouseButtons]; const NSPoint cocoaLocation = [NSEvent mouseLocation]; Uint32 retval = 0; - *x = (int)cocoaLocation.x; - *y = (int)(CGDisplayPixelsHigh(kCGDirectMainDisplay) - cocoaLocation.y); + *x = (int) cocoaLocation.x; + *y = (int) (CGDisplayPixelsHigh(kCGDirectMainDisplay) - cocoaLocation.y); retval |= (cocoaButtons & (1 << 0)) ? SDL_BUTTON_LMASK : 0; retval |= (cocoaButtons & (1 << 1)) ? SDL_BUTTON_RMASK : 0; @@ -359,11 +365,12 @@ static Uint32 Cocoa_GetGlobalMouseState(int *x, int *y) return retval; } -int Cocoa_InitMouse(_THIS) +int +Cocoa_InitMouse(_THIS) { NSPoint location; SDL_Mouse *mouse = SDL_GetMouse(); - SDL_MouseData *driverdata = (SDL_MouseData *)SDL_calloc(1, sizeof(SDL_MouseData)); + SDL_MouseData *driverdata = (SDL_MouseData*) SDL_calloc(1, sizeof(SDL_MouseData)); if (driverdata == NULL) { return SDL_OutOfMemory(); } @@ -381,13 +388,14 @@ int Cocoa_InitMouse(_THIS) SDL_SetDefaultCursor(Cocoa_CreateDefaultCursor()); - location = [NSEvent mouseLocation]; + location = [NSEvent mouseLocation]; driverdata->lastMoveX = location.x; driverdata->lastMoveY = location.y; return 0; } -static void Cocoa_HandleTitleButtonEvent(_THIS, NSEvent *event) +static void +Cocoa_HandleTitleButtonEvent(_THIS, NSEvent *event) { SDL_Window *window; NSWindow *nswindow = [event window]; @@ -420,7 +428,8 @@ static void Cocoa_HandleTitleButtonEvent(_THIS, NSEvent *event) } } -void Cocoa_HandleMouseEvent(_THIS, NSEvent *event) +void +Cocoa_HandleMouseEvent(_THIS, NSEvent *event) { SDL_Mouse *mouse; SDL_MouseData *driverdata; @@ -430,43 +439,43 @@ void Cocoa_HandleMouseEvent(_THIS, NSEvent *event) float deltaX, deltaY; SDL_bool seenWarp; switch ([event type]) { - case NSEventTypeMouseMoved: - case NSEventTypeLeftMouseDragged: - case NSEventTypeRightMouseDragged: - case NSEventTypeOtherMouseDragged: - break; + case NSEventTypeMouseMoved: + case NSEventTypeLeftMouseDragged: + case NSEventTypeRightMouseDragged: + case NSEventTypeOtherMouseDragged: + break; - case NSEventTypeLeftMouseDown: - case NSEventTypeLeftMouseUp: - case NSEventTypeRightMouseDown: - case NSEventTypeRightMouseUp: - case NSEventTypeOtherMouseDown: - case NSEventTypeOtherMouseUp: - if ([event window]) { - NSRect windowRect = [[[event window] contentView] frame]; - if (!NSMouseInRect([event locationInWindow], windowRect, NO)) { - Cocoa_HandleTitleButtonEvent(_this, event); - return; + case NSEventTypeLeftMouseDown: + case NSEventTypeLeftMouseUp: + case NSEventTypeRightMouseDown: + case NSEventTypeRightMouseUp: + case NSEventTypeOtherMouseDown: + case NSEventTypeOtherMouseUp: + if ([event window]) { + NSRect windowRect = [[[event window] contentView] frame]; + if (!NSMouseInRect([event locationInWindow], windowRect, NO)) { + Cocoa_HandleTitleButtonEvent(_this, event); + return; + } } - } - return; + return; - default: - /* Ignore any other events. */ - return; + default: + /* Ignore any other events. */ + return; } mouse = SDL_GetMouse(); - driverdata = (SDL_MouseData *)mouse->driverdata; + driverdata = (SDL_MouseData*)mouse->driverdata; if (!driverdata) { - return; /* can happen when returning from fullscreen Space on shutdown */ + return; /* can happen when returning from fullscreen Space on shutdown */ } mouseID = mouse ? mouse->mouseID : 0; seenWarp = driverdata->seenWarp; driverdata->seenWarp = NO; - location = [NSEvent mouseLocation]; + location = [NSEvent mouseLocation]; lastMoveX = driverdata->lastMoveX; lastMoveY = driverdata->lastMoveY; driverdata->lastMoveX = location.x; @@ -499,7 +508,8 @@ void Cocoa_HandleMouseEvent(_THIS, NSEvent *event) SDL_SendMouseMotion(mouse->focus, mouseID, 1, (int)deltaX, (int)deltaY); } -void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event) +void +Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event) { SDL_MouseID mouseID; SDL_MouseWheelDirection direction; @@ -536,12 +546,13 @@ void Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event) SDL_SendMouseWheel(window, mouseID, x, y, direction); } -void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y) +void +Cocoa_HandleMouseWarp(CGFloat x, CGFloat y) { /* This makes Cocoa_HandleMouseEvent ignore the delta caused by the warp, * since it gets included in the next movement event. */ - SDL_MouseData *driverdata = (SDL_MouseData *)SDL_GetMouse()->driverdata; + SDL_MouseData *driverdata = (SDL_MouseData*)SDL_GetMouse()->driverdata; driverdata->lastWarpX = x; driverdata->lastWarpY = y; driverdata->seenWarp = SDL_TRUE; @@ -549,7 +560,8 @@ void Cocoa_HandleMouseWarp(CGFloat x, CGFloat y) DLog("(%g, %g)", x, y); } -void Cocoa_QuitMouse(_THIS) +void +Cocoa_QuitMouse(_THIS) { SDL_Mouse *mouse = SDL_GetMouse(); if (mouse) { diff --git a/src/video/cocoa/SDL_cocoaopengl.h b/src/video/cocoa/SDL_cocoaopengl.h index d32c049ac..9330b5744 100644 --- a/src/video/cocoa/SDL_cocoaopengl.h +++ b/src/video/cocoa/SDL_cocoaopengl.h @@ -40,19 +40,14 @@ struct SDL_GLDriverData int initialized; }; -@interface SDLOpenGLContext : NSOpenGLContext -{ +@interface SDLOpenGLContext : NSOpenGLContext { SDL_atomic_t dirty; SDL_Window *window; CVDisplayLinkRef displayLink; - @public - SDL_mutex *swapIntervalMutex; - @public - SDL_cond *swapIntervalCond; - @public - SDL_atomic_t swapIntervalSetting; - @public - SDL_atomic_t swapIntervalsPassed; + @public SDL_mutex *swapIntervalMutex; + @public SDL_cond *swapIntervalCond; + @public SDL_atomic_t swapIntervalSetting; + @public SDL_atomic_t swapIntervalsPassed; } - (id)initWithFormat:(NSOpenGLPixelFormat *)format @@ -61,11 +56,11 @@ struct SDL_GLDriverData - (void)updateIfNeeded; - (void)movedToNewScreen; - (void)setWindow:(SDL_Window *)window; -- (SDL_Window *)window; +- (SDL_Window*)window; - (void)explicitUpdate; - (void)dealloc; -@property(retain, nonatomic) NSOpenGLPixelFormat *openglPixelFormat; // macOS 10.10 has -[NSOpenGLContext pixelFormat] but this handles older OS releases. +@property (retain, nonatomic) NSOpenGLPixelFormat* openglPixelFormat; // macOS 10.10 has -[NSOpenGLContext pixelFormat] but this handles older OS releases. @end @@ -73,12 +68,12 @@ struct SDL_GLDriverData extern int Cocoa_GL_LoadLibrary(_THIS, const char *path); extern void *Cocoa_GL_GetProcAddress(_THIS, const char *proc); extern void Cocoa_GL_UnloadLibrary(_THIS); -extern SDL_GLContext Cocoa_GL_CreateContext(_THIS, SDL_Window *window); -extern int Cocoa_GL_MakeCurrent(_THIS, SDL_Window *window, +extern SDL_GLContext Cocoa_GL_CreateContext(_THIS, SDL_Window * window); +extern int Cocoa_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); extern int Cocoa_GL_SetSwapInterval(_THIS, int interval); extern int Cocoa_GL_GetSwapInterval(_THIS); -extern int Cocoa_GL_SwapWindow(_THIS, SDL_Window *window); +extern int Cocoa_GL_SwapWindow(_THIS, SDL_Window * window); extern void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context); #ifdef __clang__ diff --git a/src/video/cocoa/SDL_cocoaopengl.m b/src/video/cocoa/SDL_cocoaopengl.m index b99aa0e0c..58df449a3 100644 --- a/src/video/cocoa/SDL_cocoaopengl.m +++ b/src/video/cocoa/SDL_cocoaopengl.m @@ -36,7 +36,7 @@ #include "SDL_opengl.h" #include "../../SDL_hints_c.h" -#define DEFAULT_OPENGL "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib" +#define DEFAULT_OPENGL "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib" /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ @@ -56,14 +56,16 @@ static SDL_bool SDL_opengl_async_dispatch = SDL_FALSE; -static void SDLCALL SDL_OpenGLAsyncDispatchChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +static void SDLCALL +SDL_OpenGLAsyncDispatchChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { SDL_opengl_async_dispatch = SDL_GetStringBoolean(hint, SDL_FALSE); } -static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *now, const CVTimeStamp *outputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *displayLinkContext) +static CVReturn +DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext) { - SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)displayLinkContext; + SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *) displayLinkContext; /*printf("DISPLAY LINK! %u\n", (unsigned int) SDL_GetTicks()); */ const int setting = SDL_AtomicGet(&nscontext->swapIntervalSetting); @@ -97,7 +99,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt /* !!! FIXME: check return values. */ CVDisplayLinkCreateWithActiveCGDisplays(&self->displayLink); - CVDisplayLinkSetOutputCallback(self->displayLink, &DisplayLinkCallback, (__bridge void *_Nullable)self); + CVDisplayLinkSetOutputCallback(self->displayLink, &DisplayLinkCallback, (__bridge void * _Nullable) self); CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(self->displayLink, [self CGLContextObj], [format CGLPixelFormatObj]); CVDisplayLinkStart(displayLink); } @@ -144,7 +146,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt /* Make sure to remove us from the old window's context list, or we'll get scheduled updates from it too. */ NSMutableArray *contexts = oldwindowdata.nscontexts; - @synchronized(contexts) { + @synchronized (contexts) { [contexts removeObject:self]; } } @@ -157,7 +159,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt /* Now sign up for scheduled updates for the new window. */ NSMutableArray *contexts = windowdata.nscontexts; - @synchronized(contexts) { + @synchronized (contexts) { [contexts addObject:self]; } @@ -165,9 +167,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt if ([NSThread isMainThread]) { [self setView:contentview]; } else { - dispatch_sync(dispatch_get_main_queue(), ^{ - [self setView:contentview]; - }); + dispatch_sync(dispatch_get_main_queue(), ^{ [self setView:contentview]; }); } if (self == [NSOpenGLContext currentContext]) { [self explicitUpdate]; @@ -185,7 +185,7 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt } } -- (SDL_Window *)window +- (SDL_Window*)window { return self->window; } @@ -196,13 +196,9 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt [super update]; } else { if (SDL_opengl_async_dispatch) { - dispatch_async(dispatch_get_main_queue(), ^{ - [super update]; - }); + dispatch_async(dispatch_get_main_queue(), ^{ [super update]; }); } else { - dispatch_sync(dispatch_get_main_queue(), ^{ - [super update]; - }); + dispatch_sync(dispatch_get_main_queue(), ^{ [super update]; }); } } } @@ -223,7 +219,9 @@ static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeSt @end -int Cocoa_GL_LoadLibrary(_THIS, const char *path) + +int +Cocoa_GL_LoadLibrary(_THIS, const char *path) { /* Load the OpenGL library */ if (path == NULL) { @@ -247,280 +245,280 @@ Cocoa_GL_GetProcAddress(_THIS, const char *proc) return SDL_LoadFunction(_this->gl_config.dll_handle, proc); } -void Cocoa_GL_UnloadLibrary(_THIS) +void +Cocoa_GL_UnloadLibrary(_THIS) { SDL_UnloadObject(_this->gl_config.dll_handle); _this->gl_config.dll_handle = NULL; } SDL_GLContext -Cocoa_GL_CreateContext(_THIS, SDL_Window *window) +Cocoa_GL_CreateContext(_THIS, SDL_Window * window) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); - SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata; - NSOpenGLPixelFormatAttribute attr[32]; - NSOpenGLPixelFormat *fmt; - SDLOpenGLContext *context; - SDL_GLContext sdlcontext; - NSOpenGLContext *share_context = nil; - int i = 0; - const char *glversion; - int glversion_major; - int glversion_minor; - NSOpenGLPixelFormatAttribute profile; - int interval; + SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); + SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata; + NSOpenGLPixelFormatAttribute attr[32]; + NSOpenGLPixelFormat *fmt; + SDLOpenGLContext *context; + SDL_GLContext sdlcontext; + NSOpenGLContext *share_context = nil; + int i = 0; + const char *glversion; + int glversion_major; + int glversion_minor; + NSOpenGLPixelFormatAttribute profile; + int interval; - if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { + if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { #if SDL_VIDEO_OPENGL_EGL - /* Switch to EGL based functions */ - Cocoa_GL_UnloadLibrary(_this); - _this->GL_LoadLibrary = Cocoa_GLES_LoadLibrary; - _this->GL_GetProcAddress = Cocoa_GLES_GetProcAddress; - _this->GL_UnloadLibrary = Cocoa_GLES_UnloadLibrary; - _this->GL_CreateContext = Cocoa_GLES_CreateContext; - _this->GL_MakeCurrent = Cocoa_GLES_MakeCurrent; - _this->GL_SetSwapInterval = Cocoa_GLES_SetSwapInterval; - _this->GL_GetSwapInterval = Cocoa_GLES_GetSwapInterval; - _this->GL_SwapWindow = Cocoa_GLES_SwapWindow; - _this->GL_DeleteContext = Cocoa_GLES_DeleteContext; - - if (Cocoa_GLES_LoadLibrary(_this, NULL) != 0) { - return NULL; - } - return Cocoa_GLES_CreateContext(_this, window); + /* Switch to EGL based functions */ + Cocoa_GL_UnloadLibrary(_this); + _this->GL_LoadLibrary = Cocoa_GLES_LoadLibrary; + _this->GL_GetProcAddress = Cocoa_GLES_GetProcAddress; + _this->GL_UnloadLibrary = Cocoa_GLES_UnloadLibrary; + _this->GL_CreateContext = Cocoa_GLES_CreateContext; + _this->GL_MakeCurrent = Cocoa_GLES_MakeCurrent; + _this->GL_SetSwapInterval = Cocoa_GLES_SetSwapInterval; + _this->GL_GetSwapInterval = Cocoa_GLES_GetSwapInterval; + _this->GL_SwapWindow = Cocoa_GLES_SwapWindow; + _this->GL_DeleteContext = Cocoa_GLES_DeleteContext; + + if (Cocoa_GLES_LoadLibrary(_this, NULL) != 0) { + return NULL; + } + return Cocoa_GLES_CreateContext(_this, window); #else - SDL_SetError("SDL not configured with EGL support"); - return NULL; + SDL_SetError("SDL not configured with EGL support"); + return NULL; #endif + } + + attr[i++] = NSOpenGLPFAAllowOfflineRenderers; + + profile = NSOpenGLProfileVersionLegacy; + if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_CORE) { + profile = NSOpenGLProfileVersion3_2Core; + } + attr[i++] = NSOpenGLPFAOpenGLProfile; + attr[i++] = profile; + + attr[i++] = NSOpenGLPFAColorSize; + attr[i++] = SDL_BYTESPERPIXEL(display->current_mode.format)*8; + + attr[i++] = NSOpenGLPFADepthSize; + attr[i++] = _this->gl_config.depth_size; + + if (_this->gl_config.double_buffer) { + attr[i++] = NSOpenGLPFADoubleBuffer; + } + + if (_this->gl_config.stereo) { + attr[i++] = NSOpenGLPFAStereo; + } + + if (_this->gl_config.stencil_size) { + attr[i++] = NSOpenGLPFAStencilSize; + attr[i++] = _this->gl_config.stencil_size; + } + + if ((_this->gl_config.accum_red_size + + _this->gl_config.accum_green_size + + _this->gl_config.accum_blue_size + + _this->gl_config.accum_alpha_size) > 0) { + attr[i++] = NSOpenGLPFAAccumSize; + attr[i++] = _this->gl_config.accum_red_size + _this->gl_config.accum_green_size + _this->gl_config.accum_blue_size + _this->gl_config.accum_alpha_size; + } + + if (_this->gl_config.multisamplebuffers) { + attr[i++] = NSOpenGLPFASampleBuffers; + attr[i++] = _this->gl_config.multisamplebuffers; + } + + if (_this->gl_config.multisamplesamples) { + attr[i++] = NSOpenGLPFASamples; + attr[i++] = _this->gl_config.multisamplesamples; + attr[i++] = NSOpenGLPFANoRecovery; + } + if (_this->gl_config.floatbuffers) { + attr[i++] = NSOpenGLPFAColorFloat; + } + + if (_this->gl_config.accelerated >= 0) { + if (_this->gl_config.accelerated) { + attr[i++] = NSOpenGLPFAAccelerated; + } else { + attr[i++] = NSOpenGLPFARendererID; + attr[i++] = kCGLRendererGenericFloatID; } + } - attr[i++] = NSOpenGLPFAAllowOfflineRenderers; + attr[i++] = NSOpenGLPFAScreenMask; + attr[i++] = CGDisplayIDToOpenGLDisplayMask(displaydata->display); + attr[i] = 0; - profile = NSOpenGLProfileVersionLegacy; - if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_CORE) { - profile = NSOpenGLProfileVersion3_2Core; - } - attr[i++] = NSOpenGLPFAOpenGLProfile; - attr[i++] = profile; + fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr]; + if (fmt == nil) { + SDL_SetError("Failed creating OpenGL pixel format"); + return NULL; + } - attr[i++] = NSOpenGLPFAColorSize; - attr[i++] = SDL_BYTESPERPIXEL(display->current_mode.format) * 8; + if (_this->gl_config.share_with_current_context) { + share_context = (__bridge NSOpenGLContext*)SDL_GL_GetCurrentContext(); + } - attr[i++] = NSOpenGLPFADepthSize; - attr[i++] = _this->gl_config.depth_size; + context = [[SDLOpenGLContext alloc] initWithFormat:fmt shareContext:share_context]; - if (_this->gl_config.double_buffer) { - attr[i++] = NSOpenGLPFADoubleBuffer; - } + if (context == nil) { + SDL_SetError("Failed creating OpenGL context"); + return NULL; + } - if (_this->gl_config.stereo) { - attr[i++] = NSOpenGLPFAStereo; - } + sdlcontext = (SDL_GLContext)CFBridgingRetain(context); - if (_this->gl_config.stencil_size) { - attr[i++] = NSOpenGLPFAStencilSize; - attr[i++] = _this->gl_config.stencil_size; - } + /* vsync is handled separately by synchronizing with a display link. */ + interval = 0; + [context setValues:&interval forParameter:NSOpenGLCPSwapInterval]; - if ((_this->gl_config.accum_red_size + - _this->gl_config.accum_green_size + - _this->gl_config.accum_blue_size + - _this->gl_config.accum_alpha_size) > 0) { - attr[i++] = NSOpenGLPFAAccumSize; - attr[i++] = _this->gl_config.accum_red_size + _this->gl_config.accum_green_size + _this->gl_config.accum_blue_size + _this->gl_config.accum_alpha_size; - } + if ( Cocoa_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext)context) < 0 ) { + Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); + SDL_SetError("Failed making OpenGL context current"); + return NULL; + } - if (_this->gl_config.multisamplebuffers) { - attr[i++] = NSOpenGLPFASampleBuffers; - attr[i++] = _this->gl_config.multisamplebuffers; - } + if (_this->gl_config.major_version < 3 && + _this->gl_config.profile_mask == 0 && + _this->gl_config.flags == 0) { + /* This is a legacy profile, so to match other backends, we're done. */ + } else { + const GLubyte *(APIENTRY * glGetStringFunc)(GLenum); - if (_this->gl_config.multisamplesamples) { - attr[i++] = NSOpenGLPFASamples; - attr[i++] = _this->gl_config.multisamplesamples; - attr[i++] = NSOpenGLPFANoRecovery; - } - if (_this->gl_config.floatbuffers) { - attr[i++] = NSOpenGLPFAColorFloat; - } - - if (_this->gl_config.accelerated >= 0) { - if (_this->gl_config.accelerated) { - attr[i++] = NSOpenGLPFAAccelerated; - } else { - attr[i++] = NSOpenGLPFARendererID; - attr[i++] = kCGLRendererGenericFloatID; - } - } - - attr[i++] = NSOpenGLPFAScreenMask; - attr[i++] = CGDisplayIDToOpenGLDisplayMask(displaydata->display); - attr[i] = 0; - - fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr]; - if (fmt == nil) { - SDL_SetError("Failed creating OpenGL pixel format"); - return NULL; - } - - if (_this->gl_config.share_with_current_context) { - share_context = (__bridge NSOpenGLContext *)SDL_GL_GetCurrentContext(); - } - - context = [[SDLOpenGLContext alloc] initWithFormat:fmt shareContext:share_context]; - - if (context == nil) { - SDL_SetError("Failed creating OpenGL context"); - return NULL; - } - - sdlcontext = (SDL_GLContext)CFBridgingRetain(context); - - /* vsync is handled separately by synchronizing with a display link. */ - interval = 0; - [context setValues:&interval forParameter:NSOpenGLCPSwapInterval]; - - if (Cocoa_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext)context) < 0) { + glGetStringFunc = (const GLubyte *(APIENTRY *)(GLenum)) SDL_GL_GetProcAddress("glGetString"); + if (!glGetStringFunc) { Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); - SDL_SetError("Failed making OpenGL context current"); + SDL_SetError ("Failed getting OpenGL glGetString entry point"); return NULL; } - if (_this->gl_config.major_version < 3 && - _this->gl_config.profile_mask == 0 && - _this->gl_config.flags == 0) { - /* This is a legacy profile, so to match other backends, we're done. */ - } else { - const GLubyte *(APIENTRY * glGetStringFunc)(GLenum); - - glGetStringFunc = (const GLubyte *(APIENTRY *)(GLenum))SDL_GL_GetProcAddress("glGetString"); - if (!glGetStringFunc) { - Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); - SDL_SetError("Failed getting OpenGL glGetString entry point"); - return NULL; - } - - glversion = (const char *)glGetStringFunc(GL_VERSION); - if (glversion == NULL) { - Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); - SDL_SetError("Failed getting OpenGL context version"); - return NULL; - } - - if (SDL_sscanf(glversion, "%d.%d", &glversion_major, &glversion_minor) != 2) { - Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); - SDL_SetError("Failed parsing OpenGL context version"); - return NULL; - } - - if ((glversion_major < _this->gl_config.major_version) || - ((glversion_major == _this->gl_config.major_version) && (glversion_minor < _this->gl_config.minor_version))) { - Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); - SDL_SetError("Failed creating OpenGL context at version requested"); - return NULL; - } - - /* In the future we'll want to do this, but to match other platforms - we'll leave the OpenGL version the way it is for now - */ - /*_this->gl_config.major_version = glversion_major;*/ - /*_this->gl_config.minor_version = glversion_minor;*/ - } - return sdlcontext; - } -} - -int Cocoa_GL_MakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context) -{ - @autoreleasepool { - if (context) { - SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)context; - if ([nscontext window] != window) { - [nscontext setWindow:window]; - [nscontext updateIfNeeded]; - } - [nscontext makeCurrentContext]; - } else { - [NSOpenGLContext clearCurrentContext]; + glversion = (const char *)glGetStringFunc(GL_VERSION); + if (glversion == NULL) { + Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); + SDL_SetError ("Failed getting OpenGL context version"); + return NULL; } - return 0; - } -} - -int Cocoa_GL_SetSwapInterval(_THIS, int interval) -{ - @autoreleasepool { - SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)SDL_GL_GetCurrentContext(); - int status; - - if (nscontext == nil) { - status = SDL_SetError("No current OpenGL context"); - } else { - SDL_LockMutex(nscontext->swapIntervalMutex); - SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0); - SDL_AtomicSet(&nscontext->swapIntervalSetting, interval); - SDL_UnlockMutex(nscontext->swapIntervalMutex); - status = 0; + if (SDL_sscanf(glversion, "%d.%d", &glversion_major, &glversion_minor) != 2) { + Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); + SDL_SetError ("Failed parsing OpenGL context version"); + return NULL; } - return status; - } -} - -int Cocoa_GL_GetSwapInterval(_THIS) -{ - @autoreleasepool { - SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)SDL_GL_GetCurrentContext(); - return nscontext ? SDL_AtomicGet(&nscontext->swapIntervalSetting) : 0; - } -} - -int Cocoa_GL_SwapWindow(_THIS, SDL_Window *window) -{ - @autoreleasepool { - SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)SDL_GL_GetCurrentContext(); - SDL_VideoData *videodata = (__bridge SDL_VideoData *)_this->driverdata; - const int setting = SDL_AtomicGet(&nscontext->swapIntervalSetting); - - if (setting == 0) { - /* nothing to do if vsync is disabled, don't even lock */ - } else if (setting < 0) { /* late swap tearing */ - SDL_LockMutex(nscontext->swapIntervalMutex); - while (SDL_AtomicGet(&nscontext->swapIntervalsPassed) == 0) { - SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex); - } - SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0); - SDL_UnlockMutex(nscontext->swapIntervalMutex); - } else { - SDL_LockMutex(nscontext->swapIntervalMutex); - do { /* always wait here so we know we just hit a swap interval. */ - SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex); - } while ((SDL_AtomicGet(&nscontext->swapIntervalsPassed) % setting) != 0); - SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0); - SDL_UnlockMutex(nscontext->swapIntervalMutex); + if ((glversion_major < _this->gl_config.major_version) || + ((glversion_major == _this->gl_config.major_version) && (glversion_minor < _this->gl_config.minor_version))) { + Cocoa_GL_DeleteContext(_this, (__bridge SDL_GLContext)context); + SDL_SetError ("Failed creating OpenGL context at version requested"); + return NULL; } - /*{ static Uint64 prev = 0; const Uint64 now = SDL_GetTicks64(); const unsigned int diff = (unsigned int) (now - prev); prev = now; printf("GLSWAPBUFFERS TICKS %u\n", diff); }*/ - - /* on 10.14 ("Mojave") and later, this deadlocks if two contexts in two - threads try to swap at the same time, so put a mutex around it. */ - SDL_LockMutex(videodata.swaplock); - [nscontext flushBuffer]; - [nscontext updateIfNeeded]; - SDL_UnlockMutex(videodata.swaplock); - return 0; + /* In the future we'll want to do this, but to match other platforms + we'll leave the OpenGL version the way it is for now + */ + /*_this->gl_config.major_version = glversion_major;*/ + /*_this->gl_config.minor_version = glversion_minor;*/ } -} + return sdlcontext; +}} -void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context) +int +Cocoa_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) +{ @autoreleasepool { - @autoreleasepool { - SDLOpenGLContext *nscontext = (SDLOpenGLContext *)CFBridgingRelease(context); - [nscontext setWindow:NULL]; + if (context) { + SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)context; + if ([nscontext window] != window) { + [nscontext setWindow:window]; + [nscontext updateIfNeeded]; + } + [nscontext makeCurrentContext]; + } else { + [NSOpenGLContext clearCurrentContext]; } -} + + return 0; +}} + +int +Cocoa_GL_SetSwapInterval(_THIS, int interval) +{ @autoreleasepool +{ + SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *) SDL_GL_GetCurrentContext(); + int status; + + if (nscontext == nil) { + status = SDL_SetError("No current OpenGL context"); + } else { + SDL_LockMutex(nscontext->swapIntervalMutex); + SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0); + SDL_AtomicSet(&nscontext->swapIntervalSetting, interval); + SDL_UnlockMutex(nscontext->swapIntervalMutex); + status = 0; + } + + return status; +}} + +int +Cocoa_GL_GetSwapInterval(_THIS) +{ @autoreleasepool +{ + SDLOpenGLContext* nscontext = (__bridge SDLOpenGLContext*)SDL_GL_GetCurrentContext(); + return nscontext ? SDL_AtomicGet(&nscontext->swapIntervalSetting) : 0; +}} + +int +Cocoa_GL_SwapWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDLOpenGLContext* nscontext = (__bridge SDLOpenGLContext*)SDL_GL_GetCurrentContext(); + SDL_VideoData *videodata = (__bridge SDL_VideoData *) _this->driverdata; + const int setting = SDL_AtomicGet(&nscontext->swapIntervalSetting); + + if (setting == 0) { + /* nothing to do if vsync is disabled, don't even lock */ + } else if (setting < 0) { /* late swap tearing */ + SDL_LockMutex(nscontext->swapIntervalMutex); + while (SDL_AtomicGet(&nscontext->swapIntervalsPassed) == 0) { + SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex); + } + SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0); + SDL_UnlockMutex(nscontext->swapIntervalMutex); + } else { + SDL_LockMutex(nscontext->swapIntervalMutex); + do { /* always wait here so we know we just hit a swap interval. */ + SDL_CondWait(nscontext->swapIntervalCond, nscontext->swapIntervalMutex); + } while ((SDL_AtomicGet(&nscontext->swapIntervalsPassed) % setting) != 0); + SDL_AtomicSet(&nscontext->swapIntervalsPassed, 0); + SDL_UnlockMutex(nscontext->swapIntervalMutex); + } + + /*{ static Uint64 prev = 0; const Uint64 now = SDL_GetTicks64(); const unsigned int diff = (unsigned int) (now - prev); prev = now; printf("GLSWAPBUFFERS TICKS %u\n", diff); }*/ + + /* on 10.14 ("Mojave") and later, this deadlocks if two contexts in two + threads try to swap at the same time, so put a mutex around it. */ + SDL_LockMutex(videodata.swaplock); + [nscontext flushBuffer]; + [nscontext updateIfNeeded]; + SDL_UnlockMutex(videodata.swaplock); + return 0; +}} + +void +Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context) +{ @autoreleasepool +{ + SDLOpenGLContext *nscontext = (SDLOpenGLContext *)CFBridgingRelease(context); + [nscontext setWindow:NULL]; +}} /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ #ifdef __clang__ diff --git a/src/video/cocoa/SDL_cocoaopengles.m b/src/video/cocoa/SDL_cocoaopengles.m index 9b6d21088..bdf2e9a08 100644 --- a/src/video/cocoa/SDL_cocoaopengles.m +++ b/src/video/cocoa/SDL_cocoaopengles.m @@ -28,7 +28,8 @@ /* EGL implementation of SDL OpenGL support */ -int Cocoa_GLES_LoadLibrary(_THIS, const char *path) +int +Cocoa_GLES_LoadLibrary(_THIS, const char *path) { /* If the profile requested is not GL ES, switch over to WIN_GL functions */ if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) { @@ -48,7 +49,7 @@ int Cocoa_GLES_LoadLibrary(_THIS, const char *path) return SDL_SetError("SDL not configured with OpenGL/CGL support"); #endif } - + if (_this->egl_data == NULL) { return SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0); } @@ -57,11 +58,11 @@ int Cocoa_GLES_LoadLibrary(_THIS, const char *path) } SDL_GLContext -Cocoa_GLES_CreateContext(_THIS, SDL_Window *window) +Cocoa_GLES_CreateContext(_THIS, SDL_Window * window) +{ @autoreleasepool { - @autoreleasepool { - SDL_GLContext context; - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_GLContext context; + SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; #if SDL_VIDEO_OPENGL_CGL if (_this->gl_config.profile_mask != SDL_GL_CONTEXT_PROFILE_ES) { @@ -77,12 +78,12 @@ Cocoa_GLES_CreateContext(_THIS, SDL_Window *window) _this->GL_SwapWindow = Cocoa_GL_SwapWindow; _this->GL_DeleteContext = Cocoa_GL_DeleteContext; - if (Cocoa_GL_LoadLibrary(_this, NULL) != 0) { - return NULL; - } - - return Cocoa_GL_CreateContext(_this, window); + if (Cocoa_GL_LoadLibrary(_this, NULL) != 0) { + return NULL; } + + return Cocoa_GL_CreateContext(_this, window); + } #endif context = SDL_EGL_CreateContext(_this, data.egl_surface); @@ -114,18 +115,12 @@ Cocoa_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) int Cocoa_GLES_SetupWindow(_THIS, SDL_Window * window) { - @autoreleasepool { - SDL_EGL_DeleteContext(_this, context); - Cocoa_GLES_UnloadLibrary(_this); - } -} + NSView* v; + /* The current context is lost in here; save it and reset it. */ + SDL_WindowData *windowdata = (__bridge SDL_WindowData *) window->driverdata; + SDL_Window *current_win = SDL_GL_GetCurrentWindow(); + SDL_GLContext current_ctx = SDL_GL_GetCurrentContext(); -int Cocoa_GLES_SwapWindow(_THIS, SDL_Window *window) -{ - @autoreleasepool { - return SDL_EGL_SwapBuffers(_this, ((__bridge SDL_WindowData *)window->driverdata).egl_surface); - } -} if (_this->egl_data == NULL) { /* !!! FIXME: commenting out this assertion is (I think) incorrect; figure out why driver_loaded is wrong for ANGLE instead. --ryan. */ @@ -136,12 +131,16 @@ int Cocoa_GLES_SwapWindow(_THIS, SDL_Window *window) SDL_EGL_UnloadLibrary(_this); return -1; } - - if (h) { - *h = height; - } + _this->gl_config.driver_loaded = 1; + } + + /* Create the GLES window surface */ + v = windowdata.nswindow.contentView; + windowdata.egl_surface = SDL_EGL_CreateSurface(_this, (__bridge NativeWindowType)[v layer]); + + if (windowdata.egl_surface == EGL_NO_SURFACE) { + return SDL_SetError("Could not create GLES window surface"); } -} return Cocoa_GLES_MakeCurrent(_this, current_win, current_ctx); } diff --git a/src/video/cocoa/SDL_cocoashape.h b/src/video/cocoa/SDL_cocoashape.h index 93957c522..358d878ef 100644 --- a/src/video/cocoa/SDL_cocoashape.h +++ b/src/video/cocoa/SDL_cocoashape.h @@ -30,13 +30,13 @@ #include "../SDL_shape_internals.h" @interface SDL_ShapeData : NSObject -@property(nonatomic) NSGraphicsContext *context; -@property(nonatomic) SDL_bool saved; -@property(nonatomic) SDL_ShapeTree *shape; + @property (nonatomic) NSGraphicsContext* context; + @property (nonatomic) SDL_bool saved; + @property (nonatomic) SDL_ShapeTree* shape; @end -extern SDL_WindowShaper *Cocoa_CreateShaper(SDL_Window *window); -extern int Cocoa_SetWindowShape(SDL_WindowShaper *shaper, SDL_Surface *shape, SDL_WindowShapeMode *shape_mode); +extern SDL_WindowShaper* Cocoa_CreateShaper(SDL_Window* window); +extern int Cocoa_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode); extern int Cocoa_ResizeWindowShape(SDL_Window *window); #endif /* SDL_cocoashape_h_ */ diff --git a/src/video/cocoa/SDL_cocoashape.m b/src/video/cocoa/SDL_cocoashape.m index 0d85f4fd9..ac3459c56 100644 --- a/src/video/cocoa/SDL_cocoashape.m +++ b/src/video/cocoa/SDL_cocoashape.m @@ -31,101 +31,100 @@ @end @interface SDL_CocoaClosure : NSObject -@property(nonatomic) NSView *view; -@property(nonatomic) NSBezierPath *path; -@property(nonatomic) SDL_Window *window; + @property (nonatomic) NSView* view; + @property (nonatomic) NSBezierPath* path; + @property (nonatomic) SDL_Window* window; @end @implementation SDL_CocoaClosure @end -SDL_WindowShaper * -Cocoa_CreateShaper(SDL_Window *window) +SDL_WindowShaper* +Cocoa_CreateShaper(SDL_Window* window) +{ @autoreleasepool { - @autoreleasepool { - SDL_WindowShaper *result; - SDL_ShapeData *data; - int resized_properly; - SDL_WindowData *windata = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowShaper* result; + SDL_ShapeData* data; + int resized_properly; + SDL_WindowData* windata = (__bridge SDL_WindowData*)window->driverdata; - result = (SDL_WindowShaper *)SDL_malloc(sizeof(SDL_WindowShaper)); - if (!result) { - SDL_OutOfMemory(); - return NULL; - } - - [windata.nswindow setOpaque:NO]; - - [windata.nswindow setStyleMask:NSWindowStyleMaskBorderless]; - - result->window = window; - result->mode.mode = ShapeModeDefault; - result->mode.parameters.binarizationCutoff = 1; - result->userx = result->usery = 0; - window->shaper = result; - - data = [[SDL_ShapeData alloc] init]; - data.context = [windata.nswindow graphicsContext]; - data.saved = SDL_FALSE; - data.shape = NULL; - - /* TODO: There's no place to release this... */ - result->driverdata = (void *)CFBridgingRetain(data); - - resized_properly = Cocoa_ResizeWindowShape(window); - SDL_assert(resized_properly == 0); - return result; + result = (SDL_WindowShaper *)SDL_malloc(sizeof(SDL_WindowShaper)); + if (!result) { + SDL_OutOfMemory(); + return NULL; } -} -void ConvertRects(SDL_ShapeTree *tree, void *closure) + [windata.nswindow setOpaque:NO]; + + [windata.nswindow setStyleMask:NSWindowStyleMaskBorderless]; + + result->window = window; + result->mode.mode = ShapeModeDefault; + result->mode.parameters.binarizationCutoff = 1; + result->userx = result->usery = 0; + window->shaper = result; + + data = [[SDL_ShapeData alloc] init]; + data.context = [windata.nswindow graphicsContext]; + data.saved = SDL_FALSE; + data.shape = NULL; + + /* TODO: There's no place to release this... */ + result->driverdata = (void*) CFBridgingRetain(data); + + resized_properly = Cocoa_ResizeWindowShape(window); + SDL_assert(resized_properly == 0); + return result; +}} + +void +ConvertRects(SDL_ShapeTree* tree, void* closure) { - SDL_CocoaClosure *data = (__bridge SDL_CocoaClosure *)closure; - if (tree->kind == OpaqueShape) { + SDL_CocoaClosure* data = (__bridge SDL_CocoaClosure*)closure; + if(tree->kind == OpaqueShape) { NSRect rect = NSMakeRect(tree->data.shape.x, data.window->h - tree->data.shape.y, tree->data.shape.w, tree->data.shape.h); [data.path appendBezierPathWithRect:[data.view convertRect:rect toView:nil]]; } } -int Cocoa_SetWindowShape(SDL_WindowShaper *shaper, SDL_Surface *shape, SDL_WindowShapeMode *shape_mode) +int +Cocoa_SetWindowShape(SDL_WindowShaper *shaper, SDL_Surface *shape, SDL_WindowShapeMode *shape_mode) +{ @autoreleasepool { - @autoreleasepool { - SDL_ShapeData *data = (__bridge SDL_ShapeData *)shaper->driverdata; - SDL_WindowData *windata = (__bridge SDL_WindowData *)shaper->window->driverdata; - SDL_CocoaClosure *closure; - if (data.saved == SDL_TRUE) { - [data.context restoreGraphicsState]; - data.saved = SDL_FALSE; - } - - /*[data.context saveGraphicsState];*/ - /*data.saved = SDL_TRUE;*/ - [NSGraphicsContext setCurrentContext:data.context]; - - [[NSColor clearColor] set]; - NSRectFill([windata.sdlContentView frame]); - data.shape = SDL_CalculateShapeTree(*shape_mode, shape); - - closure = [[SDL_CocoaClosure alloc] init]; - - closure.view = windata.sdlContentView; - closure.path = [NSBezierPath bezierPath]; - closure.window = shaper->window; - SDL_TraverseShapeTree(data.shape, &ConvertRects, (__bridge void *)closure); - [closure.path addClip]; - - return 0; + SDL_ShapeData* data = (__bridge SDL_ShapeData*)shaper->driverdata; + SDL_WindowData* windata = (__bridge SDL_WindowData*)shaper->window->driverdata; + SDL_CocoaClosure* closure; + if(data.saved == SDL_TRUE) { + [data.context restoreGraphicsState]; + data.saved = SDL_FALSE; } -} -int Cocoa_ResizeWindowShape(SDL_Window *window) -{ - @autoreleasepool { - SDL_ShapeData *data = (__bridge SDL_ShapeData *)window->shaper->driverdata; - SDL_assert(data != NULL); - return 0; - } -} + /*[data.context saveGraphicsState];*/ + /*data.saved = SDL_TRUE;*/ + [NSGraphicsContext setCurrentContext:data.context]; + + [[NSColor clearColor] set]; + NSRectFill([windata.sdlContentView frame]); + data.shape = SDL_CalculateShapeTree(*shape_mode, shape); + + closure = [[SDL_CocoaClosure alloc] init]; + + closure.view = windata.sdlContentView; + closure.path = [NSBezierPath bezierPath]; + closure.window = shaper->window; + SDL_TraverseShapeTree(data.shape, &ConvertRects, (__bridge void*)closure); + [closure.path addClip]; + + return 0; +}} + +int +Cocoa_ResizeWindowShape(SDL_Window *window) +{ @autoreleasepool { + SDL_ShapeData* data = (__bridge SDL_ShapeData*)window->shaper->driverdata; + SDL_assert(data != NULL); + return 0; +}} #endif /* SDL_VIDEO_DRIVER_COCOA */ diff --git a/src/video/cocoa/SDL_cocoavideo.h b/src/video/cocoa/SDL_cocoavideo.h index 959fd59c9..8f4a413e9 100644 --- a/src/video/cocoa/SDL_cocoavideo.h +++ b/src/video/cocoa/SDL_cocoavideo.h @@ -98,18 +98,18 @@ DECLARE_ALERT_STYLE(Critical); @class SDLTranslatorResponder; @interface SDL_VideoData : NSObject -@property(nonatomic) int allow_spaces; -@property(nonatomic) int trackpad_is_touch_only; -@property(nonatomic) unsigned int modifierFlags; -@property(nonatomic) void *key_layout; -@property(nonatomic) SDLTranslatorResponder *fieldEdit; -@property(nonatomic) NSInteger clipboard_count; -@property(nonatomic) IOPMAssertionID screensaver_assertion; -@property(nonatomic) SDL_mutex *swaplock; + @property (nonatomic) int allow_spaces; + @property (nonatomic) int trackpad_is_touch_only; + @property (nonatomic) unsigned int modifierFlags; + @property (nonatomic) void *key_layout; + @property (nonatomic) SDLTranslatorResponder *fieldEdit; + @property (nonatomic) NSInteger clipboard_count; + @property (nonatomic) IOPMAssertionID screensaver_assertion; + @property (nonatomic) SDL_mutex *swaplock; @end /* Utility functions */ -extern NSImage *Cocoa_CreateImage(SDL_Surface *surface); +extern NSImage * Cocoa_CreateImage(SDL_Surface * surface); /* Fix build with the 10.11 SDK */ #if MAC_OS_X_VERSION_MAX_ALLOWED < 101200 diff --git a/src/video/cocoa/SDL_cocoavideo.m b/src/video/cocoa/SDL_cocoavideo.m index d4dc7bf5f..6c3d44efa 100644 --- a/src/video/cocoa/SDL_cocoavideo.m +++ b/src/video/cocoa/SDL_cocoavideo.m @@ -44,22 +44,53 @@ static void Cocoa_VideoQuit(_THIS); /* Cocoa driver bootstrap functions */ -static void Cocoa_DeleteDevice(SDL_VideoDevice *device) +static void +Cocoa_DeleteDevice(SDL_VideoDevice * device) +{ @autoreleasepool { - @autoreleasepool { - if (device->wakeup_lock) { - SDL_DestroyMutex(device->wakeup_lock); - } - CFBridgingRelease(device->driverdata); - SDL_free(device); + if (device->wakeup_lock) { + SDL_DestroyMutex(device->wakeup_lock); } -} + CFBridgingRelease(device->driverdata); + SDL_free(device); +}} -static SDL_VideoDevice *Cocoa_CreateDevice(void) +static SDL_VideoDevice * +Cocoa_CreateDevice(void) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoDevice *device; - SDL_VideoData *data; + SDL_VideoDevice *device; + SDL_VideoData *data; + + Cocoa_RegisterApp(); + + /* Initialize all variables that we clean on shutdown */ + device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); + if (device) { + data = [[SDL_VideoData alloc] init]; + } else { + data = nil; + } + if (!data) { + SDL_OutOfMemory(); + SDL_free(device); + return NULL; + } + device->driverdata = (void *)CFBridgingRetain(data); + device->wakeup_lock = SDL_CreateMutex(); + + /* Set the function pointers */ + device->VideoInit = Cocoa_VideoInit; + device->VideoQuit = Cocoa_VideoQuit; + device->GetDisplayBounds = Cocoa_GetDisplayBounds; + device->GetDisplayUsableBounds = Cocoa_GetDisplayUsableBounds; + device->GetDisplayDPI = Cocoa_GetDisplayDPI; + device->GetDisplayModes = Cocoa_GetDisplayModes; + device->SetDisplayMode = Cocoa_SetDisplayMode; + device->PumpEvents = Cocoa_PumpEvents; + device->WaitEventTimeout = Cocoa_WaitEventTimeout; + device->SendWakeupEvent = Cocoa_SendWakeupEvent; + device->SuspendScreenSaver = Cocoa_SuspendScreenSaver; device->CreateSDLWindow = Cocoa_CreateWindow; device->CreateSDLWindowFrom = Cocoa_CreateWindowFrom; @@ -94,68 +125,9 @@ static SDL_VideoDevice *Cocoa_CreateDevice(void) device->AcceptDragAndDrop = Cocoa_AcceptDragAndDrop; device->FlashWindow = Cocoa_FlashWindow; - /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice)); - if (device) { - data = [[SDL_VideoData alloc] init]; - } else { - data = nil; - } - if (!data) { - SDL_OutOfMemory(); - SDL_free(device); - return NULL; - } - device->driverdata = (void *)CFBridgingRetain(data); - device->wakeup_lock = SDL_CreateMutex(); - - /* Set the function pointers */ - device->VideoInit = Cocoa_VideoInit; - device->VideoQuit = Cocoa_VideoQuit; - device->GetDisplayBounds = Cocoa_GetDisplayBounds; - device->GetDisplayUsableBounds = Cocoa_GetDisplayUsableBounds; - device->GetDisplayDPI = Cocoa_GetDisplayDPI; - device->GetDisplayModes = Cocoa_GetDisplayModes; - device->SetDisplayMode = Cocoa_SetDisplayMode; - device->PumpEvents = Cocoa_PumpEvents; - device->WaitEventTimeout = Cocoa_WaitEventTimeout; - device->SendWakeupEvent = Cocoa_SendWakeupEvent; - device->SuspendScreenSaver = Cocoa_SuspendScreenSaver; - - device->CreateSDLWindow = Cocoa_CreateWindow; - device->CreateSDLWindowFrom = Cocoa_CreateWindowFrom; - device->SetWindowTitle = Cocoa_SetWindowTitle; - device->SetWindowIcon = Cocoa_SetWindowIcon; - device->SetWindowPosition = Cocoa_SetWindowPosition; - device->SetWindowSize = Cocoa_SetWindowSize; - device->SetWindowMinimumSize = Cocoa_SetWindowMinimumSize; - device->SetWindowMaximumSize = Cocoa_SetWindowMaximumSize; - device->SetWindowOpacity = Cocoa_SetWindowOpacity; - device->GetWindowSizeInPixels = Cocoa_GetWindowSizeInPixels; - device->ShowWindow = Cocoa_ShowWindow; - device->HideWindow = Cocoa_HideWindow; - device->RaiseWindow = Cocoa_RaiseWindow; - device->MaximizeWindow = Cocoa_MaximizeWindow; - device->MinimizeWindow = Cocoa_MinimizeWindow; - device->RestoreWindow = Cocoa_RestoreWindow; - device->SetWindowBordered = Cocoa_SetWindowBordered; - device->SetWindowResizable = Cocoa_SetWindowResizable; - device->SetWindowAlwaysOnTop = Cocoa_SetWindowAlwaysOnTop; - device->SetWindowFullscreen = Cocoa_SetWindowFullscreen; - device->GetWindowICCProfile = Cocoa_GetWindowICCProfile; - device->GetWindowDisplayIndex = Cocoa_GetWindowDisplayIndex; - device->SetWindowMouseRect = Cocoa_SetWindowMouseRect; - device->SetWindowMouseGrab = Cocoa_SetWindowMouseGrab; - device->SetWindowKeyboardGrab = Cocoa_SetWindowKeyboardGrab; - device->DestroyWindow = Cocoa_DestroyWindow; - device->GetWindowWMInfo = Cocoa_GetWindowWMInfo; - device->SetWindowHitTest = Cocoa_SetWindowHitTest; - device->AcceptDragAndDrop = Cocoa_AcceptDragAndDrop; - device->FlashWindow = Cocoa_FlashWindow; - - device->shape_driver.CreateShaper = Cocoa_CreateShaper; - device->shape_driver.SetWindowShape = Cocoa_SetWindowShape; - device->shape_driver.ResizeWindowShape = Cocoa_ResizeWindowShape; + device->shape_driver.CreateShaper = Cocoa_CreateShaper; + device->shape_driver.SetWindowShape = Cocoa_SetWindowShape; + device->shape_driver.ResizeWindowShape = Cocoa_ResizeWindowShape; #if SDL_VIDEO_OPENGL_CGL device->GL_LoadLibrary = Cocoa_GL_LoadLibrary; @@ -180,77 +152,77 @@ static SDL_VideoDevice *Cocoa_CreateDevice(void) #endif #if SDL_VIDEO_VULKAN - device->Vulkan_LoadLibrary = Cocoa_Vulkan_LoadLibrary; - device->Vulkan_UnloadLibrary = Cocoa_Vulkan_UnloadLibrary; - device->Vulkan_GetInstanceExtensions = Cocoa_Vulkan_GetInstanceExtensions; - device->Vulkan_CreateSurface = Cocoa_Vulkan_CreateSurface; - device->Vulkan_GetDrawableSize = Cocoa_Vulkan_GetDrawableSize; + device->Vulkan_LoadLibrary = Cocoa_Vulkan_LoadLibrary; + device->Vulkan_UnloadLibrary = Cocoa_Vulkan_UnloadLibrary; + device->Vulkan_GetInstanceExtensions = Cocoa_Vulkan_GetInstanceExtensions; + device->Vulkan_CreateSurface = Cocoa_Vulkan_CreateSurface; + device->Vulkan_GetDrawableSize = Cocoa_Vulkan_GetDrawableSize; #endif #if SDL_VIDEO_METAL - device->Metal_CreateView = Cocoa_Metal_CreateView; - device->Metal_DestroyView = Cocoa_Metal_DestroyView; - device->Metal_GetLayer = Cocoa_Metal_GetLayer; - device->Metal_GetDrawableSize = Cocoa_Metal_GetDrawableSize; + device->Metal_CreateView = Cocoa_Metal_CreateView; + device->Metal_DestroyView = Cocoa_Metal_DestroyView; + device->Metal_GetLayer = Cocoa_Metal_GetLayer; + device->Metal_GetDrawableSize = Cocoa_Metal_GetDrawableSize; #endif - device->StartTextInput = Cocoa_StartTextInput; - device->StopTextInput = Cocoa_StopTextInput; - device->SetTextInputRect = Cocoa_SetTextInputRect; + device->StartTextInput = Cocoa_StartTextInput; + device->StopTextInput = Cocoa_StopTextInput; + device->SetTextInputRect = Cocoa_SetTextInputRect; - device->SetClipboardText = Cocoa_SetClipboardText; - device->GetClipboardText = Cocoa_GetClipboardText; - device->HasClipboardText = Cocoa_HasClipboardText; + device->SetClipboardText = Cocoa_SetClipboardText; + device->GetClipboardText = Cocoa_GetClipboardText; + device->HasClipboardText = Cocoa_HasClipboardText; - device->free = Cocoa_DeleteDevice; + device->free = Cocoa_DeleteDevice; - return device; - } -} + return device; +}} VideoBootStrap COCOA_bootstrap = { "cocoa", "SDL Cocoa video driver", Cocoa_CreateDevice }; -int Cocoa_VideoInit(_THIS) + +int +Cocoa_VideoInit(_THIS) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; - Cocoa_InitModes(_this); - Cocoa_InitKeyboard(_this); - if (Cocoa_InitMouse(_this) < 0) { - return -1; - } - - data.allow_spaces = SDL_GetHintBoolean(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, SDL_TRUE); - data.trackpad_is_touch_only = SDL_GetHintBoolean(SDL_HINT_TRACKPAD_IS_TOUCH_ONLY, SDL_FALSE); - - data.swaplock = SDL_CreateMutex(); - if (!data.swaplock) { - return -1; - } - - return 0; + Cocoa_InitModes(_this); + Cocoa_InitKeyboard(_this); + if (Cocoa_InitMouse(_this) < 0) { + return -1; } -} -void Cocoa_VideoQuit(_THIS) + data.allow_spaces = SDL_GetHintBoolean(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, SDL_TRUE); + data.trackpad_is_touch_only = SDL_GetHintBoolean(SDL_HINT_TRACKPAD_IS_TOUCH_ONLY, SDL_FALSE); + + data.swaplock = SDL_CreateMutex(); + if (!data.swaplock) { + return -1; + } + + return 0; +}} + +void +Cocoa_VideoQuit(_THIS) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; - Cocoa_QuitModes(_this); - Cocoa_QuitKeyboard(_this); - Cocoa_QuitMouse(_this); - SDL_DestroyMutex(data.swaplock); - data.swaplock = NULL; - } -} + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; + Cocoa_QuitModes(_this); + Cocoa_QuitKeyboard(_this); + Cocoa_QuitMouse(_this); + SDL_DestroyMutex(data.swaplock); + data.swaplock = NULL; +}} /* This function assumes that it's called from within an autorelease pool */ NSImage * -Cocoa_CreateImage(SDL_Surface *surface) +Cocoa_CreateImage(SDL_Surface * surface) { SDL_Surface *converted; NSBitmapImageRep *imgrep; @@ -263,16 +235,16 @@ Cocoa_CreateImage(SDL_Surface *surface) return nil; } - imgrep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL - pixelsWide:converted->w - pixelsHigh:converted->h - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bytesPerRow:converted->pitch - bitsPerPixel:converted->format->BitsPerPixel]; + imgrep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL + pixelsWide: converted->w + pixelsHigh: converted->h + bitsPerSample: 8 + samplesPerPixel: 4 + hasAlpha: YES + isPlanar: NO + colorSpaceName: NSDeviceRGBColorSpace + bytesPerRow: converted->pitch + bitsPerPixel: converted->format->BitsPerPixel]; if (imgrep == nil) { SDL_FreeSurface(converted); return nil; @@ -284,7 +256,7 @@ Cocoa_CreateImage(SDL_Surface *surface) SDL_FreeSurface(converted); /* Premultiply the alpha channel */ - for (i = (surface->h * surface->w); i--;) { + for (i = (surface->h * surface->w); i--; ) { Uint8 alpha = pixels[3]; pixels[0] = (Uint8)(((Uint16)pixels[0] * alpha) / 255); pixels[1] = (Uint8)(((Uint16)pixels[1] * alpha) / 255); @@ -292,9 +264,9 @@ Cocoa_CreateImage(SDL_Surface *surface) pixels += 4; } - img = [[NSImage alloc] initWithSize:NSMakeSize(surface->w, surface->h)]; + img = [[NSImage alloc] initWithSize: NSMakeSize(surface->w, surface->h)]; if (img != nil) { - [img addRepresentation:imgrep]; + [img addRepresentation: imgrep]; } return img; } diff --git a/src/video/cocoa/SDL_cocoavulkan.h b/src/video/cocoa/SDL_cocoavulkan.h index 819009985..9ddc70996 100644 --- a/src/video/cocoa/SDL_cocoavulkan.h +++ b/src/video/cocoa/SDL_cocoavulkan.h @@ -38,13 +38,13 @@ int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path); void Cocoa_Vulkan_UnloadLibrary(_THIS); SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS, - SDL_Window *window, - unsigned *count, - const char **names); + SDL_Window *window, + unsigned *count, + const char **names); SDL_bool Cocoa_Vulkan_CreateSurface(_THIS, - SDL_Window *window, - VkInstance instance, - VkSurfaceKHR *surface); + SDL_Window *window, + VkInstance instance, + VkSurfaceKHR *surface); void Cocoa_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h); diff --git a/src/video/cocoa/SDL_cocoavulkan.m b/src/video/cocoa/SDL_cocoavulkan.m index c502d2d71..02817f8f1 100644 --- a/src/video/cocoa/SDL_cocoavulkan.m +++ b/src/video/cocoa/SDL_cocoavulkan.m @@ -37,7 +37,7 @@ #include -const char *defaultPaths[] = { +const char* defaultPaths[] = { "vulkan.framework/vulkan", "libvulkan.1.dylib", "libvulkan.dylib", @@ -69,14 +69,14 @@ int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path) if (!path) { /* Handle the case where Vulkan Portability is linked statically. */ vkGetInstanceProcAddr = - (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE, - "vkGetInstanceProcAddr"); + (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE, + "vkGetInstanceProcAddr"); } if (vkGetInstanceProcAddr) { _this->vulkan_config.loader_handle = DEFAULT_HANDLE; } else { - const char **paths; + const char** paths; const char *foundPath = NULL; int numPaths; int i; @@ -110,7 +110,7 @@ int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path) SDL_SetError("Failed to find %s in either executable or %s: %s", "vkGetInstanceProcAddr", _this->vulkan_config.loader_path, - (const char *)dlerror()); + (const char *) dlerror()); goto fail; } @@ -139,10 +139,13 @@ int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path) } SDL_free(extensions); if (!hasSurfaceExtension) { - SDL_SetError("Installed Vulkan Portability library doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); + SDL_SetError("Installed Vulkan Portability library doesn't implement the " + VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if (!hasMetalSurfaceExtension && !hasMacOSSurfaceExtension) { - SDL_SetError("Installed Vulkan Portability library doesn't implement the " VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " VK_MVK_MACOS_SURFACE_EXTENSION_NAME " extensions"); + SDL_SetError("Installed Vulkan Portability library doesn't implement the " + VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " + VK_MVK_MACOS_SURFACE_EXTENSION_NAME " extensions"); goto fail; } return 0; @@ -164,9 +167,9 @@ void Cocoa_Vulkan_UnloadLibrary(_THIS) } SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS, - SDL_Window *window, - unsigned *count, - const char **names) + SDL_Window *window, + unsigned *count, + const char **names) { static const char *const extensionsForCocoa[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_EXT_METAL_SURFACE_EXTENSION_NAME @@ -176,8 +179,8 @@ SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS, return SDL_FALSE; } return SDL_Vulkan_GetInstanceExtensions_Helper( - count, names, SDL_arraysize(extensionsForCocoa), - extensionsForCocoa); + count, names, SDL_arraysize(extensionsForCocoa), + extensionsForCocoa); } SDL_bool Cocoa_Vulkan_CreateSurface(_THIS, @@ -221,7 +224,7 @@ SDL_bool Cocoa_Vulkan_CreateSurface(_THIS, createInfo.pNext = NULL; createInfo.flags = 0; createInfo.pLayer = (__bridge const CAMetalLayer *) - Cocoa_Metal_GetLayer(_this, metalview); + Cocoa_Metal_GetLayer(_this, metalview); result = vkCreateMetalSurfaceEXT(instance, &createInfo, NULL, surface); if (result != VK_SUCCESS) { Cocoa_Metal_DestroyView(_this, metalview); @@ -236,7 +239,7 @@ SDL_bool Cocoa_Vulkan_CreateSurface(_THIS, createInfo.flags = 0; createInfo.pView = (const void *)metalview; result = vkCreateMacOSSurfaceMVK(instance, &createInfo, - NULL, surface); + NULL, surface); if (result != VK_SUCCESS) { Cocoa_Metal_DestroyView(_this, metalview); SDL_SetError("vkCreateMacOSSurfaceMVK failed: %s", diff --git a/src/video/cocoa/SDL_cocoawindow.h b/src/video/cocoa/SDL_cocoawindow.h index bf7c4409e..18f7d8587 100644 --- a/src/video/cocoa/SDL_cocoawindow.h +++ b/src/video/cocoa/SDL_cocoawindow.h @@ -39,8 +39,7 @@ typedef enum PENDING_OPERATION_MINIMIZE } PendingWindowOperation; -@interface Cocoa_WindowListener : NSResponder -{ +@interface Cocoa_WindowListener : NSResponder { /* SDL_WindowData owns this Listener and has a strong reference to it. * To avoid reference cycles, we could have either a weak or an * unretained ref to the WindowData. */ @@ -57,64 +56,64 @@ typedef enum BOOL isDragAreaRunning; } -- (BOOL)isTouchFromTrackpad:(NSEvent *)theEvent; -- (void)listen:(SDL_WindowData *)data; -- (void)pauseVisibleObservation; -- (void)resumeVisibleObservation; -- (BOOL)setFullscreenSpace:(BOOL)state; -- (BOOL)isInFullscreenSpace; -- (BOOL)isInFullscreenSpaceTransition; -- (void)addPendingWindowOperation:(PendingWindowOperation)operation; -- (void)close; +-(BOOL) isTouchFromTrackpad:(NSEvent *)theEvent; +-(void) listen:(SDL_WindowData *) data; +-(void) pauseVisibleObservation; +-(void) resumeVisibleObservation; +-(BOOL) setFullscreenSpace:(BOOL) state; +-(BOOL) isInFullscreenSpace; +-(BOOL) isInFullscreenSpaceTransition; +-(void) addPendingWindowOperation:(PendingWindowOperation) operation; +-(void) close; -- (BOOL)isMoving; -- (BOOL)isMovingOrFocusClickPending; -- (void)setFocusClickPending:(NSInteger)button; -- (void)clearFocusClickPending:(NSInteger)button; -- (void)setPendingMoveX:(int)x Y:(int)y; -- (void)windowDidFinishMoving; -- (void)onMovingOrFocusClickPendingStateCleared; +-(BOOL) isMoving; +-(BOOL) isMovingOrFocusClickPending; +-(void) setFocusClickPending:(NSInteger) button; +-(void) clearFocusClickPending:(NSInteger) button; +-(void) setPendingMoveX:(int)x Y:(int)y; +-(void) windowDidFinishMoving; +-(void) onMovingOrFocusClickPendingStateCleared; /* Window delegate functionality */ -- (BOOL)windowShouldClose:(id)sender; -- (void)windowDidExpose:(NSNotification *)aNotification; -- (void)windowDidMove:(NSNotification *)aNotification; -- (void)windowDidResize:(NSNotification *)aNotification; -- (void)windowDidMiniaturize:(NSNotification *)aNotification; -- (void)windowDidDeminiaturize:(NSNotification *)aNotification; -- (void)windowDidBecomeKey:(NSNotification *)aNotification; -- (void)windowDidResignKey:(NSNotification *)aNotification; -- (void)windowDidChangeBackingProperties:(NSNotification *)aNotification; -- (void)windowDidChangeScreenProfile:(NSNotification *)aNotification; -- (void)windowDidChangeScreen:(NSNotification *)aNotification; -- (void)windowWillEnterFullScreen:(NSNotification *)aNotification; -- (void)windowDidEnterFullScreen:(NSNotification *)aNotification; -- (void)windowWillExitFullScreen:(NSNotification *)aNotification; -- (void)windowDidExitFullScreen:(NSNotification *)aNotification; -- (NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions; +-(BOOL) windowShouldClose:(id) sender; +-(void) windowDidExpose:(NSNotification *) aNotification; +-(void) windowDidMove:(NSNotification *) aNotification; +-(void) windowDidResize:(NSNotification *) aNotification; +-(void) windowDidMiniaturize:(NSNotification *) aNotification; +-(void) windowDidDeminiaturize:(NSNotification *) aNotification; +-(void) windowDidBecomeKey:(NSNotification *) aNotification; +-(void) windowDidResignKey:(NSNotification *) aNotification; +-(void) windowDidChangeBackingProperties:(NSNotification *) aNotification; +-(void) windowDidChangeScreenProfile:(NSNotification *) aNotification; +-(void) windowDidChangeScreen:(NSNotification *) aNotification; +-(void) windowWillEnterFullScreen:(NSNotification *) aNotification; +-(void) windowDidEnterFullScreen:(NSNotification *) aNotification; +-(void) windowWillExitFullScreen:(NSNotification *) aNotification; +-(void) windowDidExitFullScreen:(NSNotification *) aNotification; +-(NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions; /* See if event is in a drag area, toggle on window dragging. */ -- (BOOL)processHitTest:(NSEvent *)theEvent; +-(BOOL) processHitTest:(NSEvent *)theEvent; /* Window event handling */ -- (void)mouseDown:(NSEvent *)theEvent; -- (void)rightMouseDown:(NSEvent *)theEvent; -- (void)otherMouseDown:(NSEvent *)theEvent; -- (void)mouseUp:(NSEvent *)theEvent; -- (void)rightMouseUp:(NSEvent *)theEvent; -- (void)otherMouseUp:(NSEvent *)theEvent; -- (void)mouseMoved:(NSEvent *)theEvent; -- (void)mouseDragged:(NSEvent *)theEvent; -- (void)rightMouseDragged:(NSEvent *)theEvent; -- (void)otherMouseDragged:(NSEvent *)theEvent; -- (void)scrollWheel:(NSEvent *)theEvent; -- (void)touchesBeganWithEvent:(NSEvent *)theEvent; -- (void)touchesMovedWithEvent:(NSEvent *)theEvent; -- (void)touchesEndedWithEvent:(NSEvent *)theEvent; -- (void)touchesCancelledWithEvent:(NSEvent *)theEvent; +-(void) mouseDown:(NSEvent *) theEvent; +-(void) rightMouseDown:(NSEvent *) theEvent; +-(void) otherMouseDown:(NSEvent *) theEvent; +-(void) mouseUp:(NSEvent *) theEvent; +-(void) rightMouseUp:(NSEvent *) theEvent; +-(void) otherMouseUp:(NSEvent *) theEvent; +-(void) mouseMoved:(NSEvent *) theEvent; +-(void) mouseDragged:(NSEvent *) theEvent; +-(void) rightMouseDragged:(NSEvent *) theEvent; +-(void) otherMouseDragged:(NSEvent *) theEvent; +-(void) scrollWheel:(NSEvent *) theEvent; +-(void) touchesBeganWithEvent:(NSEvent *) theEvent; +-(void) touchesMovedWithEvent:(NSEvent *) theEvent; +-(void) touchesEndedWithEvent:(NSEvent *) theEvent; +-(void) touchesCancelledWithEvent:(NSEvent *) theEvent; /* Touch event handling */ -- (void)handleTouches:(NSTouchPhase)phase withEvent:(NSEvent *)theEvent; +-(void) handleTouches:(NSTouchPhase) phase withEvent:(NSEvent*) theEvent; @end /* *INDENT-ON* */ @@ -123,23 +122,23 @@ typedef enum @class SDL_VideoData; @interface SDL_WindowData : NSObject -@property(nonatomic) SDL_Window *window; -@property(nonatomic) NSWindow *nswindow; -@property(nonatomic) NSView *sdlContentView; -@property(nonatomic) NSMutableArray *nscontexts; -@property(nonatomic) SDL_bool created; -@property(nonatomic) SDL_bool inWindowFullscreenTransition; -@property(nonatomic) NSInteger window_number; -@property(nonatomic) NSInteger flash_request; -@property(nonatomic) Cocoa_WindowListener *listener; -@property(nonatomic) SDL_VideoData *videodata; + @property (nonatomic) SDL_Window *window; + @property (nonatomic) NSWindow *nswindow; + @property (nonatomic) NSView *sdlContentView; + @property (nonatomic) NSMutableArray *nscontexts; + @property (nonatomic) SDL_bool created; + @property (nonatomic) SDL_bool inWindowFullscreenTransition; + @property (nonatomic) NSInteger window_number; + @property (nonatomic) NSInteger flash_request; + @property (nonatomic) Cocoa_WindowListener *listener; + @property (nonatomic) SDL_VideoData *videodata; #if SDL_VIDEO_OPENGL_EGL -@property(nonatomic) EGLSurface egl_surface; + @property (nonatomic) EGLSurface egl_surface; #endif @end -extern int Cocoa_CreateWindow(_THIS, SDL_Window *window); -extern int Cocoa_CreateWindowFrom(_THIS, SDL_Window *window, +extern int Cocoa_CreateWindow(_THIS, SDL_Window * window); +extern int Cocoa_CreateWindowFrom(_THIS, SDL_Window * window, const void *data); extern void Cocoa_SetWindowTitle(_THIS, SDL_Window * window); extern void Cocoa_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon); @@ -168,8 +167,8 @@ extern void Cocoa_SetWindowMouseGrab(_THIS, SDL_Window * window, SDL_bool grabbe extern void Cocoa_DestroyWindow(_THIS, SDL_Window * window); extern SDL_bool Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info); extern int Cocoa_SetWindowHitTest(SDL_Window *window, SDL_bool enabled); -extern void Cocoa_AcceptDragAndDrop(SDL_Window *window, SDL_bool accept); -extern int Cocoa_FlashWindow(_THIS, SDL_Window *window, SDL_FlashOperation operation); +extern void Cocoa_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept); +extern int Cocoa_FlashWindow(_THIS, SDL_Window * window, SDL_FlashOperation operation); #endif /* SDL_cocoawindow_h_ */ diff --git a/src/video/cocoa/SDL_cocoawindow.m b/src/video/cocoa/SDL_cocoawindow.m index 785ad6ef5..c73827656 100644 --- a/src/video/cocoa/SDL_cocoawindow.m +++ b/src/video/cocoa/SDL_cocoawindow.m @@ -46,21 +46,20 @@ #ifdef DEBUG_COCOAWINDOW #define DLog(fmt, ...) printf("%s: " fmt "\n", __func__, ##__VA_ARGS__) #else -#define DLog(...) \ - do { \ - } while (0) +#define DLog(...) do { } while (0) #endif + #define FULLSCREEN_MASK (SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN) #ifndef MAC_OS_X_VERSION_10_12 #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask #endif #ifndef NSAppKitVersionNumber10_13_2 -#define NSAppKitVersionNumber10_13_2 1561.2 +#define NSAppKitVersionNumber10_13_2 1561.2 #endif #ifndef NSAppKitVersionNumber10_14 -#define NSAppKitVersionNumber10_14 1671 +#define NSAppKitVersionNumber10_14 1671 #endif @implementation SDL_WindowData @@ -69,11 +68,11 @@ @interface NSWindow (SDL) #if MAC_OS_X_VERSION_MAX_ALLOWED < 101000 /* Added in the 10.10 SDK */ -@property(readonly) NSRect contentLayoutRect; +@property (readonly) NSRect contentLayoutRect; #endif /* This is available as of 10.13.2, but isn't in public headers */ -@property(nonatomic) NSRect mouseConfinementRect; +@property (nonatomic) NSRect mouseConfinementRect; @end @interface SDLWindow : NSWindow @@ -84,12 +83,12 @@ - (void)doCommandBySelector:(SEL)aSelector; /* Handle drag-and-drop of files onto the SDL window. */ -- (NSDragOperation)draggingEntered:(id)sender; -- (BOOL)performDragOperation:(id)sender; +- (NSDragOperation)draggingEntered:(id )sender; +- (BOOL)performDragOperation:(id )sender; - (BOOL)wantsPeriodicDraggingUpdates; - (BOOL)validateMenuItem:(NSMenuItem *)menuItem; -- (SDL_Window *)findSDLWindow; +- (SDL_Window*)findSDLWindow; @end @implementation SDLWindow @@ -103,7 +102,7 @@ SDL_Window *window = [self findSDLWindow]; if (window == NULL) { return NO; - } else if ((window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_FULLSCREEN_DESKTOP)) != 0) { + } else if ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_FULLSCREEN_DESKTOP)) != 0) { return NO; } else if ((window->flags & SDL_WINDOW_RESIZABLE) == 0) { return NO; @@ -149,7 +148,7 @@ /*NSLog(@"doCommandBySelector: %@\n", NSStringFromSelector(aSelector));*/ } -- (NSDragOperation)draggingEntered:(id)sender +- (NSDragOperation)draggingEntered:(id )sender { if (([sender draggingSourceOperationMask] & NSDragOperationGeneric) == NSDragOperationGeneric) { return NSDragOperationGeneric; @@ -158,80 +157,79 @@ return NSDragOperationNone; /* no idea what to do with this, reject it. */ } -- (BOOL)performDragOperation:(id)sender +- (BOOL)performDragOperation:(id )sender +{ @autoreleasepool { - @autoreleasepool { - NSPasteboard *pasteboard = [sender draggingPasteboard]; - NSArray *types = [NSArray arrayWithObject:NSFilenamesPboardType]; - NSString *desiredType = [pasteboard availableTypeFromArray:types]; - SDL_Window *sdlwindow = [self findSDLWindow]; - NSData *data; - NSArray *array; - NSPoint point; - SDL_Mouse *mouse; - int x, y; + NSPasteboard *pasteboard = [sender draggingPasteboard]; + NSArray *types = [NSArray arrayWithObject:NSFilenamesPboardType]; + NSString *desiredType = [pasteboard availableTypeFromArray:types]; + SDL_Window *sdlwindow = [self findSDLWindow]; + NSData *data; + NSArray *array; + NSPoint point; + SDL_Mouse *mouse; + int x, y; - if (desiredType == nil) { - return NO; /* can't accept anything that's being dropped here. */ - } + if (desiredType == nil) { + return NO; /* can't accept anything that's being dropped here. */ + } - data = [pasteboard dataForType:desiredType]; - if (data == nil) { - return NO; - } + data = [pasteboard dataForType:desiredType]; + if (data == nil) { + return NO; + } - SDL_assert([desiredType isEqualToString:NSFilenamesPboardType]); - array = [pasteboard propertyListForType:@"NSFilenamesPboardType"]; + SDL_assert([desiredType isEqualToString:NSFilenamesPboardType]); + array = [pasteboard propertyListForType:@"NSFilenamesPboardType"]; - /* Code addon to update the mouse location */ - point = [sender draggingLocation]; - mouse = SDL_GetMouse(); - x = (int)point.x; - y = (int)(sdlwindow->h - point.y); - if (x >= 0 && x < sdlwindow->w && y >= 0 && y < sdlwindow->h) { - SDL_SendMouseMotion(sdlwindow, mouse->mouseID, 0, x, y); - } - /* Code addon to update the mouse location */ + /* Code addon to update the mouse location */ + point = [sender draggingLocation]; + mouse = SDL_GetMouse(); + x = (int)point.x; + y = (int)(sdlwindow->h - point.y); + if (x >= 0 && x < sdlwindow->w && y >= 0 && y < sdlwindow->h) { + SDL_SendMouseMotion(sdlwindow, mouse->mouseID, 0, x, y); + } + /* Code addon to update the mouse location */ - for (NSString *path in array) { - NSURL *fileURL = [NSURL fileURLWithPath:path]; - NSNumber *isAlias = nil; + for (NSString *path in array) { + NSURL *fileURL = [NSURL fileURLWithPath:path]; + NSNumber *isAlias = nil; - [fileURL getResourceValue:&isAlias forKey:NSURLIsAliasFileKey error:nil]; + [fileURL getResourceValue:&isAlias forKey:NSURLIsAliasFileKey error:nil]; - /* If the URL is an alias, resolve it. */ - if ([isAlias boolValue]) { - NSURLBookmarkResolutionOptions opts = NSURLBookmarkResolutionWithoutMounting | NSURLBookmarkResolutionWithoutUI; - NSData *bookmark = [NSURL bookmarkDataWithContentsOfURL:fileURL error:nil]; - if (bookmark != nil) { - NSURL *resolvedURL = [NSURL URLByResolvingBookmarkData:bookmark - options:opts - relativeToURL:nil - bookmarkDataIsStale:nil - error:nil]; + /* If the URL is an alias, resolve it. */ + if ([isAlias boolValue]) { + NSURLBookmarkResolutionOptions opts = NSURLBookmarkResolutionWithoutMounting | NSURLBookmarkResolutionWithoutUI; + NSData *bookmark = [NSURL bookmarkDataWithContentsOfURL:fileURL error:nil]; + if (bookmark != nil) { + NSURL *resolvedURL = [NSURL URLByResolvingBookmarkData:bookmark + options:opts + relativeToURL:nil + bookmarkDataIsStale:nil + error:nil]; - if (resolvedURL != nil) { - fileURL = resolvedURL; - } + if (resolvedURL != nil) { + fileURL = resolvedURL; } } - - if (!SDL_SendDropFile(sdlwindow, [[fileURL path] UTF8String])) { - return NO; - } } - SDL_SendDropComplete(sdlwindow); - return YES; + if (!SDL_SendDropFile(sdlwindow, [[fileURL path] UTF8String])) { + return NO; + } } -} + + SDL_SendDropComplete(sdlwindow); + return YES; +}} - (BOOL)wantsPeriodicDraggingUpdates { return NO; } -- (SDL_Window *)findSDLWindow +- (SDL_Window*)findSDLWindow { SDL_Window *sdlwindow = NULL; SDL_VideoDevice *_this = SDL_GetVideoDevice(); @@ -239,7 +237,7 @@ /* !!! FIXME: is there a better way to do this? */ if (_this) { for (sdlwindow = _this->windows; sdlwindow; sdlwindow = sdlwindow->next) { - NSWindow *nswindow = ((__bridge SDL_WindowData *)sdlwindow->driverdata).nswindow; + NSWindow *nswindow = ((__bridge SDL_WindowData *) sdlwindow->driverdata).nswindow; if (nswindow == self) { break; } @@ -251,6 +249,7 @@ @end + static Uint32 s_moveHack; static void ConvertNSRect(NSScreen *screen, BOOL fullscreen, NSRect *r) @@ -258,15 +257,16 @@ static void ConvertNSRect(NSScreen *screen, BOOL fullscreen, NSRect *r) r->origin.y = CGDisplayPixelsHigh(kCGDirectMainDisplay) - r->origin.y - r->size.height; } -static void ScheduleContextUpdates(SDL_WindowData *data) +static void +ScheduleContextUpdates(SDL_WindowData *data) { -/* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ -#if SDL_VIDEO_OPENGL + /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ + #if SDL_VIDEO_OPENGL -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif + #ifdef __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + #endif NSOpenGLContext *currentContext; NSMutableArray *contexts; @@ -276,7 +276,7 @@ static void ScheduleContextUpdates(SDL_WindowData *data) currentContext = [NSOpenGLContext currentContext]; contexts = data.nscontexts; - @synchronized(contexts) { + @synchronized (contexts) { for (SDLOpenGLContext *context in contexts) { if (context == currentContext) { [context update]; @@ -286,20 +286,22 @@ static void ScheduleContextUpdates(SDL_WindowData *data) } } -#ifdef __clang__ -#pragma clang diagnostic pop -#endif + #ifdef __clang__ + #pragma clang diagnostic pop + #endif -#endif /* SDL_VIDEO_OPENGL */ + #endif /* SDL_VIDEO_OPENGL */ } /* !!! FIXME: this should use a hint callback. */ -static int GetHintCtrlClickEmulateRightClick() +static int +GetHintCtrlClickEmulateRightClick() { return SDL_GetHintBoolean(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, SDL_FALSE); } -static NSUInteger GetWindowWindowedStyle(SDL_Window *window) +static NSUInteger +GetWindowWindowedStyle(SDL_Window * window) { /* IF YOU CHANGE ANY FLAGS IN HERE, PLEASE READ the NSWindowStyleMaskBorderless comments in SetupWindowData()! */ @@ -311,7 +313,7 @@ static NSUInteger GetWindowWindowedStyle(SDL_Window *window) if (window->flags & SDL_WINDOW_BORDERLESS) { style |= NSWindowStyleMaskBorderless; } else { - style |= (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable); + style |= (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable); } if (window->flags & SDL_WINDOW_RESIZABLE) { style |= NSWindowStyleMaskResizable; @@ -319,7 +321,8 @@ static NSUInteger GetWindowWindowedStyle(SDL_Window *window) return style; } -static NSUInteger GetWindowStyle(SDL_Window *window) +static NSUInteger +GetWindowStyle(SDL_Window * window) { NSUInteger style = 0; @@ -331,9 +334,10 @@ static NSUInteger GetWindowStyle(SDL_Window *window) return style; } -static SDL_bool SetWindowStyle(SDL_Window *window, NSUInteger style) +static SDL_bool +SetWindowStyle(SDL_Window * window, NSUInteger style) { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; NSWindow *nswindow = data.nswindow; /* The view responder chain gets messed with during setStyleMask */ @@ -351,9 +355,10 @@ static SDL_bool SetWindowStyle(SDL_Window *window, NSUInteger style) return SDL_TRUE; } -static SDL_bool ShouldAdjustCoordinatesForGrab(SDL_Window *window) +static SDL_bool +ShouldAdjustCoordinatesForGrab(SDL_Window * window) { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; if (!data || [data.listener isMovingOrFocusClickPending]) { return SDL_FALSE; @@ -369,7 +374,8 @@ static SDL_bool ShouldAdjustCoordinatesForGrab(SDL_Window *window) return SDL_FALSE; } -static SDL_bool AdjustCoordinatesForGrab(SDL_Window *window, int x, int y, CGPoint *adjusted) +static SDL_bool +AdjustCoordinatesForGrab(SDL_Window * window, int x, int y, CGPoint *adjusted) { if (window->mouse_rect.w > 0 && window->mouse_rect.h > 0) { SDL_Rect window_rect; @@ -408,9 +414,10 @@ static SDL_bool AdjustCoordinatesForGrab(SDL_Window *window, int x, int y, CGPoi return SDL_FALSE; } -static void Cocoa_UpdateClipCursor(SDL_Window *window) +static void +Cocoa_UpdateClipCursor(SDL_Window * window) { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; if (NSAppKitVersionNumber >= NSAppKitVersionNumber10_13_2) { NSWindow *nswindow = data.nswindow; @@ -461,6 +468,7 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) } } + @implementation Cocoa_WindowListener - (void)listen:(SDL_WindowData *)data @@ -539,13 +547,13 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) } } -- (void)pauseVisibleObservation +-(void) pauseVisibleObservation { observingVisible = NO; wasVisible = [_data.nswindow isVisible]; } -- (void)resumeVisibleObservation +-(void) resumeVisibleObservation { BOOL isVisible = [_data.nswindow isVisible]; observingVisible = YES; @@ -560,20 +568,20 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) } } -- (BOOL)setFullscreenSpace:(BOOL)state +-(BOOL) setFullscreenSpace:(BOOL) state { SDL_Window *window = _data.window; NSWindow *nswindow = _data.nswindow; - SDL_VideoData *videodata = ((__bridge SDL_WindowData *)window->driverdata).videodata; + SDL_VideoData *videodata = ((__bridge SDL_WindowData *) window->driverdata).videodata; if (!videodata.allow_spaces) { - return NO; /* Spaces are forcibly disabled. */ + return NO; /* Spaces are forcibly disabled. */ } else if (state && ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP)) { - return NO; /* we only allow you to make a Space on FULLSCREEN_DESKTOP windows. */ + return NO; /* we only allow you to make a Space on FULLSCREEN_DESKTOP windows. */ } else if (!state && ((window->last_fullscreen_flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP)) { - return NO; /* we only handle leaving the Space on windows that were previously FULLSCREEN_DESKTOP. */ + return NO; /* we only handle leaving the Space on windows that were previously FULLSCREEN_DESKTOP. */ } else if (state == isFullscreenSpace) { - return YES; /* already there. */ + return YES; /* already there. */ } if (inFullscreenTransition) { @@ -588,21 +596,21 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) /* you need to be FullScreenPrimary, or toggleFullScreen doesn't work. Unset it again in windowDidExitFullScreen. */ [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; - [nswindow performSelectorOnMainThread:@selector(toggleFullScreen:) withObject:nswindow waitUntilDone:NO]; + [nswindow performSelectorOnMainThread: @selector(toggleFullScreen:) withObject:nswindow waitUntilDone:NO]; return YES; } -- (BOOL)isInFullscreenSpace +-(BOOL) isInFullscreenSpace { return isFullscreenSpace; } -- (BOOL)isInFullscreenSpaceTransition +-(BOOL) isInFullscreenSpaceTransition { return inFullscreenTransition; } -- (void)addPendingWindowOperation:(PendingWindowOperation)operation +-(void) addPendingWindowOperation:(PendingWindowOperation) operation { pendingWindowOperation = operation; } @@ -656,12 +664,12 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) return isMoving || (focusClickPending != 0); } -- (void)setFocusClickPending:(NSInteger)button +-(void) setFocusClickPending:(NSInteger) button { focusClickPending |= (1 << button); } -- (void)clearFocusClickPending:(NSInteger)button +-(void) clearFocusClickPending:(NSInteger) button { if ((focusClickPending & (1 << button)) != 0) { focusClickPending &= ~(1 << button); @@ -671,7 +679,7 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) } } -- (void)setPendingMoveX:(int)x Y:(int)y +-(void) setPendingMoveX:(int)x Y:(int)y { pendingWindowWarpX = x; pendingWindowWarpY = y; @@ -928,7 +936,7 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) { SDL_Window *window = _data.window; - SetWindowStyle(window, (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable)); + SetWindowStyle(window, (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable)); isFullscreenSpace = YES; inFullscreenTransition = YES; @@ -946,7 +954,7 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) isFullscreenSpace = NO; inFullscreenTransition = NO; - + [self windowDidExitFullScreen:nil]; } @@ -996,16 +1004,16 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) - (void)windowDidFailToExitFullScreen:(NSNotification *)aNotification { SDL_Window *window = _data.window; - + if (window->is_destroying) { return; } - SetWindowStyle(window, (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable)); - + SetWindowStyle(window, (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable)); + isFullscreenSpace = YES; inFullscreenTransition = NO; - + [self windowDidEnterFullScreen:nil]; } @@ -1103,7 +1111,7 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) } } -- (NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions +-(NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions { if ((_data.window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) { return NSApplicationPresentationFullScreen | NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar; @@ -1157,32 +1165,33 @@ static void Cocoa_UpdateClipCursor(SDL_Window *window) { SDL_assert(isDragAreaRunning == [_data.nswindow isMovableByWindowBackground]); - if (_data.window->hit_test) { /* if no hit-test, skip this. */ + if (_data.window->hit_test) { /* if no hit-test, skip this. */ const NSPoint location = [theEvent locationInWindow]; - const SDL_Point point = { (int)location.x, _data.window->h - (((int)location.y) - 1) }; + const SDL_Point point = { (int) location.x, _data.window->h - (((int) location.y)-1) }; const SDL_HitTestResult rc = _data.window->hit_test(_data.window, &point, _data.window->hit_test_data); if (rc == SDL_HITTEST_DRAGGABLE) { if (!isDragAreaRunning) { isDragAreaRunning = YES; [_data.nswindow setMovableByWindowBackground:YES]; } - return YES; /* dragging! */ + return YES; /* dragging! */ } } if (isDragAreaRunning) { isDragAreaRunning = NO; [_data.nswindow setMovableByWindowBackground:NO]; - return YES; /* was dragging, drop event. */ + return YES; /* was dragging, drop event. */ } - return NO; /* not a special area, carry on. */ + return NO; /* not a special area, carry on. */ } -static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_Window *window, const Uint8 state, const Uint8 button) +static int +Cocoa_SendMouseButtonClicks(SDL_Mouse * mouse, NSEvent *theEvent, SDL_Window * window, const Uint8 state, const Uint8 button) { const SDL_MouseID mouseID = mouse->mouseID; - const int clicks = (int)[theEvent clickCount]; + const int clicks = (int) [theEvent clickCount]; SDL_Window *focus = SDL_GetKeyboardFocus(); int rc; @@ -1191,14 +1200,14 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ // the position in the currently-focused window. We don't (currently) send a mousemove // event for the background window, this just makes sure the button is reported at the // correct position in its own event. - if (focus && ([theEvent window] == ((__bridge SDL_WindowData *)focus->driverdata).nswindow)) { + if ( focus && ([theEvent window] == ((__bridge SDL_WindowData *) focus->driverdata).nswindow) ) { rc = SDL_SendMouseButtonClicks(window, mouseID, state, button, clicks); } else { const int orig_x = mouse->x; const int orig_y = mouse->y; const NSPoint point = [theEvent locationInWindow]; - mouse->x = (int)point.x; - mouse->y = (int)(window->h - point.y); + mouse->x = (int) point.x; + mouse->y = (int) (window->h - point.y); rc = SDL_SendMouseButtonClicks(window, mouseID, state, button, clicks); mouse->x = orig_x; mouse->y = orig_y; @@ -1226,7 +1235,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ if ([self processHitTest:theEvent]) { SDL_SendWindowEvent(_data.window, SDL_WINDOWEVENT_HIT_TEST, 0, 0); - return; /* dragging, drop event. */ + return; /* dragging, drop event. */ } switch ([theEvent buttonNumber]) { @@ -1247,7 +1256,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ button = SDL_BUTTON_MIDDLE; break; default: - button = (int)[theEvent buttonNumber] + 1; + button = (int) [theEvent buttonNumber] + 1; break; } @@ -1275,7 +1284,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ if ([self processHitTest:theEvent]) { SDL_SendWindowEvent(_data.window, SDL_WINDOWEVENT_HIT_TEST, 0, 0); - return; /* stopped dragging, drop event. */ + return; /* stopped dragging, drop event. */ } switch ([theEvent buttonNumber]) { @@ -1294,7 +1303,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ button = SDL_BUTTON_MIDDLE; break; default: - button = (int)[theEvent buttonNumber] + 1; + button = (int) [theEvent buttonNumber] + 1; break; } @@ -1328,7 +1337,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ if ([self processHitTest:theEvent]) { SDL_SendWindowEvent(window, SDL_WINDOWEVENT_HIT_TEST, 0, 0); - return; /* dragging, drop event. */ + return; /* dragging, drop event. */ } if (mouse->relative_mode) { @@ -1374,10 +1383,11 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ Cocoa_HandleMouseWheel(_data.window, theEvent); } + - (BOOL)isTouchFromTrackpad:(NSEvent *)theEvent { SDL_Window *window = _data.window; - SDL_VideoData *videodata = ((__bridge SDL_WindowData *)window->driverdata).videodata; + SDL_VideoData *videodata = ((__bridge SDL_WindowData *) window->driverdata).videodata; /* if this a MacBook trackpad, we'll make input look like a synthesized event. This is backwards from reality, but better matches user @@ -1400,7 +1410,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ return istrackpad; } -- (void)touchesBeganWithEvent:(NSEvent *)theEvent +- (void)touchesBeganWithEvent:(NSEvent *) theEvent { NSSet *touches; SDL_TouchID touchID; @@ -1411,7 +1421,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ touchID = istrackpad ? SDL_MOUSE_TOUCHID : (SDL_TouchID)(intptr_t)[[touches anyObject] device]; existingTouchCount = 0; - for (NSTouch *touch in touches) { + for (NSTouch* touch in touches) { if ([touch phase] != NSTouchPhaseBegan) { existingTouchCount++; } @@ -1420,7 +1430,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ int numFingers = SDL_GetNumTouchFingers(touchID); DLog("Reset Lost Fingers: %d", numFingers); for (--numFingers; numFingers >= 0; --numFingers) { - SDL_Finger *finger = SDL_GetTouchFinger(touchID, numFingers); + SDL_Finger* finger = SDL_GetTouchFinger(touchID, numFingers); /* trackpad touches have no window. If we really wanted one we could * use the window that has mouse or keyboard focus. * Sending a null window currently also prevents synthetic mouse @@ -1435,22 +1445,22 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ [self handleTouches:NSTouchPhaseBegan withEvent:theEvent]; } -- (void)touchesMovedWithEvent:(NSEvent *)theEvent +- (void)touchesMovedWithEvent:(NSEvent *) theEvent { [self handleTouches:NSTouchPhaseMoved withEvent:theEvent]; } -- (void)touchesEndedWithEvent:(NSEvent *)theEvent +- (void)touchesEndedWithEvent:(NSEvent *) theEvent { [self handleTouches:NSTouchPhaseEnded withEvent:theEvent]; } -- (void)touchesCancelledWithEvent:(NSEvent *)theEvent +- (void)touchesCancelledWithEvent:(NSEvent *) theEvent { [self handleTouches:NSTouchPhaseCancelled withEvent:theEvent]; } -- (void)handleTouches:(NSTouchPhase)phase withEvent:(NSEvent *)theEvent +- (void)handleTouches:(NSTouchPhase) phase withEvent:(NSEvent *) theEvent { NSSet *touches = [theEvent touchesMatchingPhase:phase inView:nil]; const BOOL istrackpad = [self isTouchFromTrackpad:theEvent]; @@ -1512,12 +1522,11 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ @end -@interface SDLView : NSView -{ +@interface SDLView : NSView { SDL_Window *_sdlWindow; } -- (void)setSDLWindow:(SDL_Window *)window; +- (void)setSDLWindow:(SDL_Window*)window; /* The default implementation doesn't pass rightMouseDown to responder chain */ - (void)rightMouseDown:(NSEvent *)theEvent; @@ -1530,7 +1539,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ @implementation SDLView -- (void)setSDLWindow:(SDL_Window *)window +- (void)setSDLWindow:(SDL_Window*)window { _sdlWindow = window; } @@ -1566,7 +1575,7 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ white until the app is ready to draw. In practice on modern macOS, this only gets called for window creation and other extraordinary events. */ self.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack); - ScheduleContextUpdates((__bridge SDL_WindowData *)_sdlWindow->driverdata); + ScheduleContextUpdates((__bridge SDL_WindowData *) _sdlWindow->driverdata); SDL_SendWindowEvent(_sdlWindow, SDL_WINDOWEVENT_EXPOSED, 0, 0); } @@ -1608,181 +1617,182 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_ } @end -static int SetupWindowData(_THIS, SDL_Window *window, NSWindow *nswindow, NSView *nsview, SDL_bool created) +static int +SetupWindowData(_THIS, SDL_Window * window, NSWindow *nswindow, NSView *nsview, SDL_bool created) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoData *videodata = (__bridge SDL_VideoData *)_this->driverdata; - SDL_WindowData *data; + SDL_VideoData *videodata = (__bridge SDL_VideoData *) _this->driverdata; + SDL_WindowData *data; - /* Allocate the window data */ - data = [[SDL_WindowData alloc] init]; - if (!data) { - return SDL_OutOfMemory(); - } - data.window = window; - data.nswindow = nswindow; - data.created = created; - data.videodata = videodata; - data.window_number = nswindow.windowNumber; - data.nscontexts = [[NSMutableArray alloc] init]; - data.sdlContentView = nsview; - - /* Create an event listener for the window */ - data.listener = [[Cocoa_WindowListener alloc] init]; - - /* Fill in the SDL window with the window data */ - { - NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]]; - ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); - window->x = (int)rect.origin.x; - window->y = (int)rect.origin.y; - window->w = (int)rect.size.width; - window->h = (int)rect.size.height; - } - - /* Set up the listener after we create the view */ - [data.listener listen:data]; - - if ([nswindow isVisible]) { - window->flags |= SDL_WINDOW_SHOWN; - } else { - window->flags &= ~SDL_WINDOW_SHOWN; - } - - { - unsigned long style = [nswindow styleMask]; - - /* NSWindowStyleMaskBorderless is zero, and it's possible to be - Resizeable _and_ borderless, so we can't do a simple bitwise AND - of NSWindowStyleMaskBorderless here. */ - if ((style & ~(NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable)) == NSWindowStyleMaskBorderless) { - window->flags |= SDL_WINDOW_BORDERLESS; - } else { - window->flags &= ~SDL_WINDOW_BORDERLESS; - } - if (style & NSWindowStyleMaskResizable) { - window->flags |= SDL_WINDOW_RESIZABLE; - } else { - window->flags &= ~SDL_WINDOW_RESIZABLE; - } - } - - /* isZoomed always returns true if the window is not resizable */ - if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) { - window->flags |= SDL_WINDOW_MAXIMIZED; - } else { - window->flags &= ~SDL_WINDOW_MAXIMIZED; - } - - if ([nswindow isMiniaturized]) { - window->flags |= SDL_WINDOW_MINIMIZED; - } else { - window->flags &= ~SDL_WINDOW_MINIMIZED; - } - - if ([nswindow isKeyWindow]) { - window->flags |= SDL_WINDOW_INPUT_FOCUS; - SDL_SetKeyboardFocus(data.window); - } - - /* SDL_WindowData will be holding a strong reference to the NSWindow, and - * it will also call [NSWindow close] in DestroyWindow before releasing the - * NSWindow, so the extra release provided by releasedWhenClosed isn't - * necessary. */ - nswindow.releasedWhenClosed = NO; - - /* Prevents the window's "window device" from being destroyed when it is - * hidden. See http://www.mikeash.com/pyblog/nsopenglcontext-and-one-shot.html - */ - [nswindow setOneShot:NO]; - - /* All done! */ - window->driverdata = (void *)CFBridgingRetain(data); - return 0; + /* Allocate the window data */ + data = [[SDL_WindowData alloc] init]; + if (!data) { + return SDL_OutOfMemory(); } -} + data.window = window; + data.nswindow = nswindow; + data.created = created; + data.videodata = videodata; + data.window_number = nswindow.windowNumber; + data.nscontexts = [[NSMutableArray alloc] init]; + data.sdlContentView = nsview; -int Cocoa_CreateWindow(_THIS, SDL_Window *window) + /* Create an event listener for the window */ + data.listener = [[Cocoa_WindowListener alloc] init]; + + /* Fill in the SDL window with the window data */ + { + NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]]; + ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); + window->x = (int)rect.origin.x; + window->y = (int)rect.origin.y; + window->w = (int)rect.size.width; + window->h = (int)rect.size.height; + } + + /* Set up the listener after we create the view */ + [data.listener listen:data]; + + if ([nswindow isVisible]) { + window->flags |= SDL_WINDOW_SHOWN; + } else { + window->flags &= ~SDL_WINDOW_SHOWN; + } + + { + unsigned long style = [nswindow styleMask]; + + /* NSWindowStyleMaskBorderless is zero, and it's possible to be + Resizeable _and_ borderless, so we can't do a simple bitwise AND + of NSWindowStyleMaskBorderless here. */ + if ((style & ~(NSWindowStyleMaskResizable|NSWindowStyleMaskMiniaturizable)) == NSWindowStyleMaskBorderless) { + window->flags |= SDL_WINDOW_BORDERLESS; + } else { + window->flags &= ~SDL_WINDOW_BORDERLESS; + } + if (style & NSWindowStyleMaskResizable) { + window->flags |= SDL_WINDOW_RESIZABLE; + } else { + window->flags &= ~SDL_WINDOW_RESIZABLE; + } + } + + /* isZoomed always returns true if the window is not resizable */ + if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) { + window->flags |= SDL_WINDOW_MAXIMIZED; + } else { + window->flags &= ~SDL_WINDOW_MAXIMIZED; + } + + if ([nswindow isMiniaturized]) { + window->flags |= SDL_WINDOW_MINIMIZED; + } else { + window->flags &= ~SDL_WINDOW_MINIMIZED; + } + + if ([nswindow isKeyWindow]) { + window->flags |= SDL_WINDOW_INPUT_FOCUS; + SDL_SetKeyboardFocus(data.window); + } + + /* SDL_WindowData will be holding a strong reference to the NSWindow, and + * it will also call [NSWindow close] in DestroyWindow before releasing the + * NSWindow, so the extra release provided by releasedWhenClosed isn't + * necessary. */ + nswindow.releasedWhenClosed = NO; + + /* Prevents the window's "window device" from being destroyed when it is + * hidden. See http://www.mikeash.com/pyblog/nsopenglcontext-and-one-shot.html + */ + [nswindow setOneShot:NO]; + + /* All done! */ + window->driverdata = (void *)CFBridgingRetain(data); + return 0; +}} + +int +Cocoa_CreateWindow(_THIS, SDL_Window * window) +{ @autoreleasepool { - @autoreleasepool { - SDL_VideoData *videodata = (__bridge SDL_VideoData *)_this->driverdata; - NSWindow *nswindow; - SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); - NSRect rect; - SDL_Rect bounds; - NSUInteger style; - NSArray *screens = [NSScreen screens]; - NSScreen *screen = nil; - SDLView *contentView; - BOOL highdpi; + SDL_VideoData *videodata = (__bridge SDL_VideoData *) _this->driverdata; + NSWindow *nswindow; + SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); + NSRect rect; + SDL_Rect bounds; + NSUInteger style; + NSArray *screens = [NSScreen screens]; + NSScreen *screen = nil; + SDLView *contentView; + BOOL highdpi; - Cocoa_GetDisplayBounds(_this, display, &bounds); - rect.origin.x = window->x; - rect.origin.y = window->y; - rect.size.width = window->w; - rect.size.height = window->h; - ConvertNSRect([screens objectAtIndex:0], (window->flags & FULLSCREEN_MASK), &rect); + Cocoa_GetDisplayBounds(_this, display, &bounds); + rect.origin.x = window->x; + rect.origin.y = window->y; + rect.size.width = window->w; + rect.size.height = window->h; + ConvertNSRect([screens objectAtIndex:0], (window->flags & FULLSCREEN_MASK), &rect); - style = GetWindowStyle(window); + style = GetWindowStyle(window); - /* Figure out which screen to place this window */ - for (NSScreen *candidate in screens) { - NSRect screenRect = [candidate frame]; - if (rect.origin.x >= screenRect.origin.x && - rect.origin.x < screenRect.origin.x + screenRect.size.width && - rect.origin.y >= screenRect.origin.y && - rect.origin.y < screenRect.origin.y + screenRect.size.height) { - screen = candidate; - rect.origin.x -= screenRect.origin.x; - rect.origin.y -= screenRect.origin.y; - } + /* Figure out which screen to place this window */ + for (NSScreen *candidate in screens) { + NSRect screenRect = [candidate frame]; + if (rect.origin.x >= screenRect.origin.x && + rect.origin.x < screenRect.origin.x + screenRect.size.width && + rect.origin.y >= screenRect.origin.y && + rect.origin.y < screenRect.origin.y + screenRect.size.height) { + screen = candidate; + rect.origin.x -= screenRect.origin.x; + rect.origin.y -= screenRect.origin.y; } + } - @try { - nswindow = [[SDLWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:NO screen:screen]; - } - @catch (NSException *e) { - return SDL_SetError("%s", [[e reason] UTF8String]); - } + @try { + nswindow = [[SDLWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:NO screen:screen]; + } + @catch (NSException *e) { + return SDL_SetError("%s", [[e reason] UTF8String]); + } - [nswindow setColorSpace:[NSColorSpace sRGBColorSpace]]; + [nswindow setColorSpace:[NSColorSpace sRGBColorSpace]]; #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 /* Added in the 10.12.0 SDK. */ - /* By default, don't allow users to make our window tabbed in 10.12 or later */ - if ([nswindow respondsToSelector:@selector(setTabbingMode:)]) { - [nswindow setTabbingMode:NSWindowTabbingModeDisallowed]; - } + /* By default, don't allow users to make our window tabbed in 10.12 or later */ + if ([nswindow respondsToSelector:@selector(setTabbingMode:)]) { + [nswindow setTabbingMode:NSWindowTabbingModeDisallowed]; + } #endif - if (videodata.allow_spaces) { - /* we put FULLSCREEN_DESKTOP windows in their own Space, without a toggle button or menubar, later */ - if (window->flags & SDL_WINDOW_RESIZABLE) { - /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */ - [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; - } + if (videodata.allow_spaces) { + /* we put FULLSCREEN_DESKTOP windows in their own Space, without a toggle button or menubar, later */ + if (window->flags & SDL_WINDOW_RESIZABLE) { + /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */ + [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; } + } - if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { - [nswindow setLevel:NSFloatingWindowLevel]; - } + if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { + [nswindow setLevel:NSFloatingWindowLevel]; + } - /* Create a default view for this window */ - rect = [nswindow contentRectForFrameRect:[nswindow frame]]; - contentView = [[SDLView alloc] initWithFrame:rect]; - [contentView setSDLWindow:window]; + /* Create a default view for this window */ + rect = [nswindow contentRectForFrameRect:[nswindow frame]]; + contentView = [[SDLView alloc] initWithFrame:rect]; + [contentView setSDLWindow:window]; -/* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - /* Note: as of the macOS 10.15 SDK, this defaults to YES instead of NO when - * the NSHighResolutionCapable boolean is set in Info.plist. */ - highdpi = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; - [contentView setWantsBestResolutionOpenGLSurface:highdpi]; -#ifdef __clang__ -#pragma clang diagnostic pop -#endif + /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ + #ifdef __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + #endif + /* Note: as of the macOS 10.15 SDK, this defaults to YES instead of NO when + * the NSHighResolutionCapable boolean is set in Info.plist. */ + highdpi = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; + [contentView setWantsBestResolutionOpenGLSurface:highdpi]; + #ifdef __clang__ + #pragma clang diagnostic pop + #endif #if SDL_VIDEO_OPENGL_ES2 #if SDL_VIDEO_OPENGL_EGL @@ -1790,42 +1800,329 @@ int Cocoa_CreateWindow(_THIS, SDL_Window *window) _this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { [contentView setWantsLayer:TRUE]; } -} +#endif /* SDL_VIDEO_OPENGL_EGL */ +#endif /* SDL_VIDEO_OPENGL_ES2 */ + [nswindow setContentView:contentView]; -void Cocoa_SetWindowResizable(_THIS, SDL_Window *window, SDL_bool resizable) -{ - @autoreleasepool { - /* Don't set this if we're in a space! - * The window will get permanently stuck if resizable is false. - * -flibit - */ - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - Cocoa_WindowListener *listener = data.listener; - NSWindow *nswindow = data.nswindow; - SDL_VideoData *videodata = data.videodata; - if (![listener isInFullscreenSpace]) { - SetWindowStyle(window, GetWindowStyle(window)); + if (SetupWindowData(_this, window, nswindow, contentView, SDL_TRUE) < 0) { + return -1; + } + + if (!(window->flags & SDL_WINDOW_OPENGL)) { + return 0; + } + + /* The rest of this macro mess is for OpenGL or OpenGL ES windows */ +#if SDL_VIDEO_OPENGL_ES2 + if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) { +#if SDL_VIDEO_OPENGL_EGL + if (Cocoa_GLES_SetupWindow(_this, window) < 0) { + Cocoa_DestroyWindow(_this, window); + return -1; } - if (videodata.allow_spaces) { - if (resizable) { - /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */ - [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; - } else { - [nswindow setCollectionBehavior:NSWindowCollectionBehaviorManaged]; - } + return 0; +#else + return SDL_SetError("Could not create GLES window surface (EGL support not configured)"); +#endif /* SDL_VIDEO_OPENGL_EGL */ + } +#endif /* SDL_VIDEO_OPENGL_ES2 */ + return 0; +}} + +int +Cocoa_CreateWindowFrom(_THIS, SDL_Window * window, const void *data) +{ @autoreleasepool +{ + NSView* nsview = nil; + NSWindow *nswindow = nil; + NSString *title; + BOOL highdpi; + + if ([(__bridge id)data isKindOfClass:[NSWindow class]]) { + nswindow = (__bridge NSWindow*)data; + nsview = [nswindow contentView]; + } else if ([(__bridge id)data isKindOfClass:[NSView class]]) { + nsview = (__bridge NSView*)data; + nswindow = [nsview window]; + } else { + SDL_assert(false); + } + + /* Query the title from the existing window */ + title = [nswindow title]; + if (title) { + window->title = SDL_strdup([title UTF8String]); + } + + /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */ + #ifdef __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + #endif + /* Note: as of the macOS 10.15 SDK, this defaults to YES instead of NO when + * the NSHighResolutionCapable boolean is set in Info.plist. */ + highdpi = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0; + [nsview setWantsBestResolutionOpenGLSurface:highdpi]; + #ifdef __clang__ + #pragma clang diagnostic pop + #endif + + return SetupWindowData(_this, window, nswindow, nsview, SDL_FALSE); +}} + +void +Cocoa_SetWindowTitle(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + const char *title = window->title ? window->title : ""; + NSWindow *nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow; + NSString *string = [[NSString alloc] initWithUTF8String:title]; + [nswindow setTitle:string]; +}} + +void +Cocoa_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon) +{ @autoreleasepool +{ + NSImage *nsimage = Cocoa_CreateImage(icon); + + if (nsimage) { + [NSApp setApplicationIconImage:nsimage]; + } +}} + +void +Cocoa_SetWindowPosition(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata; + NSWindow *nswindow = windata.nswindow; + NSRect rect; + Uint32 moveHack; + + rect.origin.x = window->x; + rect.origin.y = window->y; + rect.size.width = window->w; + rect.size.height = window->h; + ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); + + moveHack = s_moveHack; + s_moveHack = 0; + [nswindow setFrameOrigin:rect.origin]; + s_moveHack = moveHack; + + ScheduleContextUpdates(windata); +}} + +void +Cocoa_SetWindowSize(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata; + NSWindow *nswindow = windata.nswindow; + NSRect rect; + Uint32 moveHack; + + /* Cocoa will resize the window from the bottom-left rather than the + * top-left when -[nswindow setContentSize:] is used, so we must set the + * entire frame based on the new size, in order to preserve the position. + */ + rect.origin.x = window->x; + rect.origin.y = window->y; + rect.size.width = window->w; + rect.size.height = window->h; + ConvertNSRect([nswindow screen], (window->flags & FULLSCREEN_MASK), &rect); + + moveHack = s_moveHack; + s_moveHack = 0; + [nswindow setFrame:[nswindow frameRectForContentRect:rect] display:YES]; + s_moveHack = moveHack; + + ScheduleContextUpdates(windata); +}} + +void +Cocoa_SetWindowMinimumSize(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata; + + NSSize minSize; + minSize.width = window->min_w; + minSize.height = window->min_h; + + [windata.nswindow setContentMinSize:minSize]; +}} + +void +Cocoa_SetWindowMaximumSize(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata; + + NSSize maxSize; + maxSize.width = window->max_w; + maxSize.height = window->max_h; + + [windata.nswindow setContentMaxSize:maxSize]; +}} + +void +Cocoa_GetWindowSizeInPixels(_THIS, SDL_Window * window, int *w, int *h) +{ @autoreleasepool +{ + SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata; + NSView *contentView = windata.sdlContentView; + NSRect viewport = [contentView bounds]; + + if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { + /* This gives us the correct viewport for a Retina-enabled view. */ + viewport = [contentView convertRectToBacking:viewport]; + } + + *w = viewport.size.width; + *h = viewport.size.height; +}} + + +void +Cocoa_ShowWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *windowData = ((__bridge SDL_WindowData *) window->driverdata); + NSWindow *nswindow = windowData.nswindow; + + if (![nswindow isMiniaturized]) { + [windowData.listener pauseVisibleObservation]; + [nswindow makeKeyAndOrderFront:nil]; + [windowData.listener resumeVisibleObservation]; + } +}} + +void +Cocoa_HideWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + NSWindow *nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow; + + [nswindow orderOut:nil]; +}} + +void +Cocoa_RaiseWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *windowData = ((__bridge SDL_WindowData *) window->driverdata); + NSWindow *nswindow = windowData.nswindow; + + /* makeKeyAndOrderFront: has the side-effect of deminiaturizing and showing + a minimized or hidden window, so check for that before showing it. + */ + [windowData.listener pauseVisibleObservation]; + if (![nswindow isMiniaturized] && [nswindow isVisible]) { + [NSApp activateIgnoringOtherApps:YES]; + [nswindow makeKeyAndOrderFront:nil]; + } + [windowData.listener resumeVisibleObservation]; +}} + +void +Cocoa_MaximizeWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata; + NSWindow *nswindow = windata.nswindow; + + [nswindow zoom:nil]; + + ScheduleContextUpdates(windata); +}} + +void +Cocoa_MinimizeWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; + NSWindow *nswindow = data.nswindow; + if ([data.listener isInFullscreenSpaceTransition]) { + [data.listener addPendingWindowOperation:PENDING_OPERATION_MINIMIZE]; + } else { + [nswindow miniaturize:nil]; + } +}} + +void +Cocoa_RestoreWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + NSWindow *nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow; + + if ([nswindow isMiniaturized]) { + [nswindow deminiaturize:nil]; + } else if ((window->flags & SDL_WINDOW_RESIZABLE) && [nswindow isZoomed]) { + [nswindow zoom:nil]; + } +}} + +void +Cocoa_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered) +{ @autoreleasepool +{ + if (SetWindowStyle(window, GetWindowStyle(window))) { + if (bordered) { + Cocoa_SetWindowTitle(_this, window); /* this got blanked out. */ } } -} +}} -void Cocoa_SetWindowAlwaysOnTop(_THIS, SDL_Window *window, SDL_bool on_top) +void +Cocoa_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable) +{ @autoreleasepool { - @autoreleasepool { - NSWindow *nswindow = ((__bridge SDL_WindowData *)window->driverdata).nswindow; + /* Don't set this if we're in a space! + * The window will get permanently stuck if resizable is false. + * -flibit + */ + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; + Cocoa_WindowListener *listener = data.listener; + NSWindow *nswindow = data.nswindow; + SDL_VideoData *videodata = data.videodata; + if (![listener isInFullscreenSpace]) { + SetWindowStyle(window, GetWindowStyle(window)); + } + if (videodata.allow_spaces) { + if (resizable) { + /* resizable windows are Spaces-friendly: they get the "go fullscreen" toggle button on their titlebar. */ + [nswindow setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; + } else { + [nswindow setCollectionBehavior:NSWindowCollectionBehaviorManaged]; + } + } +}} + +void +Cocoa_SetWindowAlwaysOnTop(_THIS, SDL_Window * window, SDL_bool on_top) +{ @autoreleasepool + { + NSWindow *nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow; if (on_top) { [nswindow setLevel:NSFloatingWindowLevel]; } else { [nswindow setLevel:kCGNormalWindowLevel]; } + }} + +void +Cocoa_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen) +{ @autoreleasepool +{ + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; + NSWindow *nswindow = data.nswindow; + NSRect rect; + + /* The view responder chain gets messed with during setStyleMask */ + if ([data.sdlContentView nextResponder] == data.listener) { + [data.sdlContentView setNextResponder:nil]; } if (fullscreen) { @@ -2037,27 +2334,54 @@ Cocoa_SetWindowMouseRect(_THIS, SDL_Window * window) Cocoa_UpdateClipCursor(window); } -void Cocoa_SetWindowFullscreen(_THIS, SDL_Window *window, SDL_VideoDisplay *display, SDL_bool fullscreen) +void +Cocoa_SetWindowMouseGrab(_THIS, SDL_Window * window, SDL_bool grabbed) +{ @autoreleasepool { - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - NSWindow *nswindow = data.nswindow; - NSRect rect; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; - /* The view responder chain gets messed with during setStyleMask */ - if ([data.sdlContentView nextResponder] == data.listener) { - [data.sdlContentView setNextResponder:nil]; + Cocoa_UpdateClipCursor(window); + + if (data && (window->flags & SDL_WINDOW_FULLSCREEN)) { + if (SDL_ShouldAllowTopmost() && (window->flags & SDL_WINDOW_INPUT_FOCUS) + && ![data.listener isInFullscreenSpace]) { + /* OpenGL is rendering to the window, so make it visible! */ + /* Doing this in 10.11 while in a Space breaks things (bug #3152) */ + [data.nswindow setLevel:CGShieldingWindowLevel()]; + } else if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { + [data.nswindow setLevel:NSFloatingWindowLevel]; + } else { + [data.nswindow setLevel:kCGNormalWindowLevel]; + } + } +}} + +void +Cocoa_DestroyWindow(_THIS, SDL_Window * window) +{ @autoreleasepool +{ + SDL_WindowData *data = (SDL_WindowData *) CFBridgingRelease(window->driverdata); + + if (data) { + NSArray *contexts; + if ([data.listener isInFullscreenSpace]) { + [NSMenu setMenuBarVisible:YES]; + } + [data.listener close]; + data.listener = nil; + if (data.created) { + /* Release the content view to avoid further updateLayer callbacks */ + [data.nswindow setContentView:nil]; + [data.nswindow close]; } - if (fullscreen) { - SDL_Rect bounds; + #if SDL_VIDEO_OPENGL - Cocoa_GetDisplayBounds(_this, display, &bounds); - rect.origin.x = bounds.x; - rect.origin.y = bounds.y; - rect.size.width = bounds.w; - rect.size.height = bounds.h; - ConvertNSRect([nswindow screen], fullscreen, &rect); + contexts = [data.nscontexts copy]; + for (SDLOpenGLContext *context in contexts) { + /* Calling setWindow:NULL causes the context to remove itself from the context list. */ + [context setWindow:NULL]; + } #endif /* SDL_VIDEO_OPENGL */ @@ -2119,333 +2443,84 @@ Cocoa_SetWindowFullscreenSpace(SDL_Window * window, SDL_bool state) /* Wait for the transition to complete, so application changes take effect properly (e.g. setting the window size, etc.) */ - if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_14) { - NSRect screenRect = [[nswindow screen] frame]; - if (screenRect.size.height >= 1.0f) { - rect.origin.y += (screenRect.size.height - rect.size.height); - } - } - - [nswindow setStyleMask:NSWindowStyleMaskBorderless]; - } else { - NSRect frameRect; - rect.origin.x = window->windowed.x; - rect.origin.y = window->windowed.y; - rect.size.width = window->windowed.w; - rect.size.height = window->windowed.h; - ConvertNSRect([nswindow screen], fullscreen, &rect); - - /* The window is not meant to be fullscreen, but its flags might have a - * fullscreen bit set if it's scheduled to go fullscreen immediately - * after. Always using the windowed mode style here works around bugs in - * macOS 10.15 where the window doesn't properly restore the windowed - * mode decorations after exiting fullscreen-desktop, when the window - * was created as fullscreen-desktop. */ - [nswindow setStyleMask:GetWindowWindowedStyle(window)]; - - /* Hack to restore window decorations on macOS 10.10 */ - frameRect = [nswindow frame]; - [nswindow setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO]; - [nswindow setFrame:frameRect display:NO]; - } - - /* The view responder chain gets messed with during setStyleMask */ - if ([data.sdlContentView nextResponder] != data.listener) { - [data.sdlContentView setNextResponder:data.listener]; - } - - s_moveHack = 0; - [nswindow setContentSize:rect.size]; - [nswindow setFrameOrigin:rect.origin]; - s_moveHack = SDL_GetTicks(); - - /* When the window style changes the title is cleared */ - if (!fullscreen) { - Cocoa_SetWindowTitle(_this, window); - } - - if (SDL_ShouldAllowTopmost() && fullscreen) { - /* OpenGL is rendering to the window, so make it visible! */ - [nswindow setLevel:CGShieldingWindowLevel()]; - } else if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { - [nswindow setLevel:NSFloatingWindowLevel]; - } else { - [nswindow setLevel:kCGNormalWindowLevel]; - } - - if ([nswindow isVisible] || fullscreen) { - [data.listener pauseVisibleObservation]; - [nswindow makeKeyAndOrderFront:nil]; - [data.listener resumeVisibleObservation]; - } - - ScheduleContextUpdates(data); - } -} - -void * -Cocoa_GetWindowICCProfile(_THIS, SDL_Window *window, size_t *size) -{ - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - NSWindow *nswindow = data.nswindow; - NSScreen *screen = [nswindow screen]; - NSData *iccProfileData = nil; - void *retIccProfileData = NULL; - - if (screen == nil) { - SDL_SetError("Could not get screen of window."); - return NULL; - } - - if ([screen colorSpace] == nil) { - SDL_SetError("Could not get colorspace information of screen."); - return NULL; - } - - iccProfileData = [[screen colorSpace] ICCProfileData]; - if (iccProfileData == nil) { - SDL_SetError("Could not get ICC profile data."); - return NULL; - } - - retIccProfileData = SDL_malloc([iccProfileData length]); - if (!retIccProfileData) { - SDL_OutOfMemory(); - return NULL; - } - - [iccProfileData getBytes:retIccProfileData length:[iccProfileData length]]; - *size = [iccProfileData length]; - return retIccProfileData; - } -} - -int Cocoa_GetWindowDisplayIndex(_THIS, SDL_Window *window) -{ - @autoreleasepool { - NSScreen *screen; - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - - /* Not recognized via CHECK_WINDOW_MAGIC */ - if (data == nil) { - /* Don't set the error here, it hides other errors and is ignored anyway */ - /*return SDL_SetError("Window data not set");*/ - return -1; - } - - /* NSWindow.screen may be nil when the window is off-screen. */ - screen = data.nswindow.screen; - - if (screen != nil) { - CGDirectDisplayID displayid; - int i; - - /* https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc */ - displayid = [[screen.deviceDescription objectForKey:@"NSScreenNumber"] unsignedIntValue]; - - for (i = 0; i < _this->num_displays; i++) { - SDL_DisplayData *displaydata = (SDL_DisplayData *)_this->displays[i].driverdata; - if (displaydata != NULL && displaydata->display == displayid) { - return i; - } - } - } - - /* Other code may expect SDL_GetWindowDisplayIndex to always return a valid - * index for a window. The higher level GetWindowDisplayIndex code will fall - * back to a generic position-based query if the backend implementation - * fails. */ - return SDL_SetError("Couldn't find the display where the window is located."); - } -} - -void Cocoa_SetWindowMouseRect(_THIS, SDL_Window *window) -{ - Cocoa_UpdateClipCursor(window); -} - -void Cocoa_SetWindowMouseGrab(_THIS, SDL_Window *window, SDL_bool grabbed) -{ - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - - Cocoa_UpdateClipCursor(window); - - if (data && (window->flags & SDL_WINDOW_FULLSCREEN)) { - if (SDL_ShouldAllowTopmost() && (window->flags & SDL_WINDOW_INPUT_FOCUS) && ![data.listener isInFullscreenSpace]) { - /* OpenGL is rendering to the window, so make it visible! */ - /* Doing this in 10.11 while in a Space breaks things (bug #3152) */ - [data.nswindow setLevel:CGShieldingWindowLevel()]; - } else if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) { - [data.nswindow setLevel:NSFloatingWindowLevel]; - } else { - [data.nswindow setLevel:kCGNormalWindowLevel]; - } - } - } -} - -void Cocoa_DestroyWindow(_THIS, SDL_Window *window) -{ - @autoreleasepool { - SDL_WindowData *data = (SDL_WindowData *)CFBridgingRelease(window->driverdata); - - if (data) { - NSArray *contexts; - if ([data.listener isInFullscreenSpace]) { - [NSMenu setMenuBarVisible:YES]; - } - [data.listener close]; - data.listener = nil; - if (data.created) { - /* Release the content view to avoid further updateLayer callbacks */ - [data.nswindow setContentView:nil]; - [data.nswindow close]; - } - -#if SDL_VIDEO_OPENGL - - contexts = [data.nscontexts copy]; - for (SDLOpenGLContext *context in contexts) { - /* Calling setWindow:NULL causes the context to remove itself from the context list. */ - [context setWindow:NULL]; - } - -#endif /* SDL_VIDEO_OPENGL */ - - if (window->shaper) { - CFBridgingRelease(window->shaper->driverdata); - SDL_free(window->shaper); - window->shaper = NULL; - } - } - window->driverdata = NULL; - } -} - -int Cocoa_GetWindowWMInfo(_THIS, SDL_Window *window, SDL_SysWMinfo *info) -{ - @autoreleasepool { - NSWindow *nswindow = ((__bridge SDL_WindowData *)window->driverdata).nswindow; - - info->subsystem = SDL_SYSWM_COCOA; - info->info.cocoa.window = nswindow; - return 0; - } -} - -SDL_bool -Cocoa_IsWindowInFullscreenSpace(SDL_Window *window) -{ - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - - if ([data.listener isInFullscreenSpace]) { - return SDL_TRUE; - } else { - return SDL_FALSE; - } - } -} - -SDL_bool -Cocoa_SetWindowFullscreenSpace(SDL_Window *window, SDL_bool state) -{ - @autoreleasepool { - SDL_bool succeeded = SDL_FALSE; - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - - if (data.inWindowFullscreenTransition) { - return SDL_FALSE; - } - - data.inWindowFullscreenTransition = SDL_TRUE; - if ([data.listener setFullscreenSpace:(state ? YES : NO)]) { - const int maxattempts = 3; - int attempt = 0; - while (++attempt <= maxattempts) { - /* Wait for the transition to complete, so application changes - take effect properly (e.g. setting the window size, etc.) - */ - const int limit = 10000; - int count = 0; - while ([data.listener isInFullscreenSpaceTransition]) { - if (++count == limit) { - /* Uh oh, transition isn't completing. Should we assert? */ - break; - } - SDL_Delay(1); - SDL_PumpEvents(); - } - if ([data.listener isInFullscreenSpace] == (state ? YES : NO)) + const int limit = 10000; + int count = 0; + while ([data.listener isInFullscreenSpaceTransition]) { + if ( ++count == limit ) { + /* Uh oh, transition isn't completing. Should we assert? */ break; - /* Try again, the last attempt was interrupted by user gestures */ - if (![data.listener setFullscreenSpace:(state ? YES : NO)]) - break; /* ??? */ + } + SDL_Delay(1); + SDL_PumpEvents(); } - /* Return TRUE to prevent non-space fullscreen logic from running */ - succeeded = SDL_TRUE; + if ([data.listener isInFullscreenSpace] == (state ? YES : NO)) + break; + /* Try again, the last attempt was interrupted by user gestures */ + if (![data.listener setFullscreenSpace:(state ? YES : NO)]) + break; /* ??? */ } - data.inWindowFullscreenTransition = SDL_FALSE; - - return succeeded; + /* Return TRUE to prevent non-space fullscreen logic from running */ + succeeded = SDL_TRUE; } + data.inWindowFullscreenTransition = SDL_FALSE; + + return succeeded; +}} + +int +Cocoa_SetWindowHitTest(SDL_Window * window, SDL_bool enabled) +{ + return 0; /* just succeed, the real work is done elsewhere. */ } -int Cocoa_SetWindowHitTest(SDL_Window *window, SDL_bool enabled) +void +Cocoa_AcceptDragAndDrop(SDL_Window * window, SDL_bool accept) +{ @autoreleasepool { - return 0; /* just succeed, the real work is done elsewhere. */ -} - -void Cocoa_AcceptDragAndDrop(SDL_Window *window, SDL_bool accept) -{ - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - if (accept) { - [data.nswindow registerForDraggedTypes:[NSArray arrayWithObject:(NSString *)kUTTypeFileURL]]; - } else { - [data.nswindow unregisterDraggedTypes]; - } + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; + if (accept) { + [data.nswindow registerForDraggedTypes:[NSArray arrayWithObject:(NSString *)kUTTypeFileURL]]; + } else { + [data.nswindow unregisterDraggedTypes]; } -} +}} -int Cocoa_FlashWindow(_THIS, SDL_Window *window, SDL_FlashOperation operation) +int +Cocoa_FlashWindow(_THIS, SDL_Window *window, SDL_FlashOperation operation) +{ @autoreleasepool { - @autoreleasepool { - /* Note that this is app-wide and not window-specific! */ - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + /* Note that this is app-wide and not window-specific! */ + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; - if (data.flash_request) { - [NSApp cancelUserAttentionRequest:data.flash_request]; - data.flash_request = 0; - } - - switch (operation) { - case SDL_FLASH_CANCEL: - /* Canceled above */ - break; - case SDL_FLASH_BRIEFLY: - data.flash_request = [NSApp requestUserAttention:NSInformationalRequest]; - break; - case SDL_FLASH_UNTIL_FOCUSED: - data.flash_request = [NSApp requestUserAttention:NSCriticalRequest]; - break; - default: - return SDL_Unsupported(); - } - return 0; + if (data.flash_request) { + [NSApp cancelUserAttentionRequest:data.flash_request]; + data.flash_request = 0; } -} -int Cocoa_SetWindowOpacity(_THIS, SDL_Window *window, float opacity) + switch (operation) { + case SDL_FLASH_CANCEL: + /* Canceled above */ + break; + case SDL_FLASH_BRIEFLY: + data.flash_request = [NSApp requestUserAttention:NSInformationalRequest]; + break; + case SDL_FLASH_UNTIL_FOCUSED: + data.flash_request = [NSApp requestUserAttention:NSCriticalRequest]; + break; + default: + return SDL_Unsupported(); + } + return 0; +}} + +int +Cocoa_SetWindowOpacity(_THIS, SDL_Window * window, float opacity) +{ @autoreleasepool { - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - [data.nswindow setAlphaValue:opacity]; - return 0; - } -} + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; + [data.nswindow setAlphaValue:opacity]; + return 0; +}} #endif /* SDL_VIDEO_DRIVER_COCOA */ diff --git a/src/video/uikit/SDL_uikitappdelegate.h b/src/video/uikit/SDL_uikitappdelegate.h index f734ce247..ee2b5b6a8 100644 --- a/src/video/uikit/SDL_uikitappdelegate.h +++ b/src/video/uikit/SDL_uikitappdelegate.h @@ -29,7 +29,7 @@ @end -@interface SDLUIKitDelegate : NSObject +@interface SDLUIKitDelegate : NSObject + (id)sharedAppDelegate; + (NSString *)getAppDelegateClassName; @@ -40,7 +40,7 @@ * the app's UI is storyboard-based. SDL is not storyboard-based, however * several major third-party ad APIs (e.g. Google admob) incorrectly assume this * property always exists, and will crash if it doesn't. */ -@property(nonatomic) UIWindow *window; +@property (nonatomic) UIWindow *window; @end diff --git a/src/video/uikit/SDL_uikitappdelegate.m b/src/video/uikit/SDL_uikitappdelegate.m index be0d6f745..3186cc6e8 100644 --- a/src/video/uikit/SDL_uikitappdelegate.m +++ b/src/video/uikit/SDL_uikitappdelegate.m @@ -36,9 +36,9 @@ #if !TARGET_OS_TV #include -#ifndef __IPHONE_13_0 -#define __IPHONE_13_0 130000 -#endif +# ifndef __IPHONE_13_0 +# define __IPHONE_13_0 130000 +# endif #endif #ifdef main @@ -57,9 +57,9 @@ int SDL_UIKitRunApp(int argc, char *argv[], SDL_main_func mainFunction) /* store arguments */ forward_main = mainFunction; forward_argc = argc; - forward_argv = (char **)malloc((argc + 1) * sizeof(char *)); + forward_argv = (char **)malloc((argc+1) * sizeof(char *)); for (i = 0; i < argc; i++) { - forward_argv[i] = malloc((strlen(argv[i]) + 1) * sizeof(char)); + forward_argv[i] = malloc( (strlen(argv[i])+1) * sizeof(char)); strcpy(forward_argv[i], argv[i]); } forward_argv[i] = NULL; @@ -87,7 +87,8 @@ SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldVa #if !TARGET_OS_TV /* Load a launch image using the old UILaunchImageFile-era naming rules. */ -static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh) +static UIImage * +SDL_LoadLaunchImageNamed(NSString *name, int screenh) { UIInterfaceOrientation curorient = [UIApplication sharedApplication].statusBarOrientation; UIUserInterfaceIdiom idiom = [UIDevice currentDevice].userInterfaceIdiom; @@ -125,21 +126,19 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh) } @interface SDLLaunchStoryboardViewController : UIViewController -@property(nonatomic, strong) UIViewController *storyboardViewController; +@property (nonatomic, strong) UIViewController *storyboardViewController; - (instancetype)initWithStoryboardViewController:(UIViewController *)storyboardViewController; @end @implementation SDLLaunchStoryboardViewController -- (instancetype)initWithStoryboardViewController:(UIViewController *)storyboardViewController -{ +- (instancetype)initWithStoryboardViewController:(UIViewController *)storyboardViewController { self = [super init]; self.storyboardViewController = storyboardViewController; return self; } -- (void)viewDidLoad -{ +- (void)viewDidLoad { [super viewDidLoad]; [self addChildViewController:self.storyboardViewController]; @@ -152,13 +151,11 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh) UIApplication.sharedApplication.statusBarStyle = self.preferredStatusBarStyle; } -- (BOOL)prefersStatusBarHidden -{ +- (BOOL)prefersStatusBarHidden { return [[NSBundle.mainBundle objectForInfoDictionaryKey:@"UIStatusBarHidden"] boolValue]; } -- (UIStatusBarStyle)preferredStatusBarStyle -{ +- (UIStatusBarStyle)preferredStatusBarStyle { NSString *statusBarStyle = [NSBundle.mainBundle objectForInfoDictionaryKey:@"UIStatusBarStyle"]; if ([statusBarStyle isEqualToString:@"UIStatusBarStyleLightContent"]) { return UIStatusBarStyleLightContent; @@ -347,8 +344,7 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh) @end -@implementation SDLUIKitDelegate -{ +@implementation SDLUIKitDelegate { UIWindow *launchWindow; } @@ -379,14 +375,12 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh) launchWindow = nil; /* Do a nice animated fade-out (roughly matches the real launch behavior.) */ - [UIView animateWithDuration:0.2 - animations:^{ - window.alpha = 0.0; - } - completion:^(BOOL finished) { - window.hidden = YES; - UIKit_ForceUpdateHomeIndicator(); /* Wait for launch screen to hide so settings are applied to the actual view controller. */ - }]; + [UIView animateWithDuration:0.2 animations:^{ + window.alpha = 0.0; + } completion:^(BOOL finished) { + window.hidden = YES; + UIKit_ForceUpdateHomeIndicator(); /* Wait for launch screen to hide so settings are applied to the actual view controller. */ + }]; } - (void)postFinishLaunch @@ -482,7 +476,7 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh) if (_this) { SDL_Window *window = NULL; for (window = _this->windows; window != NULL; window = window->next) { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; if (data != nil) { return data.uiwindow; } @@ -509,7 +503,7 @@ static UIImage *SDL_LoadLaunchImageNamed(NSString *name, int screenh) #if TARGET_OS_TV || (defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_9_0) -- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options +- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { /* TODO: Handle options */ [self sendDropFileForURL:url]; diff --git a/src/video/uikit/SDL_uikitclipboard.m b/src/video/uikit/SDL_uikitclipboard.m index 1ecce72b0..dde939dfb 100644 --- a/src/video/uikit/SDL_uikitclipboard.m +++ b/src/video/uikit/SDL_uikitclipboard.m @@ -27,7 +27,8 @@ #import -int UIKit_SetClipboardText(_THIS, const char *text) +int +UIKit_SetClipboardText(_THIS, const char *text) { #if TARGET_OS_TV return SDL_SetError("The clipboard is not available on tvOS"); @@ -71,29 +72,31 @@ UIKit_HasClipboardText(_THIS) } } -void UIKit_InitClipboard(_THIS) +void +UIKit_InitClipboard(_THIS) { #if !TARGET_OS_TV @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; id observer = [center addObserverForName:UIPasteboardChangedNotification - object:nil - queue:nil - usingBlock:^(NSNotification *note) { - SDL_SendClipboardUpdate(); - }]; + object:nil + queue:nil + usingBlock:^(NSNotification *note) { + SDL_SendClipboardUpdate(); + }]; data.pasteboardObserver = observer; } #endif } -void UIKit_QuitClipboard(_THIS) +void +UIKit_QuitClipboard(_THIS) { @autoreleasepool { - SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata; + SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata; if (data.pasteboardObserver != nil) { [[NSNotificationCenter defaultCenter] removeObserver:data.pasteboardObserver]; diff --git a/src/video/uikit/SDL_uikitevents.m b/src/video/uikit/SDL_uikitevents.m index 95943ccc8..e1bc5a29e 100644 --- a/src/video/uikit/SDL_uikitevents.m +++ b/src/video/uikit/SDL_uikitevents.m @@ -41,8 +41,9 @@ static BOOL UIKit_EventPumpEnabled = YES; + @interface SDL_LifecycleObserver : NSObject -@property(nonatomic, assign) BOOL isObservingNotifications; +@property (nonatomic, assign) BOOL isObservingNotifications; @end @implementation SDL_LifecycleObserver @@ -59,10 +60,7 @@ static BOOL UIKit_EventPumpEnabled = YES; [notificationCenter addObserver:self selector:@selector(applicationWillTerminate) name:UIApplicationWillTerminateNotification object:nil]; [notificationCenter addObserver:self selector:@selector(applicationDidReceiveMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; #if !TARGET_OS_TV - [notificationCenter addObserver:self - selector:@selector(applicationDidChangeStatusBarOrientation) - name:UIApplicationDidChangeStatusBarOrientationNotification - object:nil]; + [notificationCenter addObserver:self selector:@selector(applicationDidChangeStatusBarOrientation) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; #endif } else if (!UIKit_EventPumpEnabled && self.isObservingNotifications) { self.isObservingNotifications = NO; @@ -109,19 +107,22 @@ static BOOL UIKit_EventPumpEnabled = YES; @end -void SDL_iPhoneSetEventPump(SDL_bool enabled) + +void +SDL_iPhoneSetEventPump(SDL_bool enabled) { UIKit_EventPumpEnabled = enabled; static SDL_LifecycleObserver *lifecycleObserver; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - lifecycleObserver = [SDL_LifecycleObserver new]; + lifecycleObserver = [SDL_LifecycleObserver new]; }); [lifecycleObserver eventPumpChanged]; } -void UIKit_PumpEvents(_THIS) +void +UIKit_PumpEvents(_THIS) { if (!UIKit_EventPumpEnabled) { return; @@ -144,7 +145,7 @@ void UIKit_PumpEvents(_THIS) /* Make sure UIScrollView objects scroll properly. */ do { result = CFRunLoopRunInMode((CFStringRef)UITrackingRunLoopMode, seconds, TRUE); - } while (result == kCFRunLoopRunHandledSource); + } while(result == kCFRunLoopRunHandledSource); /* See the comment in the function definition. */ #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 @@ -161,12 +162,13 @@ static id keyboard_disconnect_observer = nil; static void OnGCKeyboardConnected(GCKeyboard *keyboard) API_AVAILABLE(macos(11.0), ios(14.0), tvos(14.0)) { keyboard_connected = SDL_TRUE; - keyboard.keyboardInput.keyChangedHandler = ^(GCKeyboardInput *kbrd, GCControllerButtonInput *key, GCKeyCode keyCode, BOOL pressed) { - SDL_SendKeyboardKey(pressed ? SDL_PRESSED : SDL_RELEASED, (SDL_Scancode)keyCode); + keyboard.keyboardInput.keyChangedHandler = ^(GCKeyboardInput *kbrd, GCControllerButtonInput *key, GCKeyCode keyCode, BOOL pressed) + { + SDL_SendKeyboardKey(pressed ? SDL_PRESSED : SDL_RELEASED, (SDL_Scancode)keyCode); }; - dispatch_queue_t queue = dispatch_queue_create("org.libsdl.input.keyboard", DISPATCH_QUEUE_SERIAL); - dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)); + dispatch_queue_t queue = dispatch_queue_create( "org.libsdl.input.keyboard", DISPATCH_QUEUE_SERIAL ); + dispatch_set_target_queue( queue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) ); keyboard.handlerQueue = queue; } @@ -186,16 +188,16 @@ void SDL_InitGCKeyboard(void) object:nil queue:nil usingBlock:^(NSNotification *note) { - GCKeyboard *keyboard = note.object; - OnGCKeyboardConnected(keyboard); + GCKeyboard *keyboard = note.object; + OnGCKeyboardConnected(keyboard); }]; keyboard_disconnect_observer = [center addObserverForName:GCKeyboardDidDisconnectNotification object:nil queue:nil usingBlock:^(NSNotification *note) { - GCKeyboard *keyboard = note.object; - OnGCKeyboardDisconnected(keyboard); + GCKeyboard *keyboard = note.object; + OnGCKeyboardDisconnected(keyboard); }]; if (GCKeyboard.coalescedKeyboard != nil) { @@ -250,6 +252,7 @@ void SDL_QuitGCKeyboard(void) #endif /* ENABLE_GCKEYBOARD */ + #ifdef ENABLE_GCMOUSE static int mice_connected = 0; @@ -283,36 +286,42 @@ static void OnGCMouseConnected(GCMouse *mouse) API_AVAILABLE(macos(11.0), ios(14 { SDL_MouseID mouseID = mice_connected; - mouse.mouseInput.leftButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) { - OnGCMouseButtonChanged(mouseID, SDL_BUTTON_LEFT, pressed); + mouse.mouseInput.leftButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) + { + OnGCMouseButtonChanged(mouseID, SDL_BUTTON_LEFT, pressed); }; - mouse.mouseInput.middleButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) { - OnGCMouseButtonChanged(mouseID, SDL_BUTTON_MIDDLE, pressed); + mouse.mouseInput.middleButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) + { + OnGCMouseButtonChanged(mouseID, SDL_BUTTON_MIDDLE, pressed); }; - mouse.mouseInput.rightButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) { - OnGCMouseButtonChanged(mouseID, SDL_BUTTON_RIGHT, pressed); + mouse.mouseInput.rightButton.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) + { + OnGCMouseButtonChanged(mouseID, SDL_BUTTON_RIGHT, pressed); }; int auxiliary_button = SDL_BUTTON_X1; for (GCControllerButtonInput *btn in mouse.mouseInput.auxiliaryButtons) { - btn.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) { - OnGCMouseButtonChanged(mouseID, auxiliary_button, pressed); + btn.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL pressed) + { + OnGCMouseButtonChanged(mouseID, auxiliary_button, pressed); }; ++auxiliary_button; } - mouse.mouseInput.mouseMovedHandler = ^(GCMouseInput *mouseInput, float deltaX, float deltaY) { - if (SDL_GCMouseRelativeMode()) { - SDL_SendMouseMotion(SDL_GetMouseFocus(), mouseID, 1, (int)deltaX, -(int)deltaY); - } + mouse.mouseInput.mouseMovedHandler = ^(GCMouseInput *mouseInput, float deltaX, float deltaY) + { + if (SDL_GCMouseRelativeMode()) { + SDL_SendMouseMotion(SDL_GetMouseFocus(), mouseID, 1, (int)deltaX, -(int)deltaY); + } }; - mouse.mouseInput.scroll.valueChangedHandler = ^(GCControllerDirectionPad *dpad, float xValue, float yValue) { - SDL_SendMouseWheel(SDL_GetMouseFocus(), 0, xValue, yValue, SDL_MOUSEWHEEL_NORMAL); + mouse.mouseInput.scroll.valueChangedHandler = ^(GCControllerDirectionPad *dpad, float xValue, float yValue) + { + SDL_SendMouseWheel(SDL_GetMouseFocus(), 0, xValue, yValue, SDL_MOUSEWHEEL_NORMAL); }; - dispatch_queue_t queue = dispatch_queue_create("org.libsdl.input.mouse", DISPATCH_QUEUE_SERIAL); - dispatch_set_target_queue(queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)); + dispatch_queue_t queue = dispatch_queue_create( "org.libsdl.input.mouse", DISPATCH_QUEUE_SERIAL ); + dispatch_set_target_queue( queue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) ); mouse.handlerQueue = queue; ++mice_connected; @@ -353,17 +362,17 @@ void SDL_InitGCMouse(void) object:nil queue:nil usingBlock:^(NSNotification *note) { - GCMouse *mouse = note.object; - OnGCMouseConnected(mouse); + GCMouse *mouse = note.object; + OnGCMouseConnected(mouse); }]; mouse_disconnect_observer = [center addObserverForName:GCMouseDidDisconnectNotification object:nil queue:nil usingBlock:^(NSNotification *note) { - GCMouse *mouse = note.object; - OnGCMouseDisconnected(mouse); - }]; + GCMouse *mouse = note.object; + OnGCMouseDisconnected(mouse); + }]; for (GCMouse *mouse in [GCMouse mice]) { OnGCMouseConnected(mouse); diff --git a/src/video/uikit/SDL_uikitmessagebox.m b/src/video/uikit/SDL_uikitmessagebox.m index 354a66b8d..2c42ba746 100644 --- a/src/video/uikit/SDL_uikitmessagebox.m +++ b/src/video/uikit/SDL_uikitmessagebox.m @@ -36,7 +36,8 @@ UIKit_ShowingMessageBox(void) return s_showingMessageBox; } -static void UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messageboxdata, int *clickedindex) +static void +UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messageboxdata, int *clickedindex) { *clickedindex = messageboxdata->numbuttons; @@ -51,7 +52,8 @@ static void UIKit_WaitUntilMessageBoxClosed(const SDL_MessageBoxData *messagebox } } -static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messageboxdata, int *buttonid) +static BOOL +UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messageboxdata, int *buttonid) { int i; int __block clickedindex = messageboxdata->numbuttons; @@ -83,10 +85,10 @@ static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messag } action = [UIAlertAction actionWithTitle:@(sdlButton->text) - style:style - handler:^(UIAlertAction *alertAction) { - clickedindex = (int)(sdlButton - messageboxdata->buttons); - }]; + style:style + handler:^(UIAlertAction *alertAction) { + clickedindex = (int)(sdlButton - messageboxdata->buttons); + }]; [alert addAction:action]; if (sdlButton->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT) { @@ -95,7 +97,7 @@ static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messag } if (messageboxdata->window) { - SDL_WindowData *data = (__bridge SDL_WindowData *)messageboxdata->window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) messageboxdata->window->driverdata; window = data.uiwindow; } @@ -122,32 +124,30 @@ static BOOL UIKit_ShowMessageBoxAlertController(const SDL_MessageBoxData *messag return YES; } -static void UIKit_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue) +static void +UIKit_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue) +{ @autoreleasepool { - @autoreleasepool { - if (UIKit_ShowMessageBoxAlertController(messageboxdata, buttonid)) { - *returnValue = 0; - } else { - *returnValue = SDL_SetError("Could not show message box."); - } + if (UIKit_ShowMessageBoxAlertController(messageboxdata, buttonid)) { + *returnValue = 0; + } else { + *returnValue = SDL_SetError("Could not show message box."); } -} +}} -int UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) +int +UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) +{ @autoreleasepool { - @autoreleasepool { - __block int returnValue = 0; + __block int returnValue = 0; - if ([NSThread isMainThread]) { - UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); - } else { - dispatch_sync(dispatch_get_main_queue(), ^{ - UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); - }); - } - return returnValue; + if ([NSThread isMainThread]) { + UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); + } else { + dispatch_sync(dispatch_get_main_queue(), ^{ UIKit_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); }); } -} + return returnValue; +}} #endif /* SDL_VIDEO_DRIVER_UIKIT */ diff --git a/src/video/uikit/SDL_uikitmetalview.h b/src/video/uikit/SDL_uikitmetalview.h index fc0cc70b5..a4d7026d8 100644 --- a/src/video/uikit/SDL_uikitmetalview.h +++ b/src/video/uikit/SDL_uikitmetalview.h @@ -1,15 +1,15 @@ /* Simple DirectMedia Layer Copyright (C) 1997-2022 Sam Lantinga - + This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. - + Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - + 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be @@ -38,6 +38,7 @@ #import #import + @interface SDL_uikitmetalview : SDL_uikitview - (instancetype)initWithFrame:(CGRect)frame @@ -45,10 +46,10 @@ @end -SDL_MetalView UIKit_Metal_CreateView(_THIS, SDL_Window *window); +SDL_MetalView UIKit_Metal_CreateView(_THIS, SDL_Window * window); void UIKit_Metal_DestroyView(_THIS, SDL_MetalView view); void *UIKit_Metal_GetLayer(_THIS, SDL_MetalView view); -void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h); +void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h); #endif /* SDL_VIDEO_DRIVER_UIKIT && (SDL_VIDEO_VULKAN || SDL_VIDEO_METAL) */ diff --git a/src/video/uikit/SDL_uikitmetalview.m b/src/video/uikit/SDL_uikitmetalview.m index e2599f08b..e2e7015e7 100644 --- a/src/video/uikit/SDL_uikitmetalview.m +++ b/src/video/uikit/SDL_uikitmetalview.m @@ -1,15 +1,15 @@ /* Simple DirectMedia Layer Copyright (C) 1997-2022 Sam Lantinga - + This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. - + Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - + 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be @@ -75,63 +75,59 @@ @end SDL_MetalView -UIKit_Metal_CreateView(_THIS, SDL_Window *window) -{ - @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - CGFloat scale = 1.0; - SDL_uikitmetalview *metalview; +UIKit_Metal_CreateView(_THIS, SDL_Window * window) +{ @autoreleasepool { + SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + CGFloat scale = 1.0; + SDL_uikitmetalview *metalview; - if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { - /* Set the scale to the natural scale factor of the screen - then - * the backing dimensions of the Metal view will match the pixel - * dimensions of the screen rather than the dimensions in points - * yielding high resolution on retine displays. - */ - scale = data.uiwindow.screen.nativeScale; - } - - metalview = [[SDL_uikitmetalview alloc] initWithFrame:data.uiwindow.bounds - scale:scale]; - if (metalview == nil) { - SDL_OutOfMemory(); - return NULL; - } - - [metalview setSDLWindow:window]; - - return (void *)CFBridgingRetain(metalview); + if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { + /* Set the scale to the natural scale factor of the screen - then + * the backing dimensions of the Metal view will match the pixel + * dimensions of the screen rather than the dimensions in points + * yielding high resolution on retine displays. + */ + scale = data.uiwindow.screen.nativeScale; } -} -void UIKit_Metal_DestroyView(_THIS, SDL_MetalView view) -{ - @autoreleasepool { - SDL_uikitmetalview *metalview = CFBridgingRelease(view); - - if ([metalview isKindOfClass:[SDL_uikitmetalview class]]) { - [metalview setSDLWindow:NULL]; - } + metalview = [[SDL_uikitmetalview alloc] initWithFrame:data.uiwindow.bounds + scale:scale]; + if (metalview == nil) { + SDL_OutOfMemory(); + return NULL; } -} + + [metalview setSDLWindow:window]; + + return (void*)CFBridgingRetain(metalview); +}} + +void +UIKit_Metal_DestroyView(_THIS, SDL_MetalView view) +{ @autoreleasepool { + SDL_uikitmetalview *metalview = CFBridgingRelease(view); + + if ([metalview isKindOfClass:[SDL_uikitmetalview class]]) { + [metalview setSDLWindow:NULL]; + } +}} void * UIKit_Metal_GetLayer(_THIS, SDL_MetalView view) -{ - @autoreleasepool { - SDL_uikitview *uiview = (__bridge SDL_uikitview *)view; - return (__bridge void *)uiview.layer; - } -} +{ @autoreleasepool { + SDL_uikitview *uiview = (__bridge SDL_uikitview *)view; + return (__bridge void *)uiview.layer; +}} -void UIKit_Metal_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h) +void +UIKit_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; - SDL_uikitview *view = (SDL_uikitview *)data.uiwindow.rootViewController.view; - SDL_uikitmetalview *metalview = [view viewWithTag:SDL_METALVIEW_TAG]; + SDL_uikitview *view = (SDL_uikitview*)data.uiwindow.rootViewController.view; + SDL_uikitmetalview* metalview = [view viewWithTag:SDL_METALVIEW_TAG]; if (metalview) { - CAMetalLayer *layer = (CAMetalLayer *)metalview.layer; + CAMetalLayer *layer = (CAMetalLayer*)metalview.layer; assert(layer != NULL); if (w) { *w = layer.drawableSize.width; diff --git a/src/video/uikit/SDL_uikitmodes.h b/src/video/uikit/SDL_uikitmodes.h index 83830ff99..d4f3b20ef 100644 --- a/src/video/uikit/SDL_uikitmodes.h +++ b/src/video/uikit/SDL_uikitmodes.h @@ -27,16 +27,16 @@ @interface SDL_DisplayData : NSObject -- (instancetype)initWithScreen:(UIScreen *)screen; +- (instancetype)initWithScreen:(UIScreen*)screen; -@property(nonatomic, strong) UIScreen *uiscreen; -@property(nonatomic) float screenDPI; +@property (nonatomic, strong) UIScreen *uiscreen; +@property (nonatomic) float screenDPI; @end @interface SDL_DisplayModeData : NSObject -@property(nonatomic, strong) UIScreenMode *uiscreenmode; +@property (nonatomic, strong) UIScreenMode *uiscreenmode; @end @@ -45,11 +45,11 @@ extern SDL_bool UIKit_IsDisplayLandscape(UIScreen *uiscreen); extern int UIKit_InitModes(_THIS); extern int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event); extern void UIKit_DelDisplay(UIScreen *uiscreen); -extern void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display); -extern int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi); -extern int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode); +extern void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display); +extern int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi); +extern int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode); extern void UIKit_QuitModes(_THIS); -extern int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect); +extern int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect); #endif /* SDL_uikitmodes_h_ */ diff --git a/src/video/uikit/SDL_uikitmodes.m b/src/video/uikit/SDL_uikitmodes.m index 65f91d4f8..322240d18 100644 --- a/src/video/uikit/SDL_uikitmodes.m +++ b/src/video/uikit/SDL_uikitmodes.m @@ -31,7 +31,7 @@ @implementation SDL_DisplayData -- (instancetype)initWithScreen:(UIScreen *)screen +- (instancetype)initWithScreen:(UIScreen*)screen { if (self = [super init]) { self.uiscreen = screen; @@ -40,109 +40,108 @@ * A well up to date list of device info can be found here: * https://github.com/lmirosevic/GBDeviceInfo/blob/master/GBDeviceInfo/GBDeviceInfo_iOS.m */ - NSDictionary *devices = @{ - @"iPhone1,1" : @163, - @"iPhone1,2" : @163, - @"iPhone2,1" : @163, - @"iPhone3,1" : @326, - @"iPhone3,2" : @326, - @"iPhone3,3" : @326, - @"iPhone4,1" : @326, - @"iPhone5,1" : @326, - @"iPhone5,2" : @326, - @"iPhone5,3" : @326, - @"iPhone5,4" : @326, - @"iPhone6,1" : @326, - @"iPhone6,2" : @326, - @"iPhone7,1" : @401, - @"iPhone7,2" : @326, - @"iPhone8,1" : @326, - @"iPhone8,2" : @401, - @"iPhone8,4" : @326, - @"iPhone9,1" : @326, - @"iPhone9,2" : @401, - @"iPhone9,3" : @326, - @"iPhone9,4" : @401, - @"iPhone10,1" : @326, - @"iPhone10,2" : @401, - @"iPhone10,3" : @458, - @"iPhone10,4" : @326, - @"iPhone10,5" : @401, - @"iPhone10,6" : @458, - @"iPhone11,2" : @458, - @"iPhone11,4" : @458, - @"iPhone11,6" : @458, - @"iPhone11,8" : @326, - @"iPhone12,1" : @326, - @"iPhone12,3" : @458, - @"iPhone12,5" : @458, - @"iPad1,1" : @132, - @"iPad2,1" : @132, - @"iPad2,2" : @132, - @"iPad2,3" : @132, - @"iPad2,4" : @132, - @"iPad2,5" : @163, - @"iPad2,6" : @163, - @"iPad2,7" : @163, - @"iPad3,1" : @264, - @"iPad3,2" : @264, - @"iPad3,3" : @264, - @"iPad3,4" : @264, - @"iPad3,5" : @264, - @"iPad3,6" : @264, - @"iPad4,1" : @264, - @"iPad4,2" : @264, - @"iPad4,3" : @264, - @"iPad4,4" : @326, - @"iPad4,5" : @326, - @"iPad4,6" : @326, - @"iPad4,7" : @326, - @"iPad4,8" : @326, - @"iPad4,9" : @326, - @"iPad5,1" : @326, - @"iPad5,2" : @326, - @"iPad5,3" : @264, - @"iPad5,4" : @264, - @"iPad6,3" : @264, - @"iPad6,4" : @264, - @"iPad6,7" : @264, - @"iPad6,8" : @264, - @"iPad6,11" : @264, - @"iPad6,12" : @264, - @"iPad7,1" : @264, - @"iPad7,2" : @264, - @"iPad7,3" : @264, - @"iPad7,4" : @264, - @"iPad7,5" : @264, - @"iPad7,6" : @264, - @"iPad7,11" : @264, - @"iPad7,12" : @264, - @"iPad8,1" : @264, - @"iPad8,2" : @264, - @"iPad8,3" : @264, - @"iPad8,4" : @264, - @"iPad8,5" : @264, - @"iPad8,6" : @264, - @"iPad8,7" : @264, - @"iPad8,8" : @264, - @"iPad11,1" : @326, - @"iPad11,2" : @326, - @"iPad11,3" : @326, - @"iPad11,4" : @326, - @"iPod1,1" : @163, - @"iPod2,1" : @163, - @"iPod3,1" : @163, - @"iPod4,1" : @326, - @"iPod5,1" : @326, - @"iPod7,1" : @326, - @"iPod9,1" : @326, + NSDictionary* devices = @{ + @"iPhone1,1": @163, + @"iPhone1,2": @163, + @"iPhone2,1": @163, + @"iPhone3,1": @326, + @"iPhone3,2": @326, + @"iPhone3,3": @326, + @"iPhone4,1": @326, + @"iPhone5,1": @326, + @"iPhone5,2": @326, + @"iPhone5,3": @326, + @"iPhone5,4": @326, + @"iPhone6,1": @326, + @"iPhone6,2": @326, + @"iPhone7,1": @401, + @"iPhone7,2": @326, + @"iPhone8,1": @326, + @"iPhone8,2": @401, + @"iPhone8,4": @326, + @"iPhone9,1": @326, + @"iPhone9,2": @401, + @"iPhone9,3": @326, + @"iPhone9,4": @401, + @"iPhone10,1": @326, + @"iPhone10,2": @401, + @"iPhone10,3": @458, + @"iPhone10,4": @326, + @"iPhone10,5": @401, + @"iPhone10,6": @458, + @"iPhone11,2": @458, + @"iPhone11,4": @458, + @"iPhone11,6": @458, + @"iPhone11,8": @326, + @"iPhone12,1": @326, + @"iPhone12,3": @458, + @"iPhone12,5": @458, + @"iPad1,1": @132, + @"iPad2,1": @132, + @"iPad2,2": @132, + @"iPad2,3": @132, + @"iPad2,4": @132, + @"iPad2,5": @163, + @"iPad2,6": @163, + @"iPad2,7": @163, + @"iPad3,1": @264, + @"iPad3,2": @264, + @"iPad3,3": @264, + @"iPad3,4": @264, + @"iPad3,5": @264, + @"iPad3,6": @264, + @"iPad4,1": @264, + @"iPad4,2": @264, + @"iPad4,3": @264, + @"iPad4,4": @326, + @"iPad4,5": @326, + @"iPad4,6": @326, + @"iPad4,7": @326, + @"iPad4,8": @326, + @"iPad4,9": @326, + @"iPad5,1": @326, + @"iPad5,2": @326, + @"iPad5,3": @264, + @"iPad5,4": @264, + @"iPad6,3": @264, + @"iPad6,4": @264, + @"iPad6,7": @264, + @"iPad6,8": @264, + @"iPad6,11": @264, + @"iPad6,12": @264, + @"iPad7,1": @264, + @"iPad7,2": @264, + @"iPad7,3": @264, + @"iPad7,4": @264, + @"iPad7,5": @264, + @"iPad7,6": @264, + @"iPad7,11": @264, + @"iPad7,12": @264, + @"iPad8,1": @264, + @"iPad8,2": @264, + @"iPad8,3": @264, + @"iPad8,4": @264, + @"iPad8,5": @264, + @"iPad8,6": @264, + @"iPad8,7": @264, + @"iPad8,8": @264, + @"iPad11,1": @326, + @"iPad11,2": @326, + @"iPad11,3": @326, + @"iPad11,4": @326, + @"iPod1,1": @163, + @"iPod2,1": @163, + @"iPod3,1": @163, + @"iPod4,1": @326, + @"iPod5,1": @326, + @"iPod7,1": @326, + @"iPod9,1": @326, }; struct utsname systemInfo; uname(&systemInfo); - NSString *deviceName = - [NSString stringWithCString:systemInfo.machine - encoding:NSUTF8StringEncoding]; + NSString* deviceName = + [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]; id foundDPI = devices[deviceName]; if (foundDPI) { self.screenDPI = (float)[foundDPI integerValue]; @@ -186,14 +185,10 @@ { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; - [center addObserver:self - selector:@selector(screenConnected:) - name:UIScreenDidConnectNotification - object:nil]; - [center addObserver:self - selector:@selector(screenDisconnected:) - name:UIScreenDidDisconnectNotification - object:nil]; + [center addObserver:self selector:@selector(screenConnected:) + name:UIScreenDidConnectNotification object:nil]; + [center addObserver:self selector:@selector(screenDisconnected:) + name:UIScreenDidDisconnectNotification object:nil]; } + (void)stop @@ -201,20 +196,18 @@ NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center removeObserver:self - name:UIScreenDidConnectNotification - object:nil]; + name:UIScreenDidConnectNotification object:nil]; [center removeObserver:self - name:UIScreenDidDisconnectNotification - object:nil]; + name:UIScreenDidDisconnectNotification object:nil]; } -+ (void)screenConnected:(NSNotification *)notification ++ (void)screenConnected:(NSNotification*)notification { UIScreen *uiscreen = [notification object]; UIKit_AddDisplay(uiscreen, SDL_TRUE); } -+ (void)screenDisconnected:(NSNotification *)notification ++ (void)screenDisconnected:(NSNotification*)notification { UIScreen *uiscreen = [notification object]; UIKit_DelDisplay(uiscreen); @@ -222,8 +215,9 @@ @end -static int UIKit_AllocateDisplayModeData(SDL_DisplayMode *mode, - UIScreenMode *uiscreenmode) +static int +UIKit_AllocateDisplayModeData(SDL_DisplayMode * mode, + UIScreenMode * uiscreenmode) { SDL_DisplayModeData *data = nil; @@ -237,12 +231,13 @@ static int UIKit_AllocateDisplayModeData(SDL_DisplayMode *mode, data.uiscreenmode = uiscreenmode; } - mode->driverdata = (void *)CFBridgingRetain(data); + mode->driverdata = (void *) CFBridgingRetain(data); return 0; } -static void UIKit_FreeDisplayModeData(SDL_DisplayMode *mode) +static void +UIKit_FreeDisplayModeData(SDL_DisplayMode * mode) { if (mode->driverdata != NULL) { CFRelease(mode->driverdata); @@ -250,7 +245,8 @@ static void UIKit_FreeDisplayModeData(SDL_DisplayMode *mode) } } -static NSUInteger UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen) +static NSUInteger +UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen) { #ifdef __IPHONE_10_3 if ([uiscreen respondsToSelector:@selector(maximumFramesPerSecond)]) { @@ -260,8 +256,9 @@ static NSUInteger UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen) return 0; } -static int UIKit_AddSingleDisplayMode(SDL_VideoDisplay *display, int w, int h, - UIScreen *uiscreen, UIScreenMode *uiscreenmode) +static int +UIKit_AddSingleDisplayMode(SDL_VideoDisplay * display, int w, int h, + UIScreen * uiscreen, UIScreenMode * uiscreenmode) { SDL_DisplayMode mode; SDL_zero(mode); @@ -271,7 +268,7 @@ static int UIKit_AddSingleDisplayMode(SDL_VideoDisplay *display, int w, int h, } mode.format = SDL_PIXELFORMAT_ABGR8888; - mode.refresh_rate = (int)UIKit_GetDisplayModeRefreshRate(uiscreen); + mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen); mode.w = w; mode.h = h; @@ -283,8 +280,9 @@ static int UIKit_AddSingleDisplayMode(SDL_VideoDisplay *display, int w, int h, } } -static int UIKit_AddDisplayMode(SDL_VideoDisplay *display, int w, int h, UIScreen *uiscreen, - UIScreenMode *uiscreenmode, SDL_bool addRotation) +static int +UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h, UIScreen * uiscreen, + UIScreenMode * uiscreenmode, SDL_bool addRotation) { if (UIKit_AddSingleDisplayMode(display, w, h, uiscreen, uiscreenmode) < 0) { return -1; @@ -300,7 +298,8 @@ static int UIKit_AddDisplayMode(SDL_VideoDisplay *display, int w, int h, UIScree return 0; } -int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event) +int +UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event) { UIScreenMode *uiscreenmode = uiscreen.currentMode; CGSize size = uiscreen.bounds.size; @@ -316,9 +315,9 @@ int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event) } mode.format = SDL_PIXELFORMAT_ABGR8888; - mode.refresh_rate = (int)UIKit_GetDisplayModeRefreshRate(uiscreen); - mode.w = (int)size.width; - mode.h = (int)size.height; + mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen); + mode.w = (int) size.width; + mode.h = (int) size.height; if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) { return -1; @@ -335,13 +334,14 @@ int UIKit_AddDisplay(UIScreen *uiscreen, SDL_bool send_event) return SDL_OutOfMemory(); } - display.driverdata = (void *)CFBridgingRetain(data); + display.driverdata = (void *) CFBridgingRetain(data); SDL_AddVideoDisplay(&display, send_event); return 0; } -void UIKit_DelDisplay(UIScreen *uiscreen) +void +UIKit_DelDisplay(UIScreen *uiscreen) { int i; @@ -370,7 +370,8 @@ UIKit_IsDisplayLandscape(UIScreen *uiscreen) } } -int UIKit_InitModes(_THIS) +int +UIKit_InitModes(_THIS) { @autoreleasepool { for (UIScreen *uiscreen in [UIScreen screens]) { @@ -388,10 +389,11 @@ int UIKit_InitModes(_THIS) return 0; } -void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display) +void +UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display) { @autoreleasepool { - SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata; + SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; SDL_bool isLandscape = UIKit_IsDisplayLandscape(data.uiscreen); SDL_bool addRotation = (data.uiscreen == [UIScreen mainScreen]); @@ -400,7 +402,7 @@ void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display) #if TARGET_OS_TV addRotation = SDL_FALSE; - availableModes = @[ data.uiscreen.currentMode ]; + availableModes = @[data.uiscreen.currentMode]; #else availableModes = data.uiscreen.availableModes; #endif @@ -432,10 +434,11 @@ void UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay *display) } } -int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hdpi, float *vdpi) +int +UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi) { @autoreleasepool { - SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata; + SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; float dpi = data.screenDPI; if (ddpi) { @@ -452,10 +455,11 @@ int UIKit_GetDisplayDPI(_THIS, SDL_VideoDisplay *display, float *ddpi, float *hd return 0; } -int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode) +int +UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode) { @autoreleasepool { - SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata; + SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; #if !TARGET_OS_TV SDL_DisplayModeData *modedata = (__bridge SDL_DisplayModeData *)mode->driverdata; @@ -481,11 +485,12 @@ int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode return 0; } -int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rect) +int +UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect) { @autoreleasepool { - int displayIndex = (int)(display - _this->displays); - SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata; + int displayIndex = (int) (display - _this->displays); + SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; CGRect frame = data.uiscreen.bounds; /* the default function iterates displays to make a fake offset, @@ -503,7 +508,8 @@ int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay *display, SDL_Rect *rec return 0; } -void UIKit_QuitModes(_THIS) +void +UIKit_QuitModes(_THIS) { [SDL_DisplayWatch stop]; diff --git a/src/video/uikit/SDL_uikitopengles.h b/src/video/uikit/SDL_uikitopengles.h index 4cd683282..c2e6d571c 100644 --- a/src/video/uikit/SDL_uikitopengles.h +++ b/src/video/uikit/SDL_uikitopengles.h @@ -25,12 +25,12 @@ #include "../SDL_sysvideo.h" -extern int UIKit_GL_MakeCurrent(_THIS, SDL_Window *window, +extern int UIKit_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context); -extern void UIKit_GL_GetDrawableSize(_THIS, SDL_Window *window, - int *w, int *h); -extern int UIKit_GL_SwapWindow(_THIS, SDL_Window *window); -extern SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window *window); +extern void UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window, + int * w, int * h); +extern int UIKit_GL_SwapWindow(_THIS, SDL_Window * window); +extern SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window * window); extern void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context); extern void *UIKit_GL_GetProcAddress(_THIS, const char *proc); extern int UIKit_GL_LoadLibrary(_THIS, const char *path); diff --git a/src/video/uikit/SDL_uikitopengles.m b/src/video/uikit/SDL_uikitopengles.m index 81bf46630..15ea2e350 100644 --- a/src/video/uikit/SDL_uikitopengles.m +++ b/src/video/uikit/SDL_uikitopengles.m @@ -37,7 +37,7 @@ @interface SDLEAGLContext : EAGLContext /* The OpenGL ES context owns a view / drawable. */ -@property(nonatomic, strong) SDL_uikitopenglview *sdlView; +@property (nonatomic, strong) SDL_uikitopenglview *sdlView; @end @@ -64,10 +64,11 @@ UIKit_GL_GetProcAddress(_THIS, const char *proc) /* note that SDL_GL_DeleteContext makes it current without passing the window */ -int UIKit_GL_MakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context) +int +UIKit_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) { @autoreleasepool { - SDLEAGLContext *eaglcontext = (__bridge SDLEAGLContext *)context; + SDLEAGLContext *eaglcontext = (__bridge SDLEAGLContext *) context; if (![EAGLContext setCurrentContext:eaglcontext]) { return SDL_SetError("Could not make EAGL context current"); @@ -81,13 +82,14 @@ int UIKit_GL_MakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context) return 0; } -void UIKit_GL_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h) +void +UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h) { @autoreleasepool { SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; UIView *view = data.viewcontroller.view; if ([view isKindOfClass:[SDL_uikitopenglview class]]) { - SDL_uikitopenglview *glview = (SDL_uikitopenglview *)view; + SDL_uikitopenglview *glview = (SDL_uikitopenglview *) view; if (w) { *w = glview.backingWidth; } @@ -100,7 +102,8 @@ void UIKit_GL_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h) } } -int UIKit_GL_LoadLibrary(_THIS, const char *path) +int +UIKit_GL_LoadLibrary(_THIS, const char *path) { /* We shouldn't pass a path to this function, since we've already loaded the * library. */ @@ -110,10 +113,10 @@ int UIKit_GL_LoadLibrary(_THIS, const char *path) return 0; } -int UIKit_GL_SwapWindow(_THIS, SDL_Window *window) +int UIKit_GL_SwapWindow(_THIS, SDL_Window * window) { @autoreleasepool { - SDLEAGLContext *context = (__bridge SDLEAGLContext *)SDL_GL_GetCurrentContext(); + SDLEAGLContext *context = (__bridge SDLEAGLContext *) SDL_GL_GetCurrentContext(); #if SDL_POWER_UIKIT /* Check once a frame to see if we should turn off the battery monitor. */ @@ -130,12 +133,12 @@ int UIKit_GL_SwapWindow(_THIS, SDL_Window *window) } SDL_GLContext -UIKit_GL_CreateContext(_THIS, SDL_Window *window) +UIKit_GL_CreateContext(_THIS, SDL_Window * window) { @autoreleasepool { SDLEAGLContext *context = nil; SDL_uikitopenglview *view; - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; CGRect frame = UIKit_ComputeViewFrame(window, data.uiwindow.screen); EAGLSharegroup *sharegroup = nil; CGFloat scale = 1.0; @@ -158,7 +161,7 @@ UIKit_GL_CreateContext(_THIS, SDL_Window *window) } if (_this->gl_config.share_with_current_context) { - EAGLContext *currContext = (__bridge EAGLContext *)SDL_GL_GetCurrentContext(); + EAGLContext *currContext = (__bridge EAGLContext *) SDL_GL_GetCurrentContext(); sharegroup = currContext.sharegroup; } @@ -196,18 +199,19 @@ UIKit_GL_CreateContext(_THIS, SDL_Window *window) /* The context owns the view / drawable. */ context.sdlView = view; - if (UIKit_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext)context) < 0) { - UIKit_GL_DeleteContext(_this, (SDL_GLContext)CFBridgingRetain(context)); + if (UIKit_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext) context) < 0) { + UIKit_GL_DeleteContext(_this, (SDL_GLContext) CFBridgingRetain(context)); return NULL; } /* We return a +1'd context. The window's driverdata owns the view (via * MakeCurrent.) */ - return (SDL_GLContext)CFBridgingRetain(context); + return (SDL_GLContext) CFBridgingRetain(context); } } -void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context) +void +UIKit_GL_DeleteContext(_THIS, SDL_GLContext context) { @autoreleasepool { /* The context was retained in SDL_GL_CreateContext, so we release it @@ -217,7 +221,8 @@ void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context) } } -void UIKit_GL_RestoreCurrentContext(void) +void +UIKit_GL_RestoreCurrentContext(void) { @autoreleasepool { /* Some iOS system functionality (such as Dictation on the on-screen @@ -227,7 +232,7 @@ void UIKit_GL_RestoreCurrentContext(void) finished running its own code for the frame. If this isn't done, the app may crash or have other nasty symptoms when Dictation is used. */ - EAGLContext *context = (__bridge EAGLContext *)SDL_GL_GetCurrentContext(); + EAGLContext *context = (__bridge EAGLContext *) SDL_GL_GetCurrentContext(); if (context != NULL && [EAGLContext currentContext] != context) { [EAGLContext setCurrentContext:context]; } diff --git a/src/video/uikit/SDL_uikitopenglview.h b/src/video/uikit/SDL_uikitopenglview.h index 519fd328f..df659a1f1 100644 --- a/src/video/uikit/SDL_uikitopenglview.h +++ b/src/video/uikit/SDL_uikitopenglview.h @@ -43,15 +43,15 @@ multisamples:(int)multisamples context:(EAGLContext *)glcontext; -@property(nonatomic, readonly, weak) EAGLContext *context; +@property (nonatomic, readonly, weak) EAGLContext *context; /* The width and height of the drawable in pixels (as opposed to points.) */ -@property(nonatomic, readonly) int backingWidth; -@property(nonatomic, readonly) int backingHeight; +@property (nonatomic, readonly) int backingWidth; +@property (nonatomic, readonly) int backingHeight; -@property(nonatomic, readonly) GLuint drawableRenderbuffer; -@property(nonatomic, readonly) GLuint drawableFramebuffer; -@property(nonatomic, readonly) GLuint msaaResolveFramebuffer; +@property (nonatomic, readonly) GLuint drawableRenderbuffer; +@property (nonatomic, readonly) GLuint drawableFramebuffer; +@property (nonatomic, readonly) GLuint msaaResolveFramebuffer; - (void)swapBuffers; diff --git a/src/video/uikit/SDL_uikitopenglview.m b/src/video/uikit/SDL_uikitopenglview.m index 8756a8e1b..ea4db411a 100644 --- a/src/video/uikit/SDL_uikitopenglview.m +++ b/src/video/uikit/SDL_uikitopenglview.m @@ -27,8 +27,7 @@ #import "SDL_uikitopenglview.h" #include "SDL_uikitwindow.h" -@implementation SDL_uikitopenglview -{ +@implementation SDL_uikitopenglview { /* The renderbuffer and framebuffer used to render to this layer. */ GLuint viewRenderbuffer, viewFramebuffer; @@ -110,8 +109,8 @@ eaglLayer.opaque = YES; eaglLayer.drawableProperties = @{ - kEAGLDrawablePropertyRetainedBacking : @(retained), - kEAGLDrawablePropertyColorFormat : colorFormat + kEAGLDrawablePropertyRetainedBacking:@(retained), + kEAGLDrawablePropertyColorFormat:colorFormat }; /* Set the appropriate scale (for retina display support) */ @@ -280,7 +279,7 @@ - (void)swapBuffers { if (msaaFramebuffer) { - const GLenum attachments[] = { GL_COLOR_ATTACHMENT0 }; + const GLenum attachments[] = {GL_COLOR_ATTACHMENT0}; glBindFramebuffer(GL_DRAW_FRAMEBUFFER, viewFramebuffer); @@ -318,8 +317,8 @@ { [super layoutSubviews]; - int width = (int)(self.bounds.size.width * self.contentScaleFactor); - int height = (int)(self.bounds.size.height * self.contentScaleFactor); + int width = (int) (self.bounds.size.width * self.contentScaleFactor); + int height = (int) (self.bounds.size.height * self.contentScaleFactor); /* Update the color and depth buffer storage if the layer size has changed. */ if (width != backingWidth || height != backingHeight) { diff --git a/src/video/uikit/SDL_uikitvideo.h b/src/video/uikit/SDL_uikitvideo.h index a41ff3f18..b684e23a8 100644 --- a/src/video/uikit/SDL_uikitvideo.h +++ b/src/video/uikit/SDL_uikitvideo.h @@ -29,7 +29,7 @@ @interface SDL_VideoData : NSObject -@property(nonatomic, assign) id pasteboardObserver; +@property (nonatomic, assign) id pasteboardObserver; @end diff --git a/src/video/uikit/SDL_uikitvideo.m b/src/video/uikit/SDL_uikitvideo.m index bce7d676a..4e8a57755 100644 --- a/src/video/uikit/SDL_uikitvideo.m +++ b/src/video/uikit/SDL_uikitvideo.m @@ -52,7 +52,7 @@ static void UIKit_VideoQuit(_THIS); /* DUMMY driver bootstrap functions */ -static void UIKit_DeleteDevice(SDL_VideoDevice *device) +static void UIKit_DeleteDevice(SDL_VideoDevice * device) { @autoreleasepool { CFRelease(device->driverdata); @@ -60,14 +60,15 @@ static void UIKit_DeleteDevice(SDL_VideoDevice *device) } } -static SDL_VideoDevice *UIKit_CreateDevice(void) +static SDL_VideoDevice * +UIKit_CreateDevice(void) { @autoreleasepool { SDL_VideoDevice *device; SDL_VideoData *data; /* Initialize all variables that we clean on shutdown */ - device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice)); + device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice)); if (device) { data = [SDL_VideoData new]; } else { @@ -76,7 +77,7 @@ static SDL_VideoDevice *UIKit_CreateDevice(void) return (0); } - device->driverdata = (void *)CFBridgingRetain(data); + device->driverdata = (void *) CFBridgingRetain(data); /* Set the function pointers */ device->VideoInit = UIKit_VideoInit; @@ -113,20 +114,21 @@ static SDL_VideoDevice *UIKit_CreateDevice(void) /* OpenGL (ES) functions */ #if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2 - device->GL_MakeCurrent = UIKit_GL_MakeCurrent; - device->GL_GetDrawableSize = UIKit_GL_GetDrawableSize; - device->GL_SwapWindow = UIKit_GL_SwapWindow; - device->GL_CreateContext = UIKit_GL_CreateContext; - device->GL_DeleteContext = UIKit_GL_DeleteContext; - device->GL_GetProcAddress = UIKit_GL_GetProcAddress; - device->GL_LoadLibrary = UIKit_GL_LoadLibrary; + device->GL_MakeCurrent = UIKit_GL_MakeCurrent; + device->GL_GetDrawableSize = UIKit_GL_GetDrawableSize; + device->GL_SwapWindow = UIKit_GL_SwapWindow; + device->GL_CreateContext = UIKit_GL_CreateContext; + device->GL_DeleteContext = UIKit_GL_DeleteContext; + device->GL_GetProcAddress = UIKit_GL_GetProcAddress; + device->GL_LoadLibrary = UIKit_GL_LoadLibrary; #endif device->free = UIKit_DeleteDevice; #if SDL_VIDEO_VULKAN device->Vulkan_LoadLibrary = UIKit_Vulkan_LoadLibrary; device->Vulkan_UnloadLibrary = UIKit_Vulkan_UnloadLibrary; - device->Vulkan_GetInstanceExtensions = UIKit_Vulkan_GetInstanceExtensions; + device->Vulkan_GetInstanceExtensions + = UIKit_Vulkan_GetInstanceExtensions; device->Vulkan_CreateSurface = UIKit_Vulkan_CreateSurface; device->Vulkan_GetDrawableSize = UIKit_Vulkan_GetDrawableSize; #endif @@ -149,7 +151,9 @@ VideoBootStrap UIKIT_bootstrap = { UIKit_CreateDevice }; -int UIKit_VideoInit(_THIS) + +int +UIKit_VideoInit(_THIS) { _this->gl_config.driver_loaded = 1; @@ -163,7 +167,8 @@ int UIKit_VideoInit(_THIS) return 0; } -void UIKit_VideoQuit(_THIS) +void +UIKit_VideoQuit(_THIS) { SDL_QuitGCKeyboard(); SDL_QuitGCMouse(); @@ -171,7 +176,8 @@ void UIKit_VideoQuit(_THIS) UIKit_QuitModes(_this); } -void UIKit_SuspendScreenSaver(_THIS) +void +UIKit_SuspendScreenSaver(_THIS) { @autoreleasepool { /* Ignore ScreenSaver API calls if the idle timer hint has been set. */ @@ -194,7 +200,7 @@ UIKit_IsSystemVersionAtLeast(double version) CGRect UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen) { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; CGRect frame = screen.bounds; /* Use the UIWindow bounds instead of the UIScreen bounds, when possible. @@ -229,13 +235,14 @@ UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen) return frame; } -void UIKit_ForceUpdateHomeIndicator() +void +UIKit_ForceUpdateHomeIndicator() { #if !TARGET_OS_TV /* Force the main SDL window to re-evaluate home indicator state */ SDL_Window *focus = SDL_GetFocusWindow(); if (focus) { - SDL_WindowData *data = (__bridge SDL_WindowData *)focus->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) focus->driverdata; if (data != nil) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" diff --git a/src/video/uikit/SDL_uikitview.h b/src/video/uikit/SDL_uikitview.h index 15be61b55..dcd63c7a5 100644 --- a/src/video/uikit/SDL_uikitview.h +++ b/src/video/uikit/SDL_uikitview.h @@ -37,7 +37,7 @@ #if !TARGET_OS_TV && defined(__IPHONE_13_4) - (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4)); -- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4)); +- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4)); #endif - (CGPoint)touchLocation:(UITouch *)touch shouldNormalize:(BOOL)normalize; diff --git a/src/video/uikit/SDL_uikitview.m b/src/video/uikit/SDL_uikitview.m index 557b97140..8c48cfa50 100644 --- a/src/video/uikit/SDL_uikitview.m +++ b/src/video/uikit/SDL_uikitview.m @@ -1,22 +1,22 @@ -/* - Simple DirectMedia Layer - Copyright (C) 1997-2022 Sam Lantinga + /* + Simple DirectMedia Layer + Copyright (C) 1997-2022 Sam Lantinga - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" @@ -35,15 +35,14 @@ #include "SDL_uikitwindow.h" /* The maximum number of mouse buttons we support */ -#define MAX_MOUSE_BUTTONS 5 +#define MAX_MOUSE_BUTTONS 5 /* This is defined in SDL_sysjoystick.m */ #if !SDL_JOYSTICK_DISABLED extern int SDL_AppleTVRemoteOpenedAsJoystick; #endif -@implementation SDL_uikitview -{ +@implementation SDL_uikitview { SDL_Window *sdlwindow; SDL_TouchID directTouchId; @@ -104,7 +103,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; /* Remove ourself from the old window. */ if (sdlwindow) { SDL_uikitview *view = nil; - data = (__bridge SDL_WindowData *)sdlwindow->driverdata; + data = (__bridge SDL_WindowData *) sdlwindow->driverdata; [data.views removeObject:self]; @@ -123,7 +122,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; /* Add ourself to the new window. */ if (window) { - data = (__bridge SDL_WindowData *)window->driverdata; + data = (__bridge SDL_WindowData *) window->driverdata; /* Make sure the SDL window has a strong reference to this view. */ [data.views addObject:self]; @@ -150,8 +149,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; } #if !TARGET_OS_TV && defined(__IPHONE_13_4) -- (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4)) -{ +- (UIPointerRegion *)pointerInteraction:(UIPointerInteraction *)interaction regionForRequest:(UIPointerRegionRequest *)request defaultRegion:(UIPointerRegion *)defaultRegion API_AVAILABLE(ios(13.4)){ if (request != nil && !SDL_GCMouseRelativeMode()) { CGPoint origin = self.bounds.origin; CGPoint point = request.location; @@ -164,8 +162,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; return [UIPointerRegion regionWithRect:self.bounds identifier:nil]; } -- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4)) -{ +- (UIPointerStyle *)pointerInteraction:(UIPointerInteraction *)interaction styleForRegion:(UIPointerRegion *)region API_AVAILABLE(ios(13.4)){ if (SDL_ShowCursor(-1)) { return nil; } else { @@ -190,11 +187,11 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; - (SDL_TouchID)touchIdForType:(SDL_TouchDeviceType)type { switch (type) { - case SDL_TOUCH_DEVICE_DIRECT: - default: - return directTouchId; - case SDL_TOUCH_DEVICE_INDIRECT_RELATIVE: - return indirectTouchId; + case SDL_TOUCH_DEVICE_DIRECT: + default: + return directTouchId; + case SDL_TOUCH_DEVICE_INDIRECT_RELATIVE: + return indirectTouchId; } } @@ -215,7 +212,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; { #ifdef __IPHONE_9_0 if ([touch respondsToSelector:@selector(force)]) { - return (float)touch.force; + return (float) touch.force; } #endif @@ -367,7 +364,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; } #if TARGET_OS_TV || defined(__IPHONE_9_1) -- (SDL_Scancode)scancodeFromPress:(UIPress *)press +- (SDL_Scancode)scancodeFromPress:(UIPress*)press { #ifdef __IPHONE_13_4 if ([press respondsToSelector:@selector((key))]) { @@ -449,7 +446,7 @@ extern int SDL_AppleTVRemoteOpenedAsJoystick; #endif /* TARGET_OS_TV || defined(__IPHONE_9_1) */ #if TARGET_OS_TV -- (void)swipeGesture:(UISwipeGestureRecognizer *)gesture +-(void)swipeGesture:(UISwipeGestureRecognizer *)gesture { /* Swipe gestures don't trigger begin states. */ if (gesture.state == UIGestureRecognizerStateEnded) { diff --git a/src/video/uikit/SDL_uikitviewcontroller.h b/src/video/uikit/SDL_uikitviewcontroller.h index 2880ccd4a..2e64a5279 100644 --- a/src/video/uikit/SDL_uikitviewcontroller.h +++ b/src/video/uikit/SDL_uikitviewcontroller.h @@ -39,18 +39,18 @@ @interface SDL_uikitviewcontroller : SDLRootViewController #endif -@property(nonatomic, assign) SDL_Window *window; +@property (nonatomic, assign) SDL_Window *window; - (instancetype)initWithSDLWindow:(SDL_Window *)_window; - (void)setAnimationCallback:(int)interval - callback:(void (*)(void *))callback - callbackParam:(void *)callbackParam; + callback:(void (*)(void*))callback + callbackParam:(void*)callbackParam; - (void)startAnimation; - (void)stopAnimation; -- (void)doLoop:(CADisplayLink *)sender; +- (void)doLoop:(CADisplayLink*)sender; - (void)loadView; - (void)viewDidLayoutSubviews; @@ -61,7 +61,7 @@ - (BOOL)prefersHomeIndicatorAutoHidden; - (UIRectEdge)preferredScreenEdgesDeferringSystemGestures; -@property(nonatomic, assign) int homeIndicatorHidden; +@property (nonatomic, assign) int homeIndicatorHidden; #endif #if SDL_IPHONE_KEYBOARD @@ -75,9 +75,9 @@ - (void)updateKeyboard; -@property(nonatomic, assign, getter=isKeyboardVisible) BOOL keyboardVisible; -@property(nonatomic, assign) SDL_Rect textInputRect; -@property(nonatomic, assign) int keyboardHeight; +@property (nonatomic, assign, getter=isKeyboardVisible) BOOL keyboardVisible; +@property (nonatomic, assign) SDL_Rect textInputRect; +@property (nonatomic, assign) int keyboardHeight; #endif @end diff --git a/src/video/uikit/SDL_uikitviewcontroller.m b/src/video/uikit/SDL_uikitviewcontroller.m index 889cb8438..ee7ee83b0 100644 --- a/src/video/uikit/SDL_uikitviewcontroller.m +++ b/src/video/uikit/SDL_uikitviewcontroller.m @@ -36,20 +36,22 @@ #include "SDL_uikitopengles.h" #if TARGET_OS_TV -static void SDLCALL SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +static void SDLCALL +SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { @autoreleasepool { - SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *)userdata; + SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *) userdata; viewcontroller.controllerUserInteractionEnabled = hint && (*hint != '0'); } } #endif #if !TARGET_OS_TV -static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) +static void SDLCALL +SDL_HideHomeIndicatorHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint) { @autoreleasepool { - SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *)userdata; + SDL_uikitviewcontroller *viewcontroller = (__bridge SDL_uikitviewcontroller *) userdata; viewcontroller.homeIndicatorHidden = (hint && *hint) ? SDL_atoi(hint) : -1; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunguarded-availability-new" @@ -62,11 +64,10 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char } #endif -@implementation SDL_uikitviewcontroller -{ +@implementation SDL_uikitviewcontroller { CADisplayLink *displayLink; int animationInterval; - void (*animationCallback)(void *); + void (*animationCallback)(void*); void *animationCallbackParam; #if SDL_IPHONE_KEYBOARD @@ -96,13 +97,13 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char #if TARGET_OS_TV SDL_AddHintCallback(SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS, SDL_AppleTVControllerUIHintChanged, - (__bridge void *)self); + (__bridge void *) self); #endif #if !TARGET_OS_TV SDL_AddHintCallback(SDL_HINT_IOS_HIDE_HOME_INDICATOR, SDL_HideHomeIndicatorHintChanged, - (__bridge void *)self); + (__bridge void *) self); #endif } return self; @@ -117,19 +118,19 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char #if TARGET_OS_TV SDL_DelHintCallback(SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS, SDL_AppleTVControllerUIHintChanged, - (__bridge void *)self); + (__bridge void *) self); #endif #if !TARGET_OS_TV SDL_DelHintCallback(SDL_HINT_IOS_HIDE_HOME_INDICATOR, SDL_HideHomeIndicatorHintChanged, - (__bridge void *)self); + (__bridge void *) self); #endif } - (void)setAnimationCallback:(int)interval - callback:(void (*)(void *))callback - callbackParam:(void *)callbackParam + callback:(void (*)(void*))callback + callbackParam:(void*)callbackParam { [self stopAnimation]; @@ -147,9 +148,11 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(doLoop:)]; #ifdef __IPHONE_10_3 - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; - if ([displayLink respondsToSelector:@selector(preferredFramesPerSecond)] && data != nil && data.uiwindow != nil && [data.uiwindow.screen respondsToSelector:@selector(maximumFramesPerSecond)]) { + if ([displayLink respondsToSelector:@selector(preferredFramesPerSecond)] + && data != nil && data.uiwindow != nil + && [data.uiwindow.screen respondsToSelector:@selector(maximumFramesPerSecond)]) { displayLink.preferredFramesPerSecond = data.uiwindow.screen.maximumFramesPerSecond / animationInterval; } else #endif @@ -168,7 +171,7 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char displayLink = nil; } -- (void)doLoop:(CADisplayLink *)sender +- (void)doLoop:(CADisplayLink*)sender { /* Don't run the game loop while a messagebox is up */ if (!UIKit_ShowingMessageBox()) { @@ -189,8 +192,8 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char - (void)viewDidLayoutSubviews { const CGSize size = self.view.bounds.size; - int w = (int)size.width; - int h = (int)size.height; + int w = (int) size.width; + int h = (int) size.height; SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, w, h); } @@ -203,7 +206,7 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char - (BOOL)prefersStatusBarHidden { - BOOL hidden = (window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) != 0; + BOOL hidden = (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) != 0; return hidden; } @@ -227,7 +230,7 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char } /* By default, fullscreen and borderless windows get all screen gestures */ - if ((window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) != 0) { + if ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) != 0) { return UIRectEdgeAll; } else { return UIRectEdgeNone; @@ -274,16 +277,10 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; #if !TARGET_OS_TV - [center addObserver:self - selector:@selector(keyboardWillShow:) - name:UIKeyboardWillShowNotification - object:nil]; + [center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; #endif - [center addObserver:self - selector:@selector(textFieldTextDidChange:) - name:UITextFieldTextDidChangeNotification - object:nil]; + [center addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil]; } - (NSArray *)keyCommands @@ -334,26 +331,20 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char { [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; rotatingOrientation = YES; - [coordinator - animateAlongsideTransition:^(id context) { - } - completion:^(id context) { - self->rotatingOrientation = NO; - }]; + [coordinator animateAlongsideTransition:^(id context) {} + completion:^(id context) { + self->rotatingOrientation = NO; + }]; } - (void)deinitKeyboard { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; #if !TARGET_OS_TV - [center removeObserver:self - name:UIKeyboardWillShowNotification - object:nil]; + [center removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [center removeObserver:self name:UIKeyboardWillHideNotification object:nil]; #endif - [center removeObserver:self - name:UITextFieldTextDidChangeNotification - object:nil]; + [center removeObserver:self name:UITextFieldTextDidChangeNotification object:nil]; } /* reveal onscreen virtual keyboard */ @@ -480,12 +471,12 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char } /* Terminates the editing session */ -- (BOOL)textFieldShouldReturn:(UITextField *)_textField +- (BOOL)textFieldShouldReturn:(UITextField*)_textField { SDL_SendKeyboardKeyAutoRelease(SDL_SCANCODE_RETURN); if (keyboardVisible && SDL_GetHintBoolean(SDL_HINT_RETURN_KEY_HIDES_IME, SDL_FALSE)) { - SDL_StopTextInput(); + SDL_StopTextInput(); } return YES; } @@ -497,7 +488,8 @@ static void SDLCALL SDL_HideHomeIndicatorHintChanged(void *userdata, const char /* iPhone keyboard addition functions */ #if SDL_IPHONE_KEYBOARD -static SDL_uikitviewcontroller *GetWindowViewController(SDL_Window *window) +static SDL_uikitviewcontroller * +GetWindowViewController(SDL_Window * window) { if (!window || !window->driverdata) { SDL_SetError("Invalid window"); @@ -515,7 +507,8 @@ UIKit_HasScreenKeyboardSupport(_THIS) return SDL_TRUE; } -void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window) +void +UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window) { @autoreleasepool { SDL_uikitviewcontroller *vc = GetWindowViewController(window); @@ -523,7 +516,8 @@ void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window) } } -void UIKit_HideScreenKeyboard(_THIS, SDL_Window *window) +void +UIKit_HideScreenKeyboard(_THIS, SDL_Window *window) { @autoreleasepool { SDL_uikitviewcontroller *vc = GetWindowViewController(window); @@ -543,7 +537,8 @@ UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window) } } -void UIKit_SetTextInputRect(_THIS, const SDL_Rect *rect) +void +UIKit_SetTextInputRect(_THIS, const SDL_Rect *rect) { if (!rect) { SDL_InvalidParamError("rect"); @@ -562,6 +557,7 @@ void UIKit_SetTextInputRect(_THIS, const SDL_Rect *rect) } } + #endif /* SDL_IPHONE_KEYBOARD */ #endif /* SDL_VIDEO_DRIVER_UIKIT */ diff --git a/src/video/uikit/SDL_uikitvulkan.h b/src/video/uikit/SDL_uikitvulkan.h index 3c29d6fba..cc8f777eb 100644 --- a/src/video/uikit/SDL_uikitvulkan.h +++ b/src/video/uikit/SDL_uikitvulkan.h @@ -37,13 +37,13 @@ int UIKit_Vulkan_LoadLibrary(_THIS, const char *path); void UIKit_Vulkan_UnloadLibrary(_THIS); SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS, - SDL_Window *window, - unsigned *count, - const char **names); + SDL_Window *window, + unsigned *count, + const char **names); SDL_bool UIKit_Vulkan_CreateSurface(_THIS, - SDL_Window *window, - VkInstance instance, - VkSurfaceKHR *surface); + SDL_Window *window, + VkInstance instance, + VkSurfaceKHR *surface); void UIKit_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h); diff --git a/src/video/uikit/SDL_uikitvulkan.m b/src/video/uikit/SDL_uikitvulkan.m index ae011abe5..52a1ceddb 100644 --- a/src/video/uikit/SDL_uikitvulkan.m +++ b/src/video/uikit/SDL_uikitvulkan.m @@ -38,7 +38,7 @@ #include -const char *defaultPaths[] = { +const char* defaultPaths[] = { "libvulkan.dylib", }; @@ -67,14 +67,14 @@ int UIKit_Vulkan_LoadLibrary(_THIS, const char *path) if (!path) { /* Handle the case where Vulkan Portability is linked statically. */ vkGetInstanceProcAddr = - (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE, - "vkGetInstanceProcAddr"); + (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE, + "vkGetInstanceProcAddr"); } if (vkGetInstanceProcAddr) { _this->vulkan_config.loader_handle = DEFAULT_HANDLE; } else { - const char **paths; + const char** paths; const char *foundPath = NULL; int numPaths; int i; @@ -101,15 +101,15 @@ int UIKit_Vulkan_LoadLibrary(_THIS, const char *path) SDL_arraysize(_this->vulkan_config.loader_path)); vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( - _this->vulkan_config.loader_handle, - "vkGetInstanceProcAddr"); + _this->vulkan_config.loader_handle, + "vkGetInstanceProcAddr"); } if (!vkGetInstanceProcAddr) { SDL_SetError("Failed to find %s in either executable or %s: %s", "vkGetInstanceProcAddr", "linked Vulkan Portability library", - (const char *)dlerror()); + (const char *) dlerror()); goto fail; } @@ -145,10 +145,13 @@ int UIKit_Vulkan_LoadLibrary(_THIS, const char *path) SDL_free(extensions); if (!hasSurfaceExtension) { - SDL_SetError("Installed Vulkan Portability doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); + SDL_SetError("Installed Vulkan Portability doesn't implement the " + VK_KHR_SURFACE_EXTENSION_NAME " extension"); goto fail; } else if (!hasMetalSurfaceExtension && !hasIOSSurfaceExtension) { - SDL_SetError("Installed Vulkan Portability doesn't implement the " VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " VK_MVK_IOS_SURFACE_EXTENSION_NAME " extensions"); + SDL_SetError("Installed Vulkan Portability doesn't implement the " + VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " + VK_MVK_IOS_SURFACE_EXTENSION_NAME " extensions"); goto fail; } @@ -170,9 +173,9 @@ void UIKit_Vulkan_UnloadLibrary(_THIS) } SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS, - SDL_Window *window, - unsigned *count, - const char **names) + SDL_Window *window, + unsigned *count, + const char **names) { static const char *const extensionsForUIKit[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_EXT_METAL_SURFACE_EXTENSION_NAME @@ -183,25 +186,25 @@ SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS, } return SDL_Vulkan_GetInstanceExtensions_Helper( - count, names, SDL_arraysize(extensionsForUIKit), - extensionsForUIKit); + count, names, SDL_arraysize(extensionsForUIKit), + extensionsForUIKit); } SDL_bool UIKit_Vulkan_CreateSurface(_THIS, - SDL_Window *window, - VkInstance instance, - VkSurfaceKHR *surface) + SDL_Window *window, + VkInstance instance, + VkSurfaceKHR *surface) { PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; PFN_vkCreateMetalSurfaceEXT vkCreateMetalSurfaceEXT = (PFN_vkCreateMetalSurfaceEXT)vkGetInstanceProcAddr( - (VkInstance)instance, - "vkCreateMetalSurfaceEXT"); + (VkInstance)instance, + "vkCreateMetalSurfaceEXT"); PFN_vkCreateIOSSurfaceMVK vkCreateIOSSurfaceMVK = (PFN_vkCreateIOSSurfaceMVK)vkGetInstanceProcAddr( - (VkInstance)instance, - "vkCreateIOSSurfaceMVK"); + (VkInstance)instance, + "vkCreateIOSSurfaceMVK"); VkResult result; SDL_MetalView metalview; @@ -211,8 +214,9 @@ SDL_bool UIKit_Vulkan_CreateSurface(_THIS, } if (!vkCreateMetalSurfaceEXT && !vkCreateIOSSurfaceMVK) { - SDL_SetError(VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " VK_MVK_IOS_SURFACE_EXTENSION_NAME - " extensions are not enabled in the Vulkan instance."); + SDL_SetError(VK_EXT_METAL_SURFACE_EXTENSION_NAME " or " + VK_MVK_IOS_SURFACE_EXTENSION_NAME + " extensions are not enabled in the Vulkan instance."); return SDL_FALSE; } @@ -227,7 +231,7 @@ SDL_bool UIKit_Vulkan_CreateSurface(_THIS, createInfo.pNext = NULL; createInfo.flags = 0; createInfo.pLayer = (__bridge const CAMetalLayer *) - UIKit_Metal_GetLayer(_this, metalview); + UIKit_Metal_GetLayer(_this, metalview); result = vkCreateMetalSurfaceEXT(instance, &createInfo, NULL, surface); if (result != VK_SUCCESS) { UIKit_Metal_DestroyView(_this, metalview); @@ -242,7 +246,7 @@ SDL_bool UIKit_Vulkan_CreateSurface(_THIS, createInfo.flags = 0; createInfo.pView = (const void *)metalview; result = vkCreateIOSSurfaceMVK(instance, &createInfo, - NULL, surface); + NULL, surface); if (result != VK_SUCCESS) { UIKit_Metal_DestroyView(_this, metalview); SDL_SetError("vkCreateIOSSurfaceMVK failed: %s", diff --git a/src/video/uikit/SDL_uikitwindow.h b/src/video/uikit/SDL_uikitwindow.h index 7e7e7479f..7ca9b475e 100644 --- a/src/video/uikit/SDL_uikitwindow.h +++ b/src/video/uikit/SDL_uikitwindow.h @@ -40,17 +40,17 @@ extern void UIKit_GetWindowSizeInPixels(_THIS, SDL_Window * window, int *w, int extern SDL_bool UIKit_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo * info); -extern NSUInteger UIKit_GetSupportedOrientations(SDL_Window *window); +extern NSUInteger UIKit_GetSupportedOrientations(SDL_Window * window); @class UIWindow; @interface SDL_WindowData : NSObject -@property(nonatomic, strong) UIWindow *uiwindow; -@property(nonatomic, strong) SDL_uikitviewcontroller *viewcontroller; +@property (nonatomic, strong) UIWindow *uiwindow; +@property (nonatomic, strong) SDL_uikitviewcontroller *viewcontroller; /* Array of SDL_uikitviews owned by this window. */ -@property(nonatomic, copy) NSMutableArray *views; +@property (nonatomic, copy) NSMutableArray *views; @end diff --git a/src/video/uikit/SDL_uikitwindow.m b/src/video/uikit/SDL_uikitwindow.m index b58877b8e..7b8dfff56 100644 --- a/src/video/uikit/SDL_uikitwindow.m +++ b/src/video/uikit/SDL_uikitwindow.m @@ -83,22 +83,24 @@ @end -static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bool created) + +static int +SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bool created) { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); - SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *)display->driverdata; + SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *) display->driverdata; SDL_uikitview *view; CGRect frame = UIKit_ComputeViewFrame(window, displaydata.uiscreen); - int width = (int)frame.size.width; - int height = (int)frame.size.height; + int width = (int) frame.size.width; + int height = (int) frame.size.height; SDL_WindowData *data = [[SDL_WindowData alloc] init]; if (!data) { return SDL_OutOfMemory(); } - window->driverdata = (void *)CFBridgingRetain(data); + window->driverdata = (void *) CFBridgingRetain(data); data.uiwindow = uiwindow; @@ -106,9 +108,9 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo window->flags &= ~SDL_WINDOW_HIDDEN; if (displaydata.uiscreen != [UIScreen mainScreen]) { - window->flags &= ~SDL_WINDOW_RESIZABLE; /* window is NEVER resizable */ - window->flags &= ~SDL_WINDOW_INPUT_FOCUS; /* never has input focus */ - window->flags |= SDL_WINDOW_BORDERLESS; /* never has a status bar. */ + window->flags &= ~SDL_WINDOW_RESIZABLE; /* window is NEVER resizable */ + window->flags &= ~SDL_WINDOW_INPUT_FOCUS; /* never has input focus */ + window->flags |= SDL_WINDOW_BORDERLESS; /* never has a status bar. */ } #if !TARGET_OS_TV @@ -123,7 +125,7 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo NSUInteger orients = UIKit_GetSupportedOrientations(window); BOOL supportsLandscape = (orients & UIInterfaceOrientationMaskLandscape) != 0; - BOOL supportsPortrait = (orients & (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown)) != 0; + BOOL supportsPortrait = (orients & (UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskPortraitUpsideDown)) != 0; /* Make sure the width/height are oriented correctly */ if ((width > height && !supportsLandscape) || (height > width && !supportsPortrait)) { @@ -156,11 +158,12 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo return 0; } -int UIKit_CreateWindow(_THIS, SDL_Window *window) +int +UIKit_CreateWindow(_THIS, SDL_Window *window) { @autoreleasepool { SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); - SDL_DisplayData *data = (__bridge SDL_DisplayData *)display->driverdata; + SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata; SDL_Window *other; /* We currently only handle a single window per display on iOS */ @@ -201,7 +204,7 @@ int UIKit_CreateWindow(_THIS, SDL_Window *window) } if (data.uiscreen == [UIScreen mainScreen]) { - if (window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) { + if (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) { [UIApplication sharedApplication].statusBarHidden = YES; } else { [UIApplication sharedApplication].statusBarHidden = NO; @@ -226,23 +229,25 @@ int UIKit_CreateWindow(_THIS, SDL_Window *window) return 1; } -void UIKit_SetWindowTitle(_THIS, SDL_Window *window) +void +UIKit_SetWindowTitle(_THIS, SDL_Window * window) { @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; data.viewcontroller.title = @(window->title); } } -void UIKit_ShowWindow(_THIS, SDL_Window *window) +void +UIKit_ShowWindow(_THIS, SDL_Window * window) { @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; [data.uiwindow makeKeyAndVisible]; /* Make this window the current mouse focus for touch input */ SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window); - SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *)display->driverdata; + SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *) display->driverdata; if (displaydata.uiscreen == [UIScreen mainScreen]) { SDL_SetMouseFocus(window); SDL_SetKeyboardFocus(window); @@ -250,15 +255,17 @@ void UIKit_ShowWindow(_THIS, SDL_Window *window) } } -void UIKit_HideWindow(_THIS, SDL_Window *window) +void +UIKit_HideWindow(_THIS, SDL_Window * window) { @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; data.uiwindow.hidden = YES; } } -void UIKit_RaiseWindow(_THIS, SDL_Window *window) +void +UIKit_RaiseWindow(_THIS, SDL_Window * window) { /* We don't currently offer a concept of "raising" the SDL window, since * we only allow one per display, in the iOS fashion. @@ -267,9 +274,10 @@ void UIKit_RaiseWindow(_THIS, SDL_Window *window) _this->GL_MakeCurrent(_this, _this->current_glwin, _this->current_glctx); } -static void UIKit_UpdateWindowBorder(_THIS, SDL_Window *window) +static void +UIKit_UpdateWindowBorder(_THIS, SDL_Window * window) { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; SDL_uikitviewcontroller *viewcontroller = data.viewcontroller; #if !TARGET_OS_TV @@ -296,31 +304,35 @@ static void UIKit_UpdateWindowBorder(_THIS, SDL_Window *window) [viewcontroller.view layoutIfNeeded]; } -void UIKit_SetWindowBordered(_THIS, SDL_Window *window, SDL_bool bordered) +void +UIKit_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered) { @autoreleasepool { UIKit_UpdateWindowBorder(_this, window); } } -void UIKit_SetWindowFullscreen(_THIS, SDL_Window *window, SDL_VideoDisplay *display, SDL_bool fullscreen) +void +UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen) { @autoreleasepool { UIKit_UpdateWindowBorder(_this, window); } } -void UIKit_SetWindowMouseGrab(_THIS, SDL_Window *window, SDL_bool grabbed) +void +UIKit_SetWindowMouseGrab(_THIS, SDL_Window * window, SDL_bool grabbed) { /* There really isn't a concept of window grab or cursor confinement on iOS */ } -void UIKit_UpdatePointerLock(_THIS, SDL_Window *window) +void +UIKit_UpdatePointerLock(_THIS, SDL_Window * window) { #if !TARGET_OS_TV #if defined(__IPHONE_14_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; SDL_uikitviewcontroller *viewcontroller = data.viewcontroller; if (@available(iOS 14.0, *)) { [viewcontroller setNeedsUpdateOfPrefersPointerLocked]; @@ -330,11 +342,12 @@ void UIKit_UpdatePointerLock(_THIS, SDL_Window *window) #endif /* !TARGET_OS_TV */ } -void UIKit_DestroyWindow(_THIS, SDL_Window *window) +void +UIKit_DestroyWindow(_THIS, SDL_Window * window) { @autoreleasepool { if (window->driverdata != NULL) { - SDL_WindowData *data = (SDL_WindowData *)CFBridgingRelease(window->driverdata); + SDL_WindowData *data = (SDL_WindowData *) CFBridgingRelease(window->driverdata); NSArray *views = nil; [data.viewcontroller stopAnimation]; @@ -358,24 +371,18 @@ void UIKit_DestroyWindow(_THIS, SDL_Window *window) window->driverdata = NULL; } -void UIKit_GetWindowSizeInPixels(_THIS, SDL_Window *window, int *w, int *h) +void +UIKit_GetWindowSizeInPixels(_THIS, SDL_Window * window, int *w, int *h) +{ @autoreleasepool { - @autoreleasepool { - SDL_WindowData *windata = (__bridge SDL_WindowData *)window->driverdata; - UIView *view = windata.viewcontroller.view; - CGSize size = view.bounds.size; - CGFloat scale = 1.0; + SDL_WindowData *windata = (__bridge SDL_WindowData *) window->driverdata; + UIView *view = windata.viewcontroller.view; + CGSize size = view.bounds.size; + CGFloat scale = 1.0; - if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { - scale = windata.uiwindow.screen.nativeScale; - } - - /* Integer truncation of fractional values matches SDL_uikitmetalview and - * SDL_uikitopenglview. */ - *w = size.width * scale; - *h = size.height * scale; + if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) { + scale = windata.uiwindow.screen.nativeScale; } -} /* Integer truncation of fractional values matches SDL_uikitmetalview and * SDL_uikitopenglview. */ @@ -424,14 +431,14 @@ UIKit_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info) #if !TARGET_OS_TV NSUInteger -UIKit_GetSupportedOrientations(SDL_Window *window) +UIKit_GetSupportedOrientations(SDL_Window * window) { const char *hint = SDL_GetHint(SDL_HINT_ORIENTATIONS); NSUInteger validOrientations = UIInterfaceOrientationMaskAll; NSUInteger orientationMask = 0; @autoreleasepool { - SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata; + SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata; UIApplication *app = [UIApplication sharedApplication]; /* Get all possible valid orientations. If the app delegate doesn't tell @@ -490,7 +497,8 @@ UIKit_GetSupportedOrientations(SDL_Window *window) } #endif /* !TARGET_OS_TV */ -int SDL_iPhoneSetAnimationCallback(SDL_Window *window, int interval, void (*callback)(void *), void *callbackParam) +int +SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam) { if (!window || !window->driverdata) { return SDL_SetError("Invalid window");