/
CoronaViewPrivate.mm
1907 lines (1542 loc) · 51.7 KB
/
CoronaViewPrivate.mm
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
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "Core/Rtt_Build.h"
#import <QuartzCore/QuartzCore.h>
#import <CoreLocation/CoreLocation.h>
#import "CoronaViewPrivate.h"
#import "CoronaViewRuntimeDelegate.h"
#import "CoronaGyroscopeObserver.h"
#ifdef Rtt_ORIENTATION
#import "CoronaOrientationObserver.h"
#endif
#import "CoronaOrientationProvider.h"
#import "CoronaSystemResourceManager.h"
#import "AppleWeakProxy.h"
#ifdef Rtt_CORE_MOTION
#import <CoreMotion/CoreMotion.h>
#endif
#include "Core/Rtt_Build.h"
#include "Core/Rtt_New.h"
#include "Display/Rtt_Display.h"
#include "Display/Rtt_StageObject.h"
#include "Rtt_AppleBitmap.h"
#include "Rtt_AppleInputDeviceManager.h"
#include "Rtt_AppleInputMFiDeviceListener.h"
#include "Rtt_IPhonePlatformBase.h"
#include "Rtt_DeviceOrientation.h"
#include "Rtt_MPlatformDevice.h"
#include "Rtt_Runtime.h"
#import <objc/runtime.h>
#if defined( Rtt_IPHONE_ENV )
#include "Rtt_AppleKeyServices.h"
#include "Rtt_IPhonePlatformCore.h"
#include "Rtt_IPhoneOrientation.h"
#include "Rtt_IPhoneTemplate.h"
#endif
#include "Rtt_Event.h"
#include "Rtt_GPU.h"
#include "Rtt_MCallback.h"
#include "CoronaEvent.h"
#include "CoronaLua.h"
#include "Rtt_LuaContext.h"
#import "Rtt_AppleTextDelegateWrapperObjectHelper.h"
#import "Rtt_IPhoneTextBoxObject.h"
#import "Rtt_IPhoneTextFieldObject.h"
#include "Rtt_KeyName.h"
#include "Rtt_MetalAngleTypes.h"
// ----------------------------------------------------------------------------
namespace Rtt
{
class MCallback;
// ----------------------------------------------------------------------------
} // Rtt
// ----------------------------------------------------------------------------
// Creates the default platform for CoronaView
// NOTE: Default implies iOS and CoronaCards.
// NOTE: We deliberately do not have a default for non-iOS platforms
// to make the maintenance of this file (which is shared across iOS/tvOS)
// somewhat sane.
static Rtt::IPhonePlatformBase *
CreatePlatform( CoronaView *view )
{
#if defined( Rtt_IPHONE_ENV )
return new Rtt::IPhonePlatformCore( view );
#else
// On non-iOS platforms, you should pass in your own instance of iPhonePlatformBase
// We are trying to keep all non-iOS related classes/etc (e.g. TVOS) out of this file.
Rtt_ASSERT_NOT_REACHED();
return nullptr;
#endif
}
// UITouch (CoronaViewExtensions)
// ----------------------------------------------------------------------------
#pragma mark # UITouch (CoronaViewExtensions)
@interface UITouch ( CoronaViewExtensions )
- (CGPoint)locationInCoronaView:(CoronaView*)view;
@end
@implementation UITouch ( CoronaViewExtensions )
- (CGPoint)locationInCoronaView:(CoronaView*)view
{
using namespace Rtt;
// This should be the only place in this file where we call locationInView:
CGPoint result = [self locationInView:view];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
// Compiler macro is insufficient if you are building against the 4.0 SDK for new features, but
// also want to support older OS's. You need a runtime check as well.
if([view respondsToSelector:@selector(contentScaleFactor)])
{
CGFloat scale = view.contentScaleFactor;
result.x *= scale;
result.y *= scale;
}
#endif
return result;
}
@end
// TapEventWrapper
// ----------------------------------------------------------------------------
#pragma mark # TapEventWrapper
@interface TapEventWrapper : NSObject
{
Rtt::TapEvent *event;
}
- (id)initWithTouch:(UITouch*)touch inView:(CoronaView*)view;
@property (nonatomic, readonly) Rtt::TapEvent *event;
@end
@implementation TapEventWrapper
@synthesize event;
- (id)initWithTouch:(UITouch*)touch inView:(CoronaView*)view
{
self = [super init];
if ( self )
{
CGPoint p = [touch locationInCoronaView:view];
event = new Rtt::TapEvent( Rtt_FloatToReal( p.x ), Rtt_FloatToReal( p.y ), (S32)touch.tapCount );
// Rtt_TRACE( ( "TapEventWrapper create(%p)\n", event ) );
}
return self;
}
- (void)dealloc
{
delete event;
[super dealloc];
}
@end
// CoronaViewListenerAdapter
// ----------------------------------------------------------------------------
#pragma mark # CoronaViewListenerAdapter
static int
CoronaViewListenerAdapter( lua_State *L )
{
using namespace Rtt;
int result = 0;
int eventIndex = 1;
if ( lua_istable( L, eventIndex ) )
{
CoronaView *view = (CoronaView *)lua_touserdata( L, lua_upvalueindex( 1 ) );
id <CoronaViewDelegate> delegate = view.coronaViewDelegate;
if ( [delegate respondsToSelector:@selector(coronaView:receiveEvent:)] )
{
NSDictionary *event = ApplePlatform::CreateDictionary( L, eventIndex );
id value = [delegate coronaView:view receiveEvent:event];
result = (int)ApplePlatform::Push( L, value );
}
}
return result;
}
// CoronaView()
// ----------------------------------------------------------------------------
#pragma mark # CoronaView()
@interface CoronaView() <
#ifdef Rtt_ORIENTATION
CoronaOrientationObserver,
#endif
CLLocationManagerDelegate,
CoronaGyroscopeObserver,
CoronaOrientationProvider>
{
@private
NSString *fResourcePath;
CFMutableDictionaryRef fTouchesData;
CGPoint fStartTouchPosition;
NSTimeInterval fTapDelay;
int fInhibitCount; // used by TouchInhibitor
int fSuspendCount;
int fLastContentHeight;
bool fShouldInvalidate;
bool fBeganRunLoop;
// Gyroscope
BOOL gyroscopeEnabled;
U64 gyroscopePreviousTimestampCorona;
NSTimeInterval gyroscopePreviousTimestamp;
// Orientation
Rtt::DeviceOrientation::Type fLoadOrientation; // orientation when loading Runtime
// Load Parameters
NSDictionary *fParams;
// TextField/TextBox
UIView *fActiveText;
CGPoint fWindowOffset;
CGPoint fWindowCenterStart;
CGFloat fKeyboardOffset;
BOOL fKeyboardShown;
BOOL fCoronaWindowMovesWhenKeyboardAppears;
AppleInputMFiDeviceListener *fMFiInputListener;
}
@property (nonatomic, readonly) Rtt::IPhonePlatformBase *platform;
@property (nonatomic, retain) AppleWeakProxy *observerProxy;
- (void)addApplicationObserver;
- (void)removeApplicationObserver;
- (void)applicationWillResignActive:(NSNotification *)notification;
- (void)applicationDidBecomeActive:(NSNotification *)notification;
- (void)dispatchTapEvent:(TapEventWrapper*)event;
- (void)dispatchEvent:(Rtt::MEvent*)event;
- (void)pollAndDispatchMotionEvents;
- (void)dispatchEditingEventForTextView:(Rtt_AppleTextDelegateWrapperObjectHelper*)eventData;
- (void)dispatchEditingEventForTextField:(Rtt_AppleTextDelegateWrapperObjectHelper*)eventData;
@end
// CoronaView
// ----------------------------------------------------------------------------
#pragma mark # CoronaView
@implementation CoronaView
// ----------------------------------------------------------------------------
+ (Rtt::DeviceOrientation::Type)deviceOrientationForString:(NSString *)value
{
using namespace Rtt;
DeviceOrientation::Type result = DeviceOrientation::kUpright;
if ( [value isEqualToString:@"UIInterfaceOrientationPortraitUpsideDown"] )
{
result = DeviceOrientation::kUpsideDown;
}
else if ( [value isEqualToString:@"UIInterfaceOrientationLandscapeLeft"] )
{
result = DeviceOrientation::kSidewaysLeft;
}
else if ( [value isEqualToString:@"UIInterfaceOrientationLandscapeRight"] )
{
result = DeviceOrientation::kSidewaysRight;
}
return result;
}
+ (Rtt::DeviceOrientation::Type)defaultOrientation
{
using namespace Rtt;
#ifdef Rtt_IPHONE_ENV
return IPhoneOrientation::ConvertOrientation( UIInterfaceOrientationPortrait );
#elif defined( Rtt_TVOS_ENV )
// We are always in landscapeRight on tvOS.
// This has the side effect of not allowing CoronaCards portrait apps for tvOS.
return DeviceOrientation::kSidewaysRight;
#else
#error Default orientation not defined for this target platform
return DeviceOrientation::kUnknown;
#endif
}
// ----------------------------------------------------------------------------
@synthesize fInhibitCount;
@synthesize fTapDelay;
// Bottleneck for startup
- (void)initCommon
{
fResourcePath = nil;
fTouchesData = nil;
fTapDelay = 0.;
fInhibitCount = 0;
fSuspendCount = 0;
_observeSuspendResume = YES;
fLastContentHeight = -1;
fShouldInvalidate = false;
fLoadOrientation = Rtt::DeviceOrientation::kUpright;
fParams = nil;
// TextField/TextBox
{
fActiveText = nil;
fWindowOffset = CGPointZero;
fWindowCenterStart = CGPointZero;
fKeyboardOffset = 0.f;
fKeyboardShown = NO;
NSNumber *shouldWindowMove = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CoronaWindowMovesWhenKeyboardAppears"];
fCoronaWindowMovesWhenKeyboardAppears = [shouldWindowMove boolValue];
#ifndef Rtt_TVOS_ENV
// Register for keyboard notifications
NSNotificationCenter *notifier = [NSNotificationCenter defaultCenter];
[notifier addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
[notifier addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification object:nil];
#endif
}
_observerProxy = [[AppleWeakProxy alloc] initWithTarget:self];
_orientationObserver = (id< CoronaOrientationObserver >)_observerProxy;
_locationObserver = (id< CLLocationManagerDelegate >)_observerProxy;
_gyroscopeObserver = (id< CoronaGyroscopeObserver >)_observerProxy;
}
- (id)initWithFrame:(CGRect)rect context:(Rtt_EAGLContext *)context
{
if ( (self = [super initWithFrame:rect context:context]) )
{
[self initCommon];
}
return self;
}
#ifndef Rtt_MetalANGLE
- (id)initWithFrame:(CGRect)rect
{
if ( self || (self = [self initWithFrame:rect context:nil]) )
{
[self initCommon];
}
return self;
}
#endif
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ( (self = [super initWithCoder:aDecoder]) )
{
[self initCommon];
}
return self;
}
// Bottleneck for teardown
- (void)deallocCommon
{
// TextField/TextBox
{
#ifndef Rtt_TVOS_ENV
// Unregister for keyboard notifications
NSNotificationCenter *notifier = [NSNotificationCenter defaultCenter];
[notifier removeObserver:self
name:UIKeyboardWillShowNotification object:nil];
[notifier removeObserver:self
name:UIKeyboardWillHideNotification object:nil];
#endif
}
[self terminate];
if ( fTouchesData )
{
[fParams release];
CFRelease( fTouchesData );
fTouchesData = nil;
[fResourcePath release];
}
}
- (void)dealloc
{
[self deallocCommon];
[super dealloc];
}
- (void)initializeRuntime
{
[self initializeRuntimeWithPlatform:NULL runtimeDelegate:NULL];
}
- (void)initializeRuntimeWithPlatform:(Rtt::IPhonePlatformBase *)platform runtimeDelegate:(Rtt::CoronaViewRuntimeDelegate *)runtimeDelegate
{
using namespace Rtt;
if ( ! _runtime )
{
_platform = ( platform ? platform : CreatePlatform( self ) );
_runtime = new Runtime( * _platform );
_runtimeDelegate = ( runtimeDelegate ? runtimeDelegate : new CoronaViewRuntimeDelegate( self ) );
_runtime->SetDelegate( _runtimeDelegate );
#ifdef Rtt_IPHONE_ENV
bool isCoronaKit = Rtt::IPhoneTemplate::IsProperty( IPhoneTemplate::kIsCoronaKit );
#else
bool isCoronaKit = false;
#endif
_runtime->SetProperty( Rtt::Runtime::kIsCoronaKit, isCoronaKit );
if ( isCoronaKit )
{
_runtime->SetProperty( Rtt::Runtime::kIsApplicationNotArchived, true );
_runtime->SetProperty( Rtt::Runtime::kIsLuaParserAvailable, true );
}
}
}
- (Rtt_GLKViewController *)viewController
{
Rtt_ASSERT( [self.delegate isKindOfClass:[UIViewController class]] );
return (Rtt_GLKViewController *)self.delegate;
}
- (void)willBeginRunLoop:(NSDictionary *)params
{
using namespace Rtt;
lua_State *L = _runtime->VMContext().L();
// Pass launch params to main.lua
if ( params )
{
Rtt_LUA_STACK_GUARD( L );
if ( Rtt_VERIFY( _runtime->PushLaunchArgs( true ) > 0 ) )
{
lua_State *L = _runtime->VMContext().L();
ApplePlatform::CopyDictionary( L, -1, params );
lua_pop( L, 1 );
}
}
// Attach listener for "coronaView" events
{
Lua::AddCoronaViewListener( L, CoronaViewListenerAdapter, self );
// Rtt_LUA_STACK_GUARD( L );
//
// // Push Runtime.addEventListener
// // Push Runtime
// Lua::PushRuntime( L );
// lua_getfield( L, -1, "addEventListener" );
// lua_insert( L, -2 ); // swap table and function
//
// // Push 'coronaView'
// lua_pushstring( L, "coronaView" );
//
// // Push 'CoronaViewListenerAdapter'
// lua_pushlightuserdata( L, self );
// lua_pushcclosure( L, CoronaViewListenerAdapter, 1 );
//
// // Runtime.addEventListener( Runtime, "coronaView", CoronaViewListenerAdapter )
// int status = Lua::DoCall( L, 3, 0 ); Rtt_UNUSED( status );
// Rtt_ASSERT( 0 == status );
}
}
- (NSInteger)run
{
return [self runWithPath:nil parameters:nil];
}
- (NSInteger)runWithPath:(NSString*)path parameters:(NSDictionary *)params
{
Rtt::DeviceOrientation::Type orientation = [[self class] defaultOrientation];
NSString *orientationParam = [params valueForKey:@"orientation"];
// Allow params to override default orientation
if (orientationParam != nil)
{
orientation = Rtt::DeviceOrientation::TypeForString([orientationParam UTF8String]);
}
return [self runWithPath:path parameters:params orientation:orientation];
}
- (NSInteger)runWithPath:(NSString*)path parameters:(NSDictionary *)params orientation:(Rtt::DeviceOrientation::Type)orientation
{
using namespace Rtt;
NSInteger result = (NSInteger)Runtime::kGeneralFail;
[self initializeRuntime];
if(!fMFiInputListener) {
AppleInputDeviceManager& inputDeviceManager = (AppleInputDeviceManager&)_runtime->Platform().GetDevice().GetInputDeviceManager();
fMFiInputListener = [[AppleInputMFiDeviceListener alloc] initWithRuntime:_runtime andDeviceManager:&inputDeviceManager];
}
// Check if already launched
if ( ! _runtime->IsProperty( Runtime::kIsApplicationExecuting ) )
{
[self addApplicationObserver];
fResourcePath = [path copy];
_platform->SetResourceDirectory( path );
Rtt_ASSERT( self.context );
// We need to bind to correct framebuffer so that GL commands triggered by
// * LoadApplication()
// * BeginRunLoop()
// go to to the right place
[Rtt_EAGLContext setCurrentContext:self.context];
[self bindDrawable];
fLoadOrientation = orientation;
fParams = [params retain];
if ( ! self.beginRunLoopManually )
{
result = [self beginRunLoop];
}
else
{
result = Runtime::kSuccess;
}
}
return result;
}
- (NSInteger)beginRunLoop
{
using namespace Rtt;
if ( fBeganRunLoop ) { return (NSInteger)Runtime::kGeneralFail; }
fBeganRunLoop = true;
Rtt::Runtime::LoadParameters loadParameters;
U32 launchOptions = Runtime::kDeviceLaunchOption;
loadParameters.orientation = fLoadOrientation;
loadParameters.launchOptions = launchOptions;
id width = [fParams objectForKey:@"contentWidth"];
S32 contentWidth = ( [width isKindOfClass:[NSNumber class]] ? [width intValue] : -1 );
id height = [fParams objectForKey:@"contentHeight"];
S32 contentHeight = ( [height isKindOfClass:[NSNumber class]] ? [height intValue] : -1 );
if ( contentWidth > 0 && contentHeight > 0 )
{
loadParameters.contentWidth = contentWidth;
loadParameters.contentHeight = contentHeight;
}
NSInteger result =_runtime->LoadApplication( loadParameters );
if ( result == (NSInteger)Runtime::kSuccess )
{
[fMFiInputListener start];
[self willBeginRunLoop:fParams];
_runtime->BeginRunLoop();
//Forcing immediate blit (outside MGLKViewController which normally drives the display update)
[self display];
}
return result;
}
#ifdef Rtt_ORIENTATION
- (void)notifyRuntimeAboutOrientationChange:(UIInterfaceOrientation)toInterfaceOrientation
{
Rtt::Runtime *runtime = self.runtime;
if ( runtime )
{
runtime->SetContentOrientation( Rtt::IPhoneOrientation::ConvertOrientation( toInterfaceOrientation ) );
}
}
#endif
+(Rtt::Real)getTouchForce:(UITouch*)touch {
static bool initialized = false;
static bool supports3DTouch = false;
if(!initialized) {
initialized = true;
Method m = class_getInstanceMethod([touch class], @selector(force));
if(m) {
char type[10]={0};
method_getReturnType(m, type, sizeof(type));
supports3DTouch = (strncmp(type, "d", sizeof(type)) == 0);
}
}
Rtt::Real force = Rtt::TouchEvent::kPressureInvalid;
if (supports3DTouch) {
force = [touch force];
if(force == 0 && [touch type] != UITouchTypePencil) {
force = Rtt::TouchEvent::kPressureInvalid;
}
}
return force;
}
- (BOOL)simulateCommand:(NSDictionary *)args
{
BOOL result = NO;
NSString *command = [args valueForKey:@"command"];
NSDictionary *commandOptions = [args valueForKey:@"options"];
if ( [command isEqualToString:@"launch"] )
{
NSString *resourcePath = [commandOptions valueForKey:@"resourcePath"];
NSString *mainPath = [resourcePath stringByAppendingPathComponent:@"main.lua"];
NSFileManager *fileMgr = [NSFileManager defaultManager];
if ( mainPath && [fileMgr fileExistsAtPath:mainPath isDirectory:nil] )
{
_platform->SetResourceDirectory( resourcePath );
lua_State *L = _runtime->VMContext().L();
// package.path = resourcePath .. "/?.lua"
lua_getglobal( L, "package" );
{
lua_pushfstring( L, "%s" LUA_DIRSEP LUA_PATH_MARK ".lua", [resourcePath UTF8String] );
lua_setfield( L, -2, "path" );
}
lua_pop( L, 1 );
result = ( 0 == CoronaLuaDoFile( L, [mainPath UTF8String], 0, true ) );
}
}
else if ( [command isEqualToString:@"relaunch"] )
{
// NOTE: Relaunch has to happen asynchronously, so we queue the relaunch.
// The balancing release happens in the block. This guarantees it's valid
// by the time the block executes
NSString *path = [fResourcePath retain];
CoronaView *view = self;
// Define the op
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[view deallocCommon];
[view initCommon];
if ( view.launchDelegate )
{
[view.launchDelegate runView:view withPath:path parameters:nil];
}
else
{
[view runWithPath:path parameters:nil];
}
[path release];
}];
// Queue the op
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[queue addOperation:op];
result = YES;
}
return result;
}
- (void)suspend
{
if ( _runtime )
{
Rtt_ASSERT( fSuspendCount >= 0 );
if ( 0 == fSuspendCount++ )
{
if ( [_coronaViewDelegate respondsToSelector:@selector(coronaViewWillSuspend:)] )
{
[_coronaViewDelegate coronaViewWillSuspend:self];
}
_runtime->Suspend();
if ( [_coronaViewDelegate respondsToSelector:@selector(coronaViewDidSuspend:)] )
{
[_coronaViewDelegate coronaViewDidSuspend:self];
}
}
}
}
- (void)resume
{
if ( _runtime )
{
if ( fSuspendCount > 0 )
{
if ( 0 == --fSuspendCount )
{
if ( [_coronaViewDelegate respondsToSelector:@selector(coronaViewWillResume:)] )
{
[_coronaViewDelegate coronaViewWillResume:self];
}
_runtime->Resume();
_runtime->GetDisplay().Invalidate();
if ( [_coronaViewDelegate respondsToSelector:@selector(coronaViewDidResume:)] )
{
[_coronaViewDelegate coronaViewDidResume:self];
}
}
}
}
}
- (void)terminate
{
//Grab the view's context
Rtt_EAGLContext *context = self.context;
//Grab the active openGL context
Rtt_EAGLContext *openGlContext = [Rtt_EAGLContext currentContext];
if ( openGlContext != context)
{
[Rtt_EAGLContext setCurrentContext:context];
}
[self removeApplicationObserver];
// Destroy runtime first
fBeganRunLoop = false;
delete _runtime;
_runtime = NULL;
delete _runtimeDelegate;
_runtimeDelegate = NULL;
delete _platform; // We assume _platform is instantiated with plain new
_platform = NULL;
[fMFiInputListener stop];
[fMFiInputListener release];
fMFiInputListener = nil;
// Cleanup observers used by CoronaSystemResourceManager
// Do this after _platform is deleted b/c IPhoneDevice needs to remove these observers
[_observerProxy invalidate];
[_observerProxy release];
_observerProxy = nil;
_orientationObserver = nil;
_locationObserver = nil;
_gyroscopeObserver = nil;
//Restore the context
[Rtt_EAGLContext setCurrentContext:openGlContext];
}
- (id)sendEvent:(NSDictionary *)event
{
using namespace Rtt;
id result = nil;
lua_State *L = _runtime->VMContext().L();
Rtt_LUA_STACK_GUARD( L );
id name = [event valueForKey:@"name"];
if ( [name isKindOfClass:[NSString class]]
&& [name length] > 0 )
{
ApplePlatform::CreateAndPushTable( L, event ); // push event
Corona::Lua::DispatchRuntimeEvent( L, 1 );
// NOTE: In the EventListener:dispatchEvent code, the default result
// is 'false'. For Obj-C, we'd prefer the default to be 'nil'.
// Thus, if we get 'false', we skip the conversion. In Lua, these are
// morally equivalent and we probably should have set the default to be
// nil to begin with.
if ( 0 != lua_toboolean( L, -1 ) )
{
result = ApplePlatform::ToValue( L, -1 );
}
lua_pop( L, 1 ); // pop result
}
return result;
}
- (void)addApplicationObserver
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
#ifdef Rtt_ORIENTATION
[[NSNotificationCenter defaultCenter] addObserver:self.orientationObserver selector:@selector(didOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
#endif
}
- (void)removeApplicationObserver
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
#ifdef Rtt_ORIENTATION
[[NSNotificationCenter defaultCenter] removeObserver:self.orientationObserver name:UIDeviceOrientationDidChangeNotification object:nil];
#endif
}
- (void)applicationWillResignActive:(NSNotification *)notification
{
if ( _observeSuspendResume )
{
[self suspend];
}
}
- (void)applicationDidBecomeActive:(NSNotification *)notification
{
if ( _observeSuspendResume )
{
[self resume];
}
}
- (void)dispatchTapEvent:(TapEventWrapper*)e;
{
// Rtt_TRACE( ( "dispatchTapEventWrapper(%p) numTaps(%d)\n", e, e.event->NumTaps() ) );
[self dispatchEvent:e.event];
}
- (void)dispatchEvent:(Rtt::MEvent*)e;
{
using namespace Rtt;
Rtt_ASSERT( _runtime );
if ( Rtt_VERIFY( e ) )
{
_runtime->DispatchEvent( * e );
}
}
static void
TouchesDataValueRelease( CFAllocatorRef allocator, const void *p )
{
Rtt_ASSERT( p );
free( (CGPoint*)p );
}
static Rtt::TouchEvent::Phase
UITouchPhaseToTouchEventPhase( UITouchPhase phase )
{
Rtt::TouchEvent::Phase result;
switch( phase )
{
case UITouchPhaseBegan:
result = Rtt::TouchEvent::kBegan;
break;
case UITouchPhaseMoved:
result = Rtt::TouchEvent::kMoved;
break;
case UITouchPhaseStationary:
result = Rtt::TouchEvent::kStationary;
break;
case UITouchPhaseEnded:
result = Rtt::TouchEvent::kEnded;
break;
case UITouchPhaseCancelled:
result = Rtt::TouchEvent::kCancelled;
break;
default:
Rtt_ASSERT_NOT_REACHED();
result = Rtt::TouchEvent::kBegan;
break;
}
return result;
}
static void
InitializeEvents( CoronaView *view, Rtt::TouchEvent *touchEvents, NSSet *touches, CFMutableDictionaryRef touchesData )
{
using namespace Rtt;
UITouch *touch = touches.anyObject;
TouchEvent::Phase phase = UITouchPhaseToTouchEventPhase( touch.phase );
int i = 0;
for ( UITouch *t in touches )
{
CGPoint touchPoint = [t locationInCoronaView:view];
CGPoint *startPoint = (CGPoint *)CFDictionaryGetValue( touchesData, t );
if ( TouchEvent::kBegan == phase )
{
if ( Rtt_VERIFY( ! startPoint ) )
{
startPoint = (CGPoint *)malloc(sizeof(CGPoint));
CFDictionarySetValue( touchesData, t, startPoint );
}
* startPoint = touchPoint;
}
// Just in case we somehow didn't store the startPoint
if ( ! Rtt_VERIFY( startPoint ) )
{
startPoint = & touchPoint;
}
TouchEvent::Phase eventPhase = phase;
if ( eventPhase >= TouchEvent::kNumPhases )
{
eventPhase = UITouchPhaseToTouchEventPhase( t.phase );
}
Rtt::Real pressure = [CoronaView getTouchForce:touch];
// Initialize TouchEvent (use placement new to call c-tor)
TouchEvent *event = & ( touchEvents[i] );
new( event ) TouchEvent( touchPoint.x, touchPoint.y, startPoint->x, startPoint->y, eventPhase, pressure );
event->SetId( t );
i++;
// On iOS 8.1 on iPhone 6+, once CFDictionaryRemoveValue is called, the value for the key
// is also deleted. This is because of the TouchesDataValueRelease function we pass in
// when creating the dictionary
if ( TouchEvent::kEnded == phase || TouchEvent::kCancelled == phase )
{
CFDictionaryRemoveValue( touchesData, t );
}
}
}
- (void)dispatchTouches:(NSSet *)touches withEvent:(UIEvent *)event
{
using namespace Rtt;
Rtt_ASSERT( 0 == fInhibitCount );
if ( ! fTouchesData )
{
CFDictionaryValueCallBacks valueCallbacks = { 0, NULL, & TouchesDataValueRelease, NULL, NULL };
fTouchesData = CFDictionaryCreateMutable( NULL, 4, NULL, & valueCallbacks );
}