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
|
/**
* Copyright 2019-2023 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of JogAmp Community.
*/
#import "IOSNewtUIWindow.h"
#import "InputEvent.h"
#import "KeyEvent.h"
#import "MouseEvent.h"
#include <CoreFoundation/CoreFoundation.h>
#include <math.h>
#define PRINTF(...) NSLog(@ __VA_ARGS__)
#define IOS_TOUCH_COUNT 10
static jmethodID sendTouchScreenEventID = NULL;
static jmethodID requestFocusID = NULL;
static jmethodID insetsChangedID = NULL;
static jmethodID sizeChangedID = NULL;
static jmethodID sizeScreenPosInsetsChangedID = NULL;
static jmethodID updatePixelScaleID = NULL;
static jmethodID visibleChangedID = NULL;
static jmethodID screenPositionChangedID = NULL;
static jmethodID focusChangedID = NULL;
static jmethodID windowDestroyNotifyID = NULL;
static jmethodID windowRepaintID = NULL;
// Need to enqueue all events to EDT,
// since we may operate on AWT-AppKit (Main Thread)
// and direct issuing 'requestFocus()' would deadlock:
// AWT-AppKit
// AWT-EventQueue-0
@implementation NamedUITouch
- (id)initWithName:(UITouch*)t name:(short)n
{
self->name = n;
self->touch = [t retain];
return self;
}
- (void) dealloc
{
[touch release];
[super dealloc];
}
- (BOOL)isEqual:(id)object
{
// Ensure NSPointerFunctionsObjectPointerPersonality for NSArray
return self == object;
}
- (NSUInteger)hash
{
// Ensure NSPointerFunctionsObjectPointerPersonality for NSArray
//
// When building 32-bit applications, NSUInteger is a 32-bit unsigned integer.
// A 64-bit application treats NSUInteger as a 64-bit unsigned integer
// https://developer.apple.com/documentation/objectivec/nsuinteger?language=objc
return (NSUInteger)self;
}
@end
@implementation NewtUIView
- (id)initWithFrame:(CGRect)frameRect
{
id res = [super initWithFrame:frameRect];
CAEAGLLayer* l = (CAEAGLLayer*)[self layer];
[l setOpaque: YES];
l.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: /* defaults */
[NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
[self setMultipleTouchEnabled: YES]; // NEWT supports multitouch ..
[self setExclusiveTouch: YES]; // NEWT touches shall keep with NEWT
[self setUserInteractionEnabled: YES]; // Default ..
// NSMapTable<UITouch*, NamedUITouch*>* activeTouchMap;
// NSHashTable<NamedUITouch*>* activeTouches;
activeTouchMap = [[NSMapTable alloc] initWithKeyOptions:NSMapTableStrongMemory|NSMapTableObjectPointerPersonality
valueOptions:NSMapTableStrongMemory|NSMapTableObjectPointerPersonality
capacity:IOS_TOUCH_COUNT];
activeTouches = [[NSMutableArray alloc] initWithCapacity:IOS_TOUCH_COUNT];
nextTouchName = 0;
javaWindowObject = NULL;
destroyNotifySent = NO;
softLockCount = 0;
pthread_mutexattr_t softLockSyncAttr;
pthread_mutexattr_init(&softLockSyncAttr);
pthread_mutexattr_settype(&softLockSyncAttr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&softLockSync, &softLockSyncAttr); // recursive
modsDown[0] = NO; // shift
modsDown[1] = NO; // ctrl
modsDown[2] = NO; // alt
modsDown[3] = NO; // win
DBG_PRINT("NewtUIView::create: %p/%p, CAEAGLLayer %p (pixelScale %f, isCAEAGLLayer %d) (res refcnt %d)\n",
res, self, l, [l contentsScale], [l isKindOfClass:[CAEAGLLayer class]], (int)[res retainCount]);
return res;
}
#ifdef DBG_LIFECYCLE
- (void) release
{
DBG_PRINT("NewtUIView::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]);
[super release];
}
#endif
- (void) dealloc
{
DBG_PRINT("NewtUIView::dealloc.0: %p (refcnt %d)\n", self, (int)[self retainCount]);
#ifdef DBG_LIFECYCLE
NSLog(@"%@",[NSThread callStackSymbols]);
#endif
if( 0 < softLockCount ) {
NSLog(@"NewtUIView::dealloc: softLock still hold @ dealloc!\n");
}
[activeTouchMap removeAllObjects];
[activeTouchMap release];
[activeTouches removeAllObjects];
[activeTouches release];
pthread_mutex_destroy(&softLockSync);
DBG_PRINT("NewtUIView::dealloc.X: %p\n", self);
[super dealloc];
}
- (void) setJavaWindowObject: (jobject) javaWindowObj
{
javaWindowObject = javaWindowObj;
}
- (jobject) getJavaWindowObject
{
return javaWindowObject;
}
- (void) setDestroyNotifySent: (BOOL) v
{
destroyNotifySent = v;
}
- (BOOL) getDestroyNotifySent
{
return destroyNotifySent;
}
- (BOOL) softLock
{
int err;
if( 0 != ( err = pthread_mutex_lock(&softLockSync) ) ) {
NSLog(@"NewtUIView::softLock failed: errCode %d - %@", err, [NSThread callStackSymbols]);
return NO;
}
softLockCount++;
// DBG_PRINT("*************** softLock: %p count %d\n", (void*)pthread_self(), softLockCount);
return 0 < softLockCount;
}
- (BOOL) softUnlock
{
softLockCount--;
// DBG_PRINT("*************** softUnlock: %p count %d\n", (void*)pthread_self(), softLockCount);
int err;
if( 0 != ( err = pthread_mutex_unlock(&softLockSync) ) ) {
softLockCount++;
NSLog(@"NewtUIView::softUnlock failed: Not locked by current thread - errCode %d - %@", err, [NSThread callStackSymbols]);
return NO;
}
return YES;
}
- (void) drawRect:(CGRect)dirtyRect
{
DBG_PRINT("*************** drawRect: dirtyRect: %p %lf/%lf %lfx%lf\n",
javaWindowObject, dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height);
if(NULL==javaWindowObject) {
DBG_PRINT("drawRect: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("drawRect: null JNIEnv\n");
return;
}
CGRect viewFrame = [self frame];
(*env)->CallBooleanMethod(env, javaWindowObject, windowRepaintID, JNI_TRUE /* defer */,
(int)dirtyRect.origin.x, (int)viewFrame.size.height - (int)dirtyRect.origin.y,
(int)dirtyRect.size.width, (int)dirtyRect.size.height);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.drawRect: Exception occured at windowRepaint(..)");
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (BOOL) becomeFirstResponder
{
DBG_PRINT( "*************** View.becomeFirstResponder\n");
return [super becomeFirstResponder];
}
- (BOOL) resignFirstResponder
{
DBG_PRINT( "*************** View.resignFirstResponder\n");
return [super resignFirstResponder];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
[self sendTouchEvent: touches withEvent:event eventState:1 newtEventType:(short)EVENT_MOUSE_PRESSED];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
// Note use of MOUSE_MOVED event type because mouse dragged events are synthesized by Java
[self sendTouchEvent: touches withEvent:event eventState:0 newtEventType:(short)EVENT_MOUSE_MOVED];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
[self sendTouchEvent: touches withEvent:event eventState:-1 newtEventType:(short)EVENT_MOUSE_RELEASED];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
[self sendTouchEvent: touches withEvent:event eventState:-1 newtEventType:(short)EVENT_MOUSE_RELEASED];
}
- (void)touchesEstimatedPropertiesUpdated:(NSSet<UITouch *> *)touches
{
}
- (void)sendTouchEvent: (NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
eventState:(int)eventState newtEventType:(short)newtEventType
{
if (javaWindowObject == NULL) {
DBG_PRINT("sendTouchEvent: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("sendTouchEvent: null JNIEnv\n");
return;
}
jint newtEventModifiers = 0; // FIXME?
jint touchTypes[IOS_TOUCH_COUNT];
jshort pointerNames[IOS_TOUCH_COUNT];
jint x[IOS_TOUCH_COUNT];
jint y[IOS_TOUCH_COUNT];
jfloat pressure[IOS_TOUCH_COUNT];
jint actionIdx[IOS_TOUCH_COUNT];
int activeTouchesNewIdx = -1;
DBG_PRINT( "sendTouchEvent.0: Window %p, state %d, newtType %d, touches %d, activeTouches %d, nextTouchName %d\n",
(void*)javaWindowObject, eventState, (int)newtEventType, (int)[touches count], (int)[activeTouches count], nextTouchName);
// merge new touches into activeTouchMap (unify) and
// add to end of activeTouches array
{
NSEnumerator<UITouch*>* touchesEnum = [touches objectEnumerator];
UITouch * t;
while( (t = [touchesEnum nextObject]) ) {
NamedUITouch *nt = (NamedUITouch*)[activeTouchMap objectForKey: t];
if( nil == nt ) {
if( 1 != eventState ) {
// Ooops, not 'touchesBegan' but UITouch not mapped!
NewtCommon_throwNewRuntimeException(env, "Internal Error: touch event (window %p) state %d, newtType %d not mapped",
(void*)javaWindowObject, eventState, (int)newtEventType);
}
if( IOS_TOUCH_COUNT > [activeTouches count] ) {
nt = [[NamedUITouch alloc] initWithName:t name:nextTouchName++];
[activeTouchMap setObject:nt forKey:t];
[activeTouches addObject: nt];
if( 0 > activeTouchesNewIdx ) {
activeTouchesNewIdx = [activeTouches count] - 1;
}
}
}
}
}
#ifdef VERBOSE_ON
{
int activeTouchesNewCount = activeTouchesNewIdx < 0 ? 0 : [activeTouches count] - activeTouchesNewIdx;
DBG_PRINT( "sendTouchEvent.1: Window %p, state %d, newtType %d, touches %d, activeTouches %d, nextTouchName %d, newActiveTouches %d\n",
(void*)javaWindowObject, eventState, (int)newtEventType, (int)[touches count], (int)[activeTouches count], nextTouchName, activeTouchesNewCount);
}
#endif /* VERBOSE_ON */
int cnt, actionCnt;
for(cnt=0, actionCnt=0; cnt<[activeTouches count]; cnt++) {
NamedUITouch *nt = [activeTouches objectAtIndex: cnt];
switch( [nt->touch type] ) {
case UITouchTypeDirect:
case UITouchTypeIndirect: /* ??? */
touchTypes[cnt] = POINTER_TYPE_TOUCHSCREEN;
break;
case UITouchTypePencil:
touchTypes[cnt] = POINTER_TYPE_PEN;
break;
default:
touchTypes[cnt] = POINTER_TYPE_UNDEF;
break;
}
CGPoint loc = [nt->touch preciseLocationInView: self]; // [touch locationInView: self];
x[cnt] = (jint)(loc.x);
y[cnt] = (jint)(loc.y);
pressure[cnt] = (jfloat)(nt->touch.force);
pointerNames[cnt] = nt->name;
if( [touches member: nt->touch] ) {
actionIdx[actionCnt++] = cnt;
DBG_PRINT( "sendTouchEvent.2: Window %p, action-touchid[%d]: name %d, idx %d, ptr: %d/%d\n",
(void*)javaWindowObject, (actionCnt-1), nt->name, cnt, x[cnt], y[cnt]);
} else {
DBG_PRINT( "sendTouchEvent.2: Window %p, action-touchid[-1]: name %d, idx %d, ptr: %d/%d\n",
(void*)javaWindowObject, nt->name, cnt, x[cnt], y[cnt]);
}
}
if( 0 >= actionCnt || actionCnt != [touches count]) {
NewtCommon_throwNewRuntimeException(env, "Internal Error: touch event (window %p) %d actionIds not matching %d/%d touches",
(void*)javaWindowObject, actionCnt, (int)[touches count], cnt);
}
if( -1 == eventState ) {
NSEnumerator<UITouch*>* touchesEnum = [touches objectEnumerator];
UITouch * t;
while( (t = [touchesEnum nextObject]) ) {
NamedUITouch *nt = (NamedUITouch*)[activeTouchMap objectForKey: t];
if( nil == nt ) {
// Ooops, 'touchesEnded' but UITouch not mapped!
NewtCommon_throwNewRuntimeException(env, "Internal Error: touch event (window %p) state %d, newtType %d not mapped",
(void*)javaWindowObject, eventState, (int)newtEventType);
}
[activeTouchMap removeObjectForKey: t];
[activeTouches removeObject: nt];
}
if( 0 == [activeTouches count] ) {
// all finger released ..
nextTouchName = 0;
}
}
DBG_PRINT( "sendTouchEvent.3: Window %p, state %d, newtType %d, touches %d, activeTouches %d, nextTouchName %d\n",
(void*)javaWindowObject, eventState, (int)newtEventType, (int)[touches count], (int)[activeTouches count], nextTouchName);
jintArray jActionIdx = (*env)->NewIntArray(env, actionCnt);
if (jActionIdx == NULL) {
NewtCommon_throwNewRuntimeException(env, "Could not allocate int array (names) of size %d", actionCnt);
}
(*env)->SetIntArrayRegion(env, jActionIdx, 0, actionCnt, actionIdx);
jshortArray jNames = (*env)->NewShortArray(env, cnt);
if (jNames == NULL) {
NewtCommon_throwNewRuntimeException(env, "Could not allocate short array (names) of size %d", cnt);
}
(*env)->SetShortArrayRegion(env, jNames, 0, cnt, pointerNames);
jintArray jTouchTypes = (*env)->NewIntArray(env, cnt);
if (jTouchTypes == NULL) {
NewtCommon_throwNewRuntimeException(env, "Could not allocate int array (TouchTypes) of size %d", cnt);
}
(*env)->SetIntArrayRegion(env, jTouchTypes, 0, cnt, touchTypes);
jintArray jX = (*env)->NewIntArray(env, cnt);
if (jX == NULL) {
NewtCommon_throwNewRuntimeException(env, "Could not allocate int array (x) of size %d", cnt);
}
(*env)->SetIntArrayRegion(env, jX, 0, cnt, x);
jintArray jY = (*env)->NewIntArray(env, cnt);
if (jY == NULL) {
NewtCommon_throwNewRuntimeException(env, "Could not allocate int array (y) of size %d", cnt);
}
(*env)->SetIntArrayRegion(env, jY, 0, cnt, y);
jfloatArray jPressure = (*env)->NewFloatArray(env, cnt);
if (jPressure == NULL) {
NewtCommon_throwNewRuntimeException(env, "Could not allocate float array (pressure) of size %d", cnt);
}
(*env)->SetFloatArrayRegion(env, jPressure, 0, cnt, pressure);
/**
* Pressure (force) "1.0 represents the force of an average touch (predetermined by the system, not user-specific".
* So we pass 2.0f as the maxPressure value.
*/
(*env)->CallVoidMethod(env, javaWindowObject, sendTouchScreenEventID,
(jshort)newtEventType, (jint)newtEventModifiers,
jActionIdx, jNames, jTouchTypes, jX, jY, jPressure, (jfloat)2.0f);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.sendTouchEvent: Exception occured at sendTouchScreenEvent(..)");
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (CGPoint) screenPos2NewtClientWinPos: (CGPoint) p
{
CGRect viewFrame = [self frame];
CGRect r;
r.origin.x = p.x;
r.origin.y = p.y;
r.size.width = 0;
r.size.height = 0;
// CGRect rS = [[self window] convertRectFromScreen: r]; // 10.7
CGPoint oS = r.origin; // TODO [[self window] convertScreenToBase: r.origin];
oS.y = viewFrame.size.height - oS.y; // y-flip
return oS;
}
@end
@implementation NewtUIWindow
+ (BOOL) initNatives: (JNIEnv*) env forClass: (jclass) clazz
{
sendTouchScreenEventID = (*env)->GetMethodID(env, clazz, "sendTouchScreenEvent", "(SI[I[S[I[I[I[FF)Z");
sizeChangedID = (*env)->GetMethodID(env, clazz, "sizeChanged", "(ZZIIZ)Z");
updatePixelScaleID = (*env)->GetMethodID(env, clazz, "updatePixelScale", "(ZFFFZ)V");
visibleChangedID = (*env)->GetMethodID(env, clazz, "visibleChanged", "(Z)Z");
insetsChangedID = (*env)->GetMethodID(env, clazz, "insetsChanged", "(ZIIII)Z");
sizeScreenPosInsetsChangedID = (*env)->GetMethodID(env, clazz, "sizeScreenPosInsetsChanged", "(ZIIIIIIIIZZ)Z");
screenPositionChangedID = (*env)->GetMethodID(env, clazz, "screenPositionChanged", "(ZII)Z");
focusChangedID = (*env)->GetMethodID(env, clazz, "focusChanged", "(ZZ)Z");
windowDestroyNotifyID = (*env)->GetMethodID(env, clazz, "windowDestroyNotify", "(Z)Z");
windowRepaintID = (*env)->GetMethodID(env, clazz, "windowRepaint", "(ZIIII)Z");
requestFocusID = (*env)->GetMethodID(env, clazz, "requestFocus", "(Z)V");
if (sendTouchScreenEventID && sizeChangedID && updatePixelScaleID && visibleChangedID &&
insetsChangedID && sizeScreenPosInsetsChangedID &&
screenPositionChangedID && focusChangedID && windowDestroyNotifyID && requestFocusID && windowRepaintID)
{
// TODO CKCH_CreateDictionaries();
return YES;
}
return NO;
}
- (id) initWithFrame: (CGRect) contentRect
styleMask: (NSUInteger) windowStyle
backing: (NSUInteger) bufferingType
defer: (BOOL) deferCreation
isFullscreenWindow:(BOOL)isfs
{
id res = [super initWithFrame: contentRect];
self.rootViewController = [[[UIViewController alloc] initWithNibName:nil bundle:nil] autorelease];
isFullscreenWindow = NO; // TODO isfs;
cachedInsets[0] = 0; // l
cachedInsets[1] = 0; // r
cachedInsets[2] = 0; // t
cachedInsets[3] = 0; // b
realized = YES;
withinLiveResize = JNI_FALSE;
contentNewtUIView = NULL;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(becameVisible:)
name:UIWindowDidBecomeVisibleNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(becameHidden:)
name:UIWindowDidBecomeHiddenNotification
object:nil];
DBG_PRINT("NewtWindow::create: %p, realized %d, (refcnt %d)\n",
res, realized, (int)[res retainCount]);
return res;
}
#ifdef DBG_LIFECYCLE
- (void) release
{
DBG_PRINT("NewtWindow::release.0: %p (refcnt %d)\n", self, (int)[self retainCount]);
// NSLog(@"%@",[NSThread callStackSymbols]);
[super release];
}
#endif
- (void) dealloc
{
DBG_PRINT("NewtWindow::dealloc.0: %p (refcnt %d)\n", self, (int)[self retainCount]);
#ifdef DBG_LIFECYCLE
NSLog(@"%@",[NSThread callStackSymbols]);
#endif
[[NSNotificationCenter defaultCenter] removeObserver:self];
if( NULL != contentNewtUIView ) {
[contentNewtUIView removeFromSuperview];
[contentNewtUIView release];
contentNewtUIView=NULL;
}
[super dealloc];
DBG_PRINT("NewtWindow::dealloc.X: %p\n", self);
}
- (void) setContentNewtUIView: (NewtUIView*)v
{
DBG_PRINT( "NewtWindow::setContentNewtUIView.0: view %p -> %p\n", contentNewtUIView, v);
if( NULL != contentNewtUIView ) {
[contentNewtUIView removeFromSuperview];
[contentNewtUIView release];
contentNewtUIView=NULL;
}
contentNewtUIView = v;
if( NULL != contentNewtUIView ) {
[contentNewtUIView retain];
[self addSubview: contentNewtUIView];
}
}
- (NewtUIView*) getContentNewtUIView
{
return contentNewtUIView;
}
- (void) setRealized: (BOOL)v
{
realized = v;
}
- (BOOL) isRealized
{
return realized;
}
- (void) setAlwaysOn: (BOOL)top bottom:(BOOL)bottom
{
/**
if( top ) {
DBG_PRINT( "*************** setAlwaysOn -> top\n");
[self setLevel: kCGMaximumWindowLevel];
} else if ( bottom ) {
DBG_PRINT( "*************** setAlwaysOn -> bottom\n");
[self setLevel: kCGDesktopIconWindowLevel]; // w/ input
} else {
DBG_PRINT( "*************** setAlwaysOn -> normal\n");
[self setLevel:NSNormalWindowLevel];
} */
}
- (void) updatePixelScale: (BOOL) defer
{
NewtUIView* newtView = contentNewtUIView;
DBG_PRINT( "updatePixelScale view %p, autoMaxPixelScale %d, defer %d\n",
newtView, useAutoMaxPixelScale, defer);
if( NULL == newtView ) {
return;
}
jobject javaWindowObject = [newtView getJavaWindowObject];
if ( NULL == javaWindowObject ) {
DBG_PRINT("updatePixelScale: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("updatePixelScale: null JNIEnv\n");
return;
}
CGFloat oldPixelScaleV = [newtView contentScaleFactor];
CGFloat oldPixelScaleL = [[newtView layer] contentsScale];
UIScreen* _screen = [self screen];
CGFloat maxPixelScale = [_screen scale];
CGFloat pixelScale;
BOOL changeScale;
if ( useAutoMaxPixelScale ) {
pixelScale = maxPixelScale;
changeScale = pixelScale != oldPixelScaleV || pixelScale != oldPixelScaleL;
} else {
pixelScale = oldPixelScaleV;
changeScale = NO;
}
DBG_PRINT("updatePixelScale: PixelScale: autoMaxPixelScale %d, max %f, view %f, layer %f -> %f (change %d)\n",
useAutoMaxPixelScale, (float)maxPixelScale, (float)oldPixelScaleV, (float)oldPixelScaleL, (float)pixelScale, changeScale);
if( changeScale ) {
[newtView setContentScaleFactor: pixelScale];
[[newtView layer] setContentsScale: pixelScale];
}
(*env)->CallVoidMethod(env, javaWindowObject, updatePixelScaleID, defer?JNI_TRUE:JNI_FALSE,
(jfloat)oldPixelScaleV, (jfloat)pixelScale, (jfloat)maxPixelScale, (jboolean)changeScale);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.updatePixelScale: Exception occured at updatePixelScale(..)");
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (void) setPixelScale: (CGFloat)reqPixelScale defer:(BOOL)defer
{
NewtUIView* newtView = contentNewtUIView;
useAutoMaxPixelScale = NewtCommon_isFloatZero(reqPixelScale);
DBG_PRINT( "setPixelScale view %p, reqPixelScale %f, autoMaxPixelScale %d, defer %d\n",
newtView, reqPixelScale, useAutoMaxPixelScale, defer);
if( NULL == newtView ) {
return;
}
jobject javaWindowObject = [newtView getJavaWindowObject];
if ( NULL == javaWindowObject ) {
DBG_PRINT("setPixelScale: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("setPixelScale: null JNIEnv\n");
return;
}
CGFloat oldPixelScaleV = [newtView contentScaleFactor];
CGFloat oldPixelScaleL = [[newtView layer] contentsScale];
UIScreen* _screen = [self screen];
{
CGRect _bounds = [_screen bounds];
CGRect _nativeBounds = [_screen nativeBounds];
CGFloat _scale = [_screen scale];
CGFloat _nativeScale = [_screen nativeScale];
DBG_PRINT("setPixelScale: screen %p[native %f/%f %fx%f scale %f; logical %f/%f %fx%f scale %f]\n",
_screen,
_nativeBounds.origin.x, _nativeBounds.origin.y, _nativeBounds.size.width, _nativeBounds.size.height, _nativeScale,
_bounds.origin.x, _bounds.origin.y, _bounds.size.width, _bounds.size.height, _scale);
}
CGFloat maxPixelScale = [_screen scale];
CGFloat pixelScale;
BOOL changeScale;
if ( useAutoMaxPixelScale || maxPixelScale < reqPixelScale ) {
pixelScale = maxPixelScale;
} else if( 0 > reqPixelScale ) {
pixelScale = 1.0f;
} else {
pixelScale = reqPixelScale;
}
changeScale = pixelScale != oldPixelScaleV || pixelScale != oldPixelScaleL;
DBG_PRINT("setPixelScale: PixelScale: autoMaxPixelScale %d, max %f, view %f, layer %f, req %f -> %f (change %d)\n",
useAutoMaxPixelScale, (float)maxPixelScale, (float)oldPixelScaleV, (float)oldPixelScaleL, (float)reqPixelScale, (float)pixelScale, changeScale);
if( changeScale ) {
[newtView setContentScaleFactor: pixelScale];
[[newtView layer] setContentsScale: pixelScale];
}
(*env)->CallVoidMethod(env, javaWindowObject, updatePixelScaleID, defer?JNI_TRUE:JNI_FALSE,
(jfloat)oldPixelScaleV, (jfloat)pixelScale, (jfloat)maxPixelScale, (jboolean)changeScale);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.setPixelScale: Exception occured at updatePixelScale(..)");
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (void) updateInsets: (JNIEnv*) env jwin: (jobject) javaWin
{
/**
CGRect frameRect = [self frame];
CGRect contentRect = [self contentRectForFrameRect: frameRect];
// note: this is a simplistic implementation which doesn't take
// into account DPI and scaling factor
CGFloat l = contentRect.origin.x - frameRect.origin.x;
cachedInsets[0] = (int)l; // l
cachedInsets[1] = (int)(frameRect.size.width - (contentRect.size.width + l)); // r
cachedInsets[2] = (jint)(frameRect.size.height - contentRect.size.height); // t
cachedInsets[3] = (jint)(contentRect.origin.y - frameRect.origin.y); // b
*/
UIEdgeInsets uiInsets = [self safeAreaInsets];
cachedInsets[0] = uiInsets.left;
cachedInsets[1] = uiInsets.right;
cachedInsets[2] = uiInsets.top;
cachedInsets[3] = uiInsets.bottom;
DBG_PRINT( "updateInsets: [ l %d, r %d, t %d, b %d ]\n", cachedInsets[0], cachedInsets[1], cachedInsets[2], cachedInsets[3]);
if( NULL != env && NULL != javaWin ) {
(*env)->CallBooleanMethod(env, javaWin, insetsChangedID, JNI_FALSE, cachedInsets[0], cachedInsets[1], cachedInsets[2], cachedInsets[3]);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.updateInsets: Exception occured at insetsChanged(..)");
}
}
- (void) updateSizePosInsets: (JNIEnv*) env jwin: (jobject) javaWin defer: (jboolean)defer
{
// update insets on every window resize for lack of better hook place
[self updateInsets: NULL jwin:NULL];
CGRect frameRect = [self frame];
UIScreen* _screen = [self screen];
CGPoint pS = [self convertPoint: frameRect.origin toCoordinateSpace: _screen.fixedCoordinateSpace];
DBG_PRINT( "updateSize: [ w %d, h %d ], liveResize %d\n", (jint) frameRect.size.width, (jint) frameRect.size.height, (jint)withinLiveResize);
DBG_PRINT( "updatePos: [ x %d, y %d ]\n", (jint) pS.x, (jint) pS.y);
if( NULL != env && NULL != javaWin ) {
(*env)->CallBooleanMethod(env, javaWin, sizeScreenPosInsetsChangedID, defer,
(jint) pS.x, (jint) pS.y,
(jint) frameRect.size.width, (jint) frameRect.size.height,
cachedInsets[0], cachedInsets[1], cachedInsets[2], cachedInsets[3],
JNI_FALSE, // force
withinLiveResize
);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.updateSizePosInsets: Exception occured at sizeScreenPosInsetsChangedID(..)");
}
}
- (void) attachToParent: (UIWindow*) parent
{
DBG_PRINT( "attachToParent.1\n");
[parent addSubview: self];
// [self setwindowLevel: [parent windowLevel]+1.0f];
// NSWindow: [parent addChildWindow: self ordered: UIWindowAbove];
// NSWindow: [self setParentWindow: parent];
DBG_PRINT( "attachToParent.X\n");
}
- (void) detachFromParent: (UIWindow*) parent
{
DBG_PRINT( "detachFromParent.1\n");
[self removeFromSuperview];
/**
// NSWindow:
[self setParentWindow: nil];
if(NULL != parent) {
DBG_PRINT( "detachFromParent.2\n");
[parent removeChildWindow: self];
}
*/
DBG_PRINT( "detachFromParent.X\n");
}
/**
* p rel client window position w/ top-left origin
* returns: abs screen position w/ bottom-left origin
*/
- (CGPoint) newtRelClientTLWinPos2AbsTLScreenPos: (CGPoint) p
{
return [self getLocationOnScreen: p];
}
- (CGSize) newtClientSize2TLSize: (CGSize) nsz
{
CGSize topSZ = { nsz.width, nsz.height + cachedInsets[2] + cachedInsets[3] }; // height + insets.top + insets.bottom
return topSZ;
}
/**
* p rel client window position w/ top-left origin
* returns: location in 0/0 top-left space.
*/
- (CGPoint) getLocationOnScreen: (CGPoint) p
{
UIScreen* _screen = [self screen];
CGPoint pS = [self convertPoint: p toCoordinateSpace: _screen.fixedCoordinateSpace];
#ifdef VERBOSE_ON
CGRect winFrame = [self frame];
DBG_PRINT( "getLocationOnScreen: point-in[%d/%d], winFrame[%d/%d %dx%d] -> %d/%d\n",
(int)p.x, (int)p.y,
(int)winFrame.origin.x, (int)winFrame.origin.y, (int)winFrame.size.width, (int)winFrame.size.height,
(int)pS.x, (int)pS.y);
#endif
return pS;
}
- (void) focusChanged: (BOOL) gained
{
NewtUIView* newtView = contentNewtUIView;
DBG_PRINT( "focusChanged: gained %d, view %p\n", gained, newtView);
if( NULL == newtView ) {
return;
}
jobject javaWindowObject = [newtView getJavaWindowObject];
if ( NULL == javaWindowObject ) {
DBG_PRINT("focusChanged: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("focusChanged: null JNIEnv\n");
return;
}
(*env)->CallBooleanMethod(env, javaWindowObject, focusChangedID, JNI_FALSE, (gained == YES) ? JNI_TRUE : JNI_FALSE);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.focusChanged: Exception occured at focusChanged(..)");
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (void) visibilityChanged: (BOOL) visible
{
DBG_PRINT( "visibilityChanged: visible %d\n", visible);
NewtUIView* newtView = contentNewtUIView;
if( NULL == newtView ) {
return;
}
jobject javaWindowObject = [newtView getJavaWindowObject];
if ( NULL == javaWindowObject ) {
DBG_PRINT("visibilityChanged: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("visibilityChanged: null JNIEnv\n");
return;
}
(*env)->CallBooleanMethod(env, javaWindowObject, visibleChangedID, (visible == YES) ? JNI_TRUE : JNI_FALSE);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.visibilityChanged: Exception occured at visibilityChanged(..)");
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (BOOL) canBecomeFirstResponder
{
return YES;
}
- (BOOL) becomeFirstResponder
{
DBG_PRINT( "*************** Win.becomeFirstResponder\n");
return [super becomeFirstResponder];
}
- (BOOL) canResignFirstResponder
{
return YES;
}
- (BOOL) resignFirstResponder
{
DBG_PRINT( "*************** Win.resignFirstResponder\n");
return [super resignFirstResponder];
}
- (void) becomeKeyWindow
{
DBG_PRINT( "*************** becomeKeyWindow\n");
[super becomeKeyWindow];
[self focusChanged: YES];
}
- (void) resignKeyWindow
{
DBG_PRINT( "*************** resignKeyWindow: isFullscreen %d\n", (int)isFullscreenWindow);
if(!isFullscreenWindow) {
[super resignKeyWindow];
}
[self focusChanged: NO];
}
- (void) becameVisible: (NSNotification*)notice
{
DBG_PRINT( "*************** becameVisible\n");
[self visibilityChanged: YES];
}
- (void) becameHidden: (NSNotification*)notice
{
DBG_PRINT( "*************** becameHidden\n");
[self visibilityChanged: NO];
}
- (void) sendResizeEvent
{
// FIXME: Needs to be called
NewtUIView* newtView = contentNewtUIView;
if( NULL == newtView ) {
return;
}
jobject javaWindowObject = [newtView getJavaWindowObject];
if ( NULL == javaWindowObject ) {
DBG_PRINT("sendResizeEvent: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if( NULL == env ) {
DBG_PRINT("windowDidResize: null JNIEnv\n");
return;
}
[self updateSizePosInsets: env jwin: javaWindowObject defer:JNI_TRUE];
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (void)windowDidMove: (NSNotification*) notification
{
// FIXME: Needs to be called
NewtUIView* newtView = contentNewtUIView;
if( NULL == newtView ) {
return;
}
jobject javaWindowObject = [newtView getJavaWindowObject];
if ( NULL == javaWindowObject ) {
DBG_PRINT("windowDidMove: null javaWindowObject\n");
return;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("windowDidMove: null JNIEnv\n");
return;
}
CGPoint p0 = { 0, 0 };
p0 = [self getLocationOnScreen: p0];
DBG_PRINT( "windowDidMove: [ x %d, y %d ]\n", (jint) p0.x, (jint) p0.y);
(*env)->CallBooleanMethod(env, javaWindowObject, screenPositionChangedID, JNI_TRUE, (jint) p0.x, (jint) p0.y);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.windowDidMove: Exception occured at screenPositionChanged(..)");
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
}
- (BOOL) windowClosingImpl: (BOOL) force
{
// FIXME: Needs to be called
jboolean closed = JNI_FALSE;
NewtUIView* newtView = contentNewtUIView;
if( NULL == newtView ) {
return NO;
}
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
if( false == [newtView getDestroyNotifySent] ) {
jobject javaWindowObject = [newtView getJavaWindowObject];
DBG_PRINT( "*************** windowWillClose.0: %p\n", (void *)(intptr_t)javaWindowObject);
if ( NULL == javaWindowObject ) {
DBG_PRINT("windowWillClose: null javaWindowObject\n");
[pool release];
return NO;
}
int shallBeDetached = 0;
JNIEnv* env = NewtCommon_GetJNIEnv(1 /* asDaemon */, &shallBeDetached);
if(NULL==env) {
DBG_PRINT("windowWillClose: null JNIEnv\n");
[pool release];
return NO;
}
[newtView setDestroyNotifySent: true]; // earmark assumption of being closed
closed = (*env)->CallBooleanMethod(env, javaWindowObject, windowDestroyNotifyID, force ? JNI_TRUE : JNI_FALSE);
NewtCommon_ExceptionCheck1_throwNewRuntimeException(env, "IOSWindow.windowClosingImpl: Exception occured at windowDestroyNotify(..)");
if(!force && !closed) {
// not closed on java side, not force -> clear flag
[newtView setDestroyNotifySent: false];
}
// detaching thread not required - daemon
// NewtCommon_ReleaseJNIEnv(shallBeDetached);
DBG_PRINT( "*************** windowWillClose.X: %p, closed %d\n", (void *)(intptr_t)javaWindowObject, (int)closed);
} else {
DBG_PRINT( "*************** windowWillClose (skip)\n");
}
[pool release];
return JNI_TRUE == closed ? YES : NO ;
}
@end
|