-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathui_cocoatouch.m
More file actions
1582 lines (1381 loc) · 54.6 KB
/
Copy pathui_cocoatouch.m
File metadata and controls
1582 lines (1381 loc) · 54.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* RetroArch - A frontend for libretro.
* Copyright (C) 2011-2016 - Daniel De Matteis
*
* RetroArch is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <boolean.h>
#include <file/file_path.h>
#include <queues/task_queue.h>
#include <string/stdstring.h>
#include <retro_timers.h>
#include <defines/cocoa_defines.h>
#include "cocoa/cocoa_common.h"
#include "cocoa/apple_platform.h"
#ifdef HAVE_RETROARCH_PLAYLIST_MANAGER
#import "cocoa/RetroArchPlaylistManager.h"
#endif
#if defined(HAVE_COCOA_METAL)
#include "../../gfx/common/metal_view.h"
#endif
#include "../ui_companion_driver.h"
#include "../../audio/audio_driver.h"
#include "../../gfx/video_display_server.h"
#include "../../configuration.h"
#include "../../frontend/frontend.h"
#include "../../input/drivers/cocoa_input.h"
#include "../../input/input_driver.h"
#include "../../input/drivers_keyboard/keyboard_event_apple.h"
#include "../../retroarch.h"
#include "../../tasks/task_content.h"
#include "../../verbosity.h"
#include "../../core_info.h"
#if HAVE_SWIFT
#if TARGET_OS_TV
#import "RetroArchTV-Swift.h"
#else
#import "RetroArch-Swift.h"
#endif
#endif
#ifdef HAVE_MENU
#include "../../menu/menu_setting.h"
#endif
#ifdef HAVE_NETWORKING
#include "../../network/netplay/netplay_private.h"
#endif
#import <AVFoundation/AVFoundation.h>
#import <CoreFoundation/CoreFoundation.h>
#import <MetricKit/MetricKit.h>
#import <MetricKit/MXMetricManager.h>
#import "../../pkg/apple/WebServer/WebServer.h"
#ifdef HAVE_MFI
#import <GameController/GameController.h>
#import <GameController/GCMouse.h>
#import <GameController/GCMouseInput.h>
#endif
#ifdef HAVE_KSCRASH
#import <KSCrash.h>
#import <KSCrashConfiguration.h>
#import <KSCrashReportStore.h>
#import <KSCrashInstallation.h>
#import <KSCrashReport.h>
#endif
#ifdef HAVE_SDL2
#define SDL_MAIN_HANDLED
#include "SDL.h"
#endif
#if defined(HAVE_COCOA_METAL) || defined(HAVE_COCOATOUCH)
#import "JITSupport.h"
id<ApplePlatform> apple_platform;
#else
static id apple_platform;
#endif
static void ui_companion_cocoatouch_event_command(
void *data, enum event_command cmd) { }
static struct string_list *ui_companion_cocoatouch_get_app_icons(void)
{
static struct string_list *list = NULL;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
union string_list_elem_attr attr;
attr.i = 0;
NSDictionary *iconfiles = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIcons"];
NSString *primary;
const char *cstr;
#if TARGET_OS_TV
primary = iconfiles[@"CFBundlePrimaryIcon"];
#else
primary = iconfiles[@"CFBundlePrimaryIcon"][@"CFBundleIconName"];
#endif
list = string_list_new();
cstr = [primary cStringUsingEncoding:kCFStringEncodingUTF8];
if (cstr)
string_list_append(list, cstr, attr);
NSArray<NSString *> *alts;
#if TARGET_OS_TV
alts = iconfiles[@"CFBundleAlternateIcons"];
#else
alts = [iconfiles[@"CFBundleAlternateIcons"] allKeys];
#endif
NSArray<NSString *> *sorted = [alts sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (NSString *str in sorted)
{
cstr = [str cStringUsingEncoding:kCFStringEncodingUTF8];
if (cstr)
string_list_append(list, cstr, attr);
}
});
return list;
}
static void ui_companion_cocoatouch_set_app_icon(const char *iconName)
{
NSString *str;
if (!string_is_equal(iconName, "Default"))
str = [NSString stringWithCString:iconName encoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] setAlternateIconName:str completionHandler:nil];
}
static uintptr_t ui_companion_cocoatouch_get_app_icon_texture(const char *icon)
{
static NSMutableDictionary<NSString *, NSNumber *> *textures = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
textures = [NSMutableDictionary dictionaryWithCapacity:6];
});
NSString *iconName = [NSString stringWithUTF8String:icon];
if (!textures[iconName])
{
UIImage *img = [UIImage imageNamed:iconName];
if (!img)
{
RARCH_LOG("[Cocoa] Could not load %s.\n", icon);
return 0;
}
NSData *png = UIImagePNGRepresentation(img);
if (!png)
{
RARCH_LOG("[Cocoa] Could not get png for %s.\n", icon);
return 0;
}
uintptr_t item;
gfx_display_reset_textures_list_buffer(&item, TEXTURE_FILTER_MIPMAP_LINEAR,
(void*)[png bytes], (unsigned int)[png length], IMAGE_TYPE_PNG,
NULL, NULL);
textures[iconName] = [NSNumber numberWithUnsignedLong:item];
}
return [textures[iconName] unsignedLongValue];
}
void get_ios_version(int *major, int *minor)
{
static int savedMajor, savedMinor;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^ {
NSArray *decomposed_os_version = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if (decomposed_os_version.count > 0)
savedMajor = (int)[decomposed_os_version[0] integerValue];
if (decomposed_os_version.count > 1)
savedMinor = (int)[decomposed_os_version[1] integerValue];
});
if (major) *major = savedMajor;
if (minor) *minor = savedMinor;
}
bool ios_running_on_ipad(void)
{
return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
}
/* Input helpers: This is kept here because it needs ObjC */
static void handle_touch_event(NSArray* touches)
{
#if !TARGET_OS_TV
unsigned i;
cocoa_input_data_t *apple = (cocoa_input_data_t*)
input_state_get_ptr()->current_data;
float scale = cocoa_screen_get_native_scale();
if (!apple)
return;
apple->touch_count = 0;
for (i = 0; i < touches.count && (apple->touch_count < MAX_TOUCHES); i++)
{
UITouch *touch = [touches objectAtIndex:i];
CGPoint coord = [touch locationInView:[touch view]];
if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled)
{
apple->touches[apple->touch_count ].screen_x = coord.x * scale;
apple->touches[apple->touch_count ++].screen_y = coord.y * scale;
}
}
#endif
}
#ifndef HAVE_APPLE_STORE
/* iOS7 Keyboard support */
@interface UIEvent(iOS7Keyboard)
@property(readonly, nonatomic) long long _keyCode;
@property(readonly, nonatomic) _Bool _isKeyDown;
@property(retain, nonatomic) NSString *_privateInput;
@property(nonatomic) long long _modifierFlags;
- (struct __IOHIDEvent { }*)_hidEvent;
@end
@interface UIApplication(iOS7Keyboard)
- (void)handleKeyUIEvent:(UIEvent*)event;
- (id)_keyCommandForEvent:(UIEvent*)event;
@end
#endif
@interface RApplication : UIApplication
@end
@implementation RApplication
#ifndef HAVE_APPLE_STORE
/* Keyboard handler for iOS 7. */
/* This is copied here as it isn't
* defined in any standard iOS header */
enum
{
NSAlphaShiftKeyMask = 1 << 16,
NSShiftKeyMask = 1 << 17,
NSControlKeyMask = 1 << 18,
NSAlternateKeyMask = 1 << 19,
NSCommandKeyMask = 1 << 20,
NSNumericPadKeyMask = 1 << 21,
NSHelpKeyMask = 1 << 22,
NSFunctionKeyMask = 1 << 23,
NSDeviceIndependentModifierFlagsMask = 0xffff0000U
};
/* This is specifically for iOS 9, according to the private headers */
-(void)handleKeyUIEvent:(UIEvent *)event
{
/* This gets called twice with the same timestamp
* for each keypress, that's fine for polling
* but is bad for business with events. */
static double last_time_stamp;
if (last_time_stamp == event.timestamp)
return [super handleKeyUIEvent:event];
last_time_stamp = event.timestamp;
/* If the _hidEvent is NULL, [event _keyCode] will crash.
* (This happens with the on screen keyboard). */
if (event._hidEvent)
{
NSString *ch = (NSString*)event._privateInput;
uint32_t character = 0;
uint32_t mod = 0;
NSUInteger mods = event._modifierFlags;
if (mods & NSAlphaShiftKeyMask)
mod |= RETROKMOD_CAPSLOCK;
if (mods & NSShiftKeyMask)
mod |= RETROKMOD_SHIFT;
if (mods & NSControlKeyMask)
mod |= RETROKMOD_CTRL;
if (mods & NSAlternateKeyMask)
mod |= RETROKMOD_ALT;
if (mods & NSCommandKeyMask)
mod |= RETROKMOD_META;
if (mods & NSNumericPadKeyMask)
mod |= RETROKMOD_NUMLOCK;
if (ch && ch.length != 0)
{
unsigned i;
character = [ch characterAtIndex:0];
apple_input_keyboard_event(event._isKeyDown,
(uint32_t)event._keyCode, 0, mod,
RETRO_DEVICE_KEYBOARD);
for (i = 1; i < ch.length; i++)
apple_input_keyboard_event(event._isKeyDown,
0, [ch characterAtIndex:i], mod,
RETRO_DEVICE_KEYBOARD);
}
apple_input_keyboard_event(event._isKeyDown,
(uint32_t)event._keyCode, character, mod,
RETRO_DEVICE_KEYBOARD);
}
[super handleKeyUIEvent:event];
}
/* This is for iOS versions < 9.0 */
- (id)_keyCommandForEvent:(UIEvent*)event
{
/* This gets called twice with the same timestamp
* for each keypress, that's fine for polling
* but is bad for business with events. */
static double last_time_stamp;
if (last_time_stamp == event.timestamp)
return [super _keyCommandForEvent:event];
last_time_stamp = event.timestamp;
/* If the _hidEvent is null, [event _keyCode] will crash.
* (This happens with the on screen keyboard). */
if (event._hidEvent)
{
NSString *ch = (NSString*)event._privateInput;
uint32_t character = 0;
uint32_t mod = 0;
NSUInteger mods = event._modifierFlags;
if (mods & NSAlphaShiftKeyMask)
mod |= RETROKMOD_CAPSLOCK;
if (mods & NSShiftKeyMask)
mod |= RETROKMOD_SHIFT;
if (mods & NSControlKeyMask)
mod |= RETROKMOD_CTRL;
if (mods & NSAlternateKeyMask)
mod |= RETROKMOD_ALT;
if (mods & NSCommandKeyMask)
mod |= RETROKMOD_META;
if (mods & NSNumericPadKeyMask)
mod |= RETROKMOD_NUMLOCK;
if (ch && ch.length != 0)
{
unsigned i;
character = [ch characterAtIndex:0];
apple_input_keyboard_event(event._isKeyDown,
(uint32_t)event._keyCode, 0, mod,
RETRO_DEVICE_KEYBOARD);
for (i = 1; i < ch.length; i++)
apple_input_keyboard_event(event._isKeyDown,
0, [ch characterAtIndex:i], mod,
RETRO_DEVICE_KEYBOARD);
}
apple_input_keyboard_event(event._isKeyDown,
(uint32_t)event._keyCode, character, mod,
RETRO_DEVICE_KEYBOARD);
}
return [super _keyCommandForEvent:event];
}
#else
- (void)handleUIPress:(UIPress *)press withEvent:(UIPressesEvent *)event down:(BOOL)down
{
NSString *ch;
uint32_t character = 0;
uint32_t mod = 0;
NSUInteger mods = 0;
if (@available(iOS 13.4, tvOS 13.4, *))
{
ch = (NSString*)press.key.characters;
mods = event.modifierFlags;
}
if (mods & UIKeyModifierAlphaShift)
mod |= RETROKMOD_CAPSLOCK;
if (mods & UIKeyModifierShift)
mod |= RETROKMOD_SHIFT;
if (mods & UIKeyModifierControl)
mod |= RETROKMOD_CTRL;
if (mods & UIKeyModifierAlternate)
mod |= RETROKMOD_ALT;
if (mods & UIKeyModifierCommand)
mod |= RETROKMOD_META;
if (mods & UIKeyModifierNumericPad)
mod |= RETROKMOD_NUMLOCK;
if (ch && ch.length != 0)
{
unsigned i;
character = [ch characterAtIndex:0];
apple_input_keyboard_event(down,
(uint32_t)press.key.keyCode, 0, mod,
RETRO_DEVICE_KEYBOARD);
for (i = 1; i < ch.length; i++)
apple_input_keyboard_event(down,
0, [ch characterAtIndex:i], mod,
RETRO_DEVICE_KEYBOARD);
}
if (@available(iOS 13.4, tvOS 13.4, *))
apple_input_keyboard_event(down,
(uint32_t)press.key.keyCode, character, mod,
RETRO_DEVICE_KEYBOARD);
}
- (void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event
{
/* Skip processing if iOS native keyboard (UITextField) is active
* to prevent double-processing and memory corruption in UIKit's string formatting */
if (ios_keyboard_active())
return [super pressesBegan:presses withEvent:event];
for (UIPress *press in presses)
[self handleUIPress:press withEvent:event down:YES];
[super pressesBegan:presses withEvent:event];
}
- (void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(UIPressesEvent *)event
{
/* Skip processing if iOS native keyboard (UITextField) is active
* to prevent double-processing and memory corruption in UIKit's string formatting */
if (ios_keyboard_active())
return [super pressesEnded:presses withEvent:event];
for (UIPress *press in presses)
[self handleUIPress:press withEvent:event down:NO];
[super pressesEnded:presses withEvent:event];
}
#endif
#define GSEVENT_TYPE_KEYDOWN 10
#define GSEVENT_TYPE_KEYUP 11
- (void)sendEvent:(UIEvent *)event
{
[super sendEvent:event];
if (@available(iOS 13.4, tvOS 13.4, *))
{
if (event.type == UIEventTypeHover)
return;
}
if (event.allTouches.count)
handle_touch_event(event.allTouches.allObjects);
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000
{
int major, minor;
get_ios_version(&major, &minor);
if ((major < 7) && [event respondsToSelector:@selector(_gsEvent)])
{
/* Keyboard event hack for iOS versions prior to iOS 7.
*
* Derived from:
* http://nacho4d-nacho4d.blogspot.com/2012/01/
* catching-keyboard-events-in-ios.html
*/
const uint8_t *eventMem = objc_unretainedPointer([event performSelector:@selector(_gsEvent)]);
int eventType = eventMem ? *(int*)&eventMem[8] : 0;
switch (eventType)
{
case GSEVENT_TYPE_KEYDOWN:
case GSEVENT_TYPE_KEYUP:
apple_input_keyboard_event(eventType == GSEVENT_TYPE_KEYDOWN,
*(uint16_t*)&eventMem[0x3C], 0, 0, RETRO_DEVICE_KEYBOARD);
break;
}
}
}
#endif
}
@end
#ifdef HAVE_COCOA_METAL
@implementation MetalLayerView
+ (Class)layerClass {
return [CAMetalLayer class];
}
- (instancetype)init {
self = [super init];
if (self)
[self setupMetalLayer];
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self)
[self setupMetalLayer];
return self;
}
- (CAMetalLayer *)metalLayer {
return (CAMetalLayer *)self.layer;
}
- (void)setupMetalLayer {
self.metalLayer.device = MTLCreateSystemDefaultDevice();
self.metalLayer.contentsScale = cocoa_screen_get_native_scale();
self.metalLayer.opaque = YES;
}
@end
#endif
#if TARGET_OS_IOS
@interface RetroArch_iOS () <MXMetricManagerSubscriber, UIPointerInteractionDelegate>
@end
#endif
@interface RetroArch_iOS () <UITextFieldDelegate>
/* 'retain' works identically to 'strong' under ARC but unlike 'strong'
* is also accepted by the pre-ARC compiler - so the file remains
* buildable under MRR without a separate code path. */
@property (nonatomic, retain) UITextField *keyboardTextField;
@property (nonatomic, copy) void(^keyboardCompletionCallback)(const char *);
@property (nonatomic, assign) char **keyboardBufferPtr;
@property (nonatomic, assign) size_t *keyboardSizePtr;
@property (nonatomic, assign) size_t *keyboardPtrPtr;
@property (nonatomic, assign) char *keyboardAllocatedBuffer;
@end
@implementation RetroArch_iOS
#pragma mark - ApplePlatform
-(id)renderView { return _renderView; }
-(bool)hasFocus
{
return [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
}
- (void)setViewType:(apple_view_type_t)vt
{
if (vt == _vt)
return;
_vt = vt;
if (_renderView != nil)
{
[_renderView removeFromSuperview];
/* _renderView holds a +1 retain regardless of which path below
* created it (the Metal / Vulkan branches take +1 directly from
* +new; the OPENGL_ES branch retains the singleton returned by
* glkitview_init()). Release it here so the ownership invariant
* is balanced before we nil the ivar. Under ARC this is a
* no-op and the implicit __strong ivar handles the release when
* _renderView is assigned nil. */
RARCH_RELEASE(_renderView);
_renderView = nil;
}
switch (vt)
{
#ifdef HAVE_COCOA_METAL
case APPLE_VIEW_TYPE_VULKAN:
/* +new returns a +1 object; that retain transfers into
* _renderView and satisfies the ivar's ownership invariant
* directly. No extra RARCH_RETAIN needed. */
_renderView = [MetalLayerView new];
#if TARGET_OS_IOS
_renderView.multipleTouchEnabled = YES;
#endif
break;
case APPLE_VIEW_TYPE_METAL:
{
MetalView *v = [MetalView new];
v.paused = YES;
v.enableSetNeedsDisplay = NO;
#if TARGET_OS_IOS
v.multipleTouchEnabled = YES;
#endif
_renderView = v;
}
break;
#endif
case APPLE_VIEW_TYPE_OPENGL_ES:
/* glkitview_init() returns an unretained pointer to the
* cocoa_gl_ctx.m singleton. Retain explicitly so _renderView
* matches the +1 invariant the Metal / Vulkan paths get from
* +new. Under ARC RARCH_RETAIN is a no-op and the implicit
* __strong ivar assignment takes the retain via objc_storeStrong. */
_renderView = RARCH_RETAIN((BRIDGE GLKView*)glkitview_init());
break;
case APPLE_VIEW_TYPE_NONE:
default:
return;
}
_renderView.translatesAutoresizingMaskIntoConstraints = NO;
UIView *rootView = [CocoaView get].view;
[rootView addSubview:_renderView];
#if TARGET_OS_IOS
if (@available(iOS 13.4, *))
{
/* +[UIPointerInteraction alloc] initWithDelegate: returns +1.
* -addInteraction: retains internally, so autorelease our own
* +1 to balance under MRR. ARC already releases on scope
* exit; the macro is a no-op there. RARCH_AUTORELEASE is a
* statement-only macro (it expands to ((void)0) under ARC)
* so it must appear on its own line rather than wrapping the
* rvalue. */
UIPointerInteraction *interaction = [[UIPointerInteraction alloc] initWithDelegate:self];
RARCH_AUTORELEASE(interaction);
[_renderView addInteraction:interaction];
_renderView.userInteractionEnabled = YES;
}
#endif
[[_renderView.topAnchor constraintEqualToAnchor:rootView.topAnchor] setActive:YES];
[[_renderView.bottomAnchor constraintEqualToAnchor:rootView.bottomAnchor] setActive:YES];
[[_renderView.leadingAnchor constraintEqualToAnchor:rootView.leadingAnchor] setActive:YES];
[[_renderView.trailingAnchor constraintEqualToAnchor:rootView.trailingAnchor] setActive:YES];
[_renderView layoutIfNeeded];
}
- (apple_view_type_t)viewType { return _vt; }
- (void)setVideoMode:(gfx_ctx_mode_t)mode
{
#ifdef HAVE_COCOA_METAL
MetalView *metalView = (MetalView*) _renderView;
CGFloat scale = [[UIScreen mainScreen] scale];
[metalView setDrawableSize:CGSizeMake(
_renderView.bounds.size.width * scale,
_renderView.bounds.size.height * scale
)];
#endif
}
- (void)setCursorVisible:(bool)v { /* no-op for iOS */ }
- (bool)setDisableDisplaySleep:(bool)disable
{
#if TARGET_OS_TV
[[UIApplication sharedApplication] setIdleTimerDisabled:disable];
return YES;
#else
return NO;
#endif
}
+ (RetroArch_iOS*)get { return (RetroArch_iOS*)[[UIApplication sharedApplication] delegate]; }
-(NSString*)documentsDirectory
{
if (_documentsDirectory == nil)
{
#if TARGET_OS_IOS
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
#elif TARGET_OS_TV
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
#endif
_documentsDirectory = paths.firstObject;
}
return _documentsDirectory;
}
- (void)handleAudioSessionInterruption:(NSNotification *)notification
{
NSNumber *type = notification.userInfo[AVAudioSessionInterruptionTypeKey];
if (![type isKindOfClass:[NSNumber class]])
return;
if ([type unsignedIntegerValue] == AVAudioSessionInterruptionTypeBegan)
{
RARCH_DBG("[Cocoa] AudioSession Interruption Began.\n");
audio_driver_stop();
}
else if ([type unsignedIntegerValue] == AVAudioSessionInterruptionTypeEnded)
{
RARCH_DBG("[Cocoa] AudioSession Interruption Ended.\n");
audio_driver_start(false);
}
}
#ifdef HAVE_KSCRASH
- (NSString *)crashReportsPath
{
/* Store crash reports in Documents directory for user access */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths firstObject];
return [documentsPath stringByAppendingPathComponent:@"CrashReports"];
}
- (void)initKSCrash
{
NSString *crashReportsPath = [self crashReportsPath];
/* Create the crash reports directory if it doesn't exist */
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *createError = nil;
if (![fileManager fileExistsAtPath:crashReportsPath])
{
[fileManager createDirectoryAtPath:crashReportsPath
withIntermediateDirectories:YES
attributes:nil
error:&createError];
if (createError)
{
NSLog(@"[KSCrash] Failed to create crash reports directory: %@\n", createError);
return;
}
}
/* Configure KSCrash for local storage only.
* Autorelease the +1 from +new: -installWithConfiguration: keeps
* its own reference via config.reportStoreConfiguration retain and
* KSCrash's own retain of the config, so our local can be released
* at autorelease-pool drain without dangling any of those.
* RARCH_AUTORELEASE is a statement-only macro; call it on its own
* line after the assignment. No-op under ARC. */
KSCrashConfiguration *config = [KSCrashConfiguration new];
RARCH_AUTORELEASE(config);
config.installPath = crashReportsPath;
KSCrashReportStoreConfiguration *storeConfig = [KSCrashReportStoreConfiguration new];
RARCH_AUTORELEASE(storeConfig);
storeConfig.reportsPath = crashReportsPath;
storeConfig.appName = @"RetroArch";
storeConfig.maxReportCount = 10; /* Keep last 10 crash reports */
config.reportStoreConfiguration = storeConfig;
/* Set appropriate monitors */
if (jit_available())
config.monitors = KSCrashMonitorTypeDebuggerSafe;
else
config.monitors = KSCrashMonitorTypeProductionSafe;
/* Enable useful debugging features */
config.enableMemoryIntrospection = YES;
config.enableQueueNameSearch = YES;
config.addConsoleLogToReport = YES;
/* Install KSCrash without any network sink */
NSError *installError = nil;
if (![[KSCrash sharedInstance] installWithConfiguration:config error:&installError])
{
NSLog(@"[KSCrash] Failed to install crash reporter: %@\n", installError);
return;
}
NSLog(@"[KSCrash] reports will be stored in: %@\n", crashReportsPath);
}
- (void)processKSCrashReports
{
/* Check if we crashed last launch */
if (![[KSCrash sharedInstance] crashedLastLaunch])
return;
if ([[[KSCrash sharedInstance] reportStore] reportCount] <= 0)
return;
RARCH_LOG("[KSCrash] crash report available in Documents/CrashReports\n");
/* Process crash reports to strip binary_images section */
KSCrashReportStore *store = [[KSCrash sharedInstance] reportStore];
NSArray<NSNumber *> *reportIDs = [store reportIDs];
for (NSNumber *reportIDNum in reportIDs)
{
int64_t reportID = [reportIDNum longLongValue];
KSCrashReportDictionary *report = [store reportForID:reportID];
if (!report)
continue;
/* -mutableCopy returns +1. Inside a for-loop that's a
* per-iteration leak under MRR; autorelease so it is cleaned up
* when the pool drains at the next run-loop iteration.
* Statement-only macro, so on its own line. No-op under ARC. */
NSMutableDictionary *mutableReport = [report.value mutableCopy];
RARCH_AUTORELEASE(mutableReport);
/* Remove binary_images to reduce file size */
if ([mutableReport objectForKey:@"binary_images"])
[mutableReport removeObjectForKey:@"binary_images"];
/* Save pretty-printed version as standalone file */
NSData *prettyData = [NSJSONSerialization dataWithJSONObject:mutableReport
options:NSJSONWritingPrettyPrinted
error:nil];
if (prettyData)
{
NSString *reportPath = [NSString stringWithFormat:@"%@/report-%lld.json",
[self crashReportsPath], reportID];
[prettyData writeToFile:reportPath options:NSDataWritingAtomic error:nil];
RARCH_LOG("[KSCrash] Saved stripped report %lld to: %s\n",
reportID, [reportPath UTF8String]);
}
/* Log minified JSON on a single line for easy extraction */
NSData *minifiedData = [NSJSONSerialization dataWithJSONObject:mutableReport
options:0 /* no pretty printing */
error:nil];
if (minifiedData)
{
/* +1 from alloc+init; per-iteration leak inside the for-loop
* under MRR without an autorelease. Statement-only macro, so
* on its own line. No-op under ARC. */
NSString *jsonString = [[NSString alloc] initWithData:minifiedData
encoding:NSUTF8StringEncoding];
RARCH_AUTORELEASE(jsonString);
if (jsonString)
{
/* Log with a unique marker that can be extracted with grep/sed */
RARCH_LOG("[KSCrash] Report %lld follows on next line\n", reportID);
RARCH_LOG("%s\n", [jsonString UTF8String]);
}
}
/* Delete the report from KSCrash store to prevent re-logging on next launch */
[store deleteReportWithID:reportID];
}
if (reportIDs.count > 0)
RARCH_LOG("[KSCrash] Processed and removed %lu report(s) from store\n", (unsigned long)reportIDs.count);
}
#endif
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
#ifdef HAVE_KSCRASH
[self initKSCrash];
#endif
char arguments[] = "retroarch";
char *argv[] = {arguments, NULL};
int argc = 1;
apple_platform = self;
if ([NSUserDefaults.standardUserDefaults boolForKey:@"restore_default_config"])
{
[NSUserDefaults.standardUserDefaults setBool:NO forKey:@"restore_default_config"];
[NSUserDefaults.standardUserDefaults setObject:@"" forKey:@FILE_PATH_MAIN_CONFIG];
// Get the Caches directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths firstObject];
// Define the original and new file paths
NSString *originalPath = [cachesDirectory stringByAppendingPathComponent:@"RetroArch/config/retroarch.cfg"];
/* +1 from alloc+init; autorelease so scope-exit cleans up under
* MRR the same way ARC does. Statement-only macro, so on its
* own line. No-op under ARC. */
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
RARCH_AUTORELEASE(dateFormatter);
[dateFormatter setDateFormat:@"HHmm-yyMMdd"];
NSString *timestamp = [dateFormatter stringFromDate:[NSDate date]];
NSString *newPath = [cachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"RetroArch/config/RetroArch-%@.cfg", timestamp]];
// File manager instance
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the file exists and rename it
if ([fileManager fileExistsAtPath:originalPath])
{
NSError *error = nil;
if ([fileManager moveItemAtPath:originalPath toPath:newPath error:&error])
NSLog(@"File renamed to %@", newPath);
else
NSLog(@"Error renaming file: %@", error.localizedDescription);
}
else
NSLog(@"File does not exist at path %@", originalPath);
}
[self setDelegate:self];
/* Setup window.
* self.window is a retain property (see apple_platform.h); the
* setter takes its own retain. Autorelease the +1 from alloc+init
* via a temp so the setter's retain is the sole owner under MRR.
* Under ARC the strong setter retains and ARC scope-releases the
* temp. Statement-only macro, so RARCH_AUTORELEASE goes on its
* own line. */
UIWindow *win = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
RARCH_AUTORELEASE(win);
self.window = win;
[self.window makeKeyAndVisible];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
[self showGameView];
rarch_main(argc, argv, NULL);
#ifdef HAVE_KSCRASH
[self processKSCrashReports];
#endif
uico_driver_state_t *uico_st = uico_state_get_ptr();
rarch_setting_t *appicon_setting = menu_setting_find_enum(MENU_ENUM_LABEL_APPICON_SETTINGS);
struct string_list *icons;
if ( appicon_setting
&& uico_st->drv
&& uico_st->drv->get_app_icons
&& (icons = uico_st->drv->get_app_icons())
&& icons->size > 1)
{
int i;
size_t _len = 0;
char *options = NULL;
const char *icon_name;
appicon_setting->default_value.string = icons->elems[0].data;
icon_name = [[application alternateIconName] cStringUsingEncoding:kCFStringEncodingUTF8]; /* need to ask uico_st for this */
for (i = 0; i < (int)icons->size; i++)
{
_len += strlen(icons->elems[i].data) + 1;
if (string_is_equal(icon_name, icons->elems[i].data))
appicon_setting->value.target.string = icons->elems[i].data;
}
options = (char*)calloc(_len, sizeof(char));
string_list_join_concat(options, _len, icons, "|");
if (appicon_setting->values)
free((void*)appicon_setting->values);
appicon_setting->values = options;
}
#if TARGET_OS_TV
update_topshelf();
#endif
#if HAVE_SWIFT
if (@available(iOS 16.0, tvOS 16.0, *)) {
[RetroArchAppShortcuts updateAppShortcuts];
}
#endif
#if TARGET_OS_IOS
if (@available(iOS 13.0, *))
[MXMetricManager.sharedManager addSubscriber:self];
#endif
#ifdef HAVE_MFI
extern void *apple_gamecontroller_joypad_init(void *data);
apple_gamecontroller_joypad_init(NULL);
if (@available(macOS 11, iOS 14, tvOS 14, *))
{
[[NSNotificationCenter defaultCenter] addObserverForName:GCMouseDidConnectNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note)
{
GCMouse *mouse = note.object;
mouse.mouseInput.mouseMovedHandler = ^(GCMouseInput * _Nonnull mouse, float delta_x, float delta_y)
{
cocoa_input_data_t *apple = (cocoa_input_data_t*) input_state_get_ptr()->current_data;
if (!apple)
return;
apple->window_pos_x += (int16_t)delta_x;
apple->window_pos_y -= (int16_t)delta_y;
};
mouse.mouseInput.leftButton.pressedChangedHandler = ^(GCControllerButtonInput * _Nonnull button, float value, BOOL pressed)
{
cocoa_input_data_t *apple = (cocoa_input_data_t*) input_state_get_ptr()->current_data;
if (!apple)
return;
if (pressed)
apple->mouse_buttons |= (1 << 0);
else
apple->mouse_buttons &= ~(1 << 0);
};
mouse.mouseInput.rightButton.pressedChangedHandler = ^(GCControllerButtonInput * _Nonnull button, float value, BOOL pressed)
{
cocoa_input_data_t *apple = (cocoa_input_data_t*) input_state_get_ptr()->current_data;
if (!apple)
return;
if (pressed)
apple->mouse_buttons |= (1 << 1);
else
apple->mouse_buttons &= ~(1 << 1);
};