-
Notifications
You must be signed in to change notification settings - Fork 2
/
Tweak.mm
1175 lines (923 loc) · 39.2 KB
/
Tweak.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
/* Veency - VNC Remote Access Server for iPhoneOS
* Copyright (C) 2008-2014 Jay Freeman (saurik)
*/
/* GNU Affero General Public License, Version 3 {{{ */
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */
#define _trace() \
NSLog(@"_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)
#define _likely(expr) \
__builtin_expect(expr, 1)
#define _unlikely(expr) \
__builtin_expect(expr, 0)
#include <substrate.h>
#include <rfb/rfb.h>
#include <rfb/keysym.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/mman.h>
#include <sys/sysctl.h>
#undef assert
#include <CoreFoundation/CFUserNotification.h>
#import <CoreGraphics/CGGeometry.h>
#import <GraphicsServices/GraphicsServices.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <IOKit/hid/IOHIDEventTypes.h>
#include <IOKit/hidsystem/IOHIDUsageTables.h>
extern "C" {
#include "SpringBoardAccess.h"
}
typedef CFTypeRef IOHIDEventRef;
typedef CFTypeRef IOHIDEventSystemClientRef;
typedef CFTypeRef IOHIDEventSystemConnectionRef;
MSClassHook(BKAccessibility)
MSClassHook(UIApplication)
@interface UIApplication (Apple)
- (void) addStatusBarImageNamed:(NSString *)name;
- (void) removeStatusBarImageNamed:(NSString *)name;
@end
@interface CAWindowServerDisplay : NSObject
- (mach_port_t) clientPortAtPosition:(CGPoint)position;
@end
@interface CAWindowServer : NSObject
+ (CAWindowServer *) serverIfRunning;
- (NSArray *) displays;
@end
@interface UIModalView : UIView
- (id) addButtonWithTitle:(NSString *)title;
- (void) setBodyText:(NSString *)text;
- (void) setDelegate:(id)delegate;
- (void) setTitle:(NSString *)title;
@end
@interface SBAlertItem : NSObject
- (void) dismiss;
- (UIModalView *) alertSheet;
@end
@interface SBAlertItemsController : NSObject
+ (SBAlertItemsController *) sharedInstance;
- (void) activateAlertItem:(SBAlertItem *)item;
@end
@interface SBStatusBarController : NSObject
+ (SBStatusBarController *) sharedStatusBarController;
- (void) addStatusBarItem:(NSString *)item;
- (void) removeStatusBarItem:(NSString *)item;
@end
#if defined(_ARM_ARCH_6) && !defined(_ARM_ARCH_7)
#define kIOSurfaceAllocSize kCoreSurfaceBufferAllocSize
#define kIOSurfaceBytesPerRow kCoreSurfaceBufferPitch
#define kIOSurfaceHeight kCoreSurfaceBufferHeight
#define kIOSurfaceIsGlobal kCoreSurfaceBufferGlobal
#define kIOSurfaceMemoryRegion kCoreSurfaceBufferMemoryRegion
#define kIOSurfacePixelFormat kCoreSurfaceBufferPixelFormat
#define kIOSurfaceWidth kCoreSurfaceBufferWidth
#define IOSurfaceRef CoreSurfaceBufferRef
#define IOSurfaceAcceleratorRef CoreSurfaceAcceleratorRef
#define IOSurfaceCreate CoreSurfaceBufferCreate
#define IOSurfaceFlushProcessorCaches CoreSurfaceBufferFlushProcessorCaches
#define IOSurfaceGetBaseAddress CoreSurfaceBufferGetBaseAddress
#define IOSurfaceLock CoreSurfaceBufferLock
#define IOSurfaceUnlock CoreSurfaceBufferUnlock
#define IOSurfaceAcceleratorCreate CoreSurfaceAcceleratorCreate
#define IOSurfaceAcceleratorTransferSurface CoreSurfaceAcceleratorTransferSurface
#endif
typedef void *IOSurfaceRef;
extern CFStringRef kIOSurfaceIsGlobal;
extern CFStringRef kIOSurfaceMemoryRegion;
extern CFStringRef kIOSurfaceBytesPerRow;
extern CFStringRef kIOSurfaceWidth;
extern CFStringRef kIOSurfaceHeight;
extern CFStringRef kIOSurfacePixelFormat;
extern CFStringRef kIOSurfaceAllocSize;
#define kIOSurfaceLockReadOnly 1
#define kIOSurfaceLockAvoidSync 2
extern "C" IOSurfaceRef IOSurfaceCreate(CFDictionaryRef dict);
extern "C" int IOSurfaceLock(IOSurfaceRef surface, uint32_t options, uint32_t *seed);
extern "C" int IOSurfaceUnlock(IOSurfaceRef surface, uint32_t options, uint32_t *seed);
extern "C" void *IOSurfaceGetBaseAddress(IOSurfaceRef surface);
extern "C" void IOSurfaceFlushProcessorCaches(IOSurfaceRef buffer);
typedef void *IOSurfaceAcceleratorRef;
extern "C" int IOSurfaceAcceleratorCreate(CFAllocatorRef allocator, void *type, IOSurfaceAcceleratorRef *accel);
extern "C" unsigned int IOSurfaceAcceleratorTransferSurface(IOSurfaceAcceleratorRef accelerator, IOSurfaceRef dest, IOSurfaceRef src, void *, void *, void *, void *);
#if defined(_ARM_ARCH_6) && !defined(_ARM_ARCH_7)
#define CoreSurfaceBufferLock(surface, options, seed) \
CoreSurfaceBufferLock(surface, 3, NULL)
#define CoreSurfaceBufferUnlock(surface, options, seed) \
CoreSurfaceBufferUnlock(surface, 3, NULL)
#endif
typedef void *IOMobileFramebufferRef;
extern "C" kern_return_t IOMobileFramebufferSwapSetLayer(
IOMobileFramebufferRef fb,
int layer,
IOSurfaceRef buffer,
CGRect bounds,
CGRect frame,
int flags
);
extern "C" void IOMobileFramebufferGetDisplaySize(IOMobileFramebufferRef connect, CGSize *size);
void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, BOOL *);
extern "C" {
IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint16_t page, uint16_t usage, Boolean down, IOHIDEventOptionBits flags);
IOHIDEventRef IOHIDEventCreateDigitizerEvent(CFAllocatorRef allocator, uint64_t timeStamp, IOHIDDigitizerTransducerType type, uint32_t index, uint32_t identity, uint32_t eventMask, uint32_t buttonMask, IOHIDFloat x, IOHIDFloat y, IOHIDFloat z, IOHIDFloat tipPressure, IOHIDFloat barrelPressure, Boolean range, Boolean touch, IOOptionBits options);
IOHIDEventRef IOHIDEventCreateDigitizerFingerEvent(CFAllocatorRef allocator, uint64_t timeStamp, uint32_t index, uint32_t identity, uint32_t eventMask, IOHIDFloat x, IOHIDFloat y, IOHIDFloat z, IOHIDFloat tipPressure, IOHIDFloat twist, Boolean range, Boolean touch, IOOptionBits options);
IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
void IOHIDEventAppendEvent(IOHIDEventRef parent, IOHIDEventRef child);
void IOHIDEventSetIntegerValue(IOHIDEventRef event, IOHIDEventField field, int value);
void IOHIDEventSetSenderID(IOHIDEventRef event, uint64_t sender);
void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef client, IOHIDEventRef event);
void IOHIDEventSystemConnectionDispatchEvent(IOHIDEventSystemConnectionRef connection, IOHIDEventRef event);
}
static size_t width_;
static size_t height_;
static NSUInteger ratio_ = 0;
static const size_t BytesPerPixel = 4;
static const size_t BitsPerSample = 8;
static IOSurfaceAcceleratorRef accelerator_;
static IOSurfaceRef buffer_;
static NSMutableSet *handlers_;
static rfbScreenInfoPtr screen_;
static bool running_;
static int buttons_;
static int x_, y_;
static unsigned clients_;
static CFMessagePortRef ashikase_;
static bool cursor_;
static rfbPixel *black_;
static void VNCBlack() {
if (_unlikely(black_ == NULL))
black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
screen_->frameBuffer = reinterpret_cast<char *>(black_);
}
static bool Ashikase(bool always) {
if (!always && !cursor_)
return false;
if (ashikase_ == NULL)
ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
if (ashikase_ != NULL)
return true;
cursor_ = false;
return false;
}
static CFDataRef cfTrue_;
static CFDataRef cfFalse_;
typedef struct {
float x, y;
int buttons;
BOOL absolute;
} MouseEvent;
static MouseEvent event_;
static CFDataRef cfEvent_;
typedef enum {
MouseMessageTypeEvent,
MouseMessageTypeSetEnabled
} MouseMessageType;
static void AshikaseSendEvent(float x, float y, int buttons = 0) {
event_.x = x;
event_.y = y;
event_.buttons = buttons;
event_.absolute = true;
CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
}
static void AshikaseSetEnabled(bool enabled, bool always) {
if (!Ashikase(always))
return;
CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
if (enabled)
AshikaseSendEvent(x_, y_);
}
MSClassHook(SBAlertItem)
MSClassHook(SBAlertItemsController)
MSClassHook(SBStatusBarController)
@interface VNCAlertItem : SBAlertItem
@end
static Class $VNCAlertItem;
static NSString *DialogTitle(@"Remote Access Request");
static NSString *DialogFormat(@"Accept connection from\n%s?\n\nVeency VNC Server\nby Jay Freeman (saurik)\[email protected]\nhttp://www.saurik.com/\n\nSet a VNC password in Settings!");
static NSString *DialogAccept(@"Accept");
static NSString *DialogReject(@"Reject");
static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
static NSCondition *condition_;
static NSLock *lock_;
static rfbClientPtr client_;
static void VNCSetup();
static void VNCEnabled();
float (*$GSMainScreenScaleFactor)();
static void VNCAction(rfbNewClientAction action) {
[condition_ lock];
action_ = action;
[condition_ signal];
[condition_ unlock];
}
static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
if ((flags & 0x3) == 1)
VNCAction(RFB_CLIENT_ACCEPT);
else
VNCAction(RFB_CLIENT_REFUSE);
CFRelease(notification);
}
@interface VNCBridge : NSObject {
}
+ (void) askForConnection;
+ (void) removeStatusBarItem;
+ (void) registerClient;
@end
@implementation VNCBridge
+ (void) askForConnection {
if ($VNCAlertItem != nil) {
[[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
return;
}
SInt32 error;
CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
DialogTitle, kCFUserNotificationAlertHeaderKey,
[NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
DialogReject, kCFUserNotificationDefaultButtonTitleKey,
nil]));
if (error != 0) {
CFRelease(notification);
notification = NULL;
}
if (notification == NULL) {
VNCAction(RFB_CLIENT_REFUSE);
return;
}
CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
}
+ (void) removeStatusBarItem {
AshikaseSetEnabled(false, false);
if (SBA_available())
SBA_removeStatusBarImage(const_cast<char *>("Veency"));
else if ($SBStatusBarController != nil)
[[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
else if (UIApplication *app = [$UIApplication sharedApplication])
[app removeStatusBarImageNamed:@"Veency"];
}
+ (void) registerClient {
// XXX: this could find a better home
if (ratio_ == 0) {
if ($GSMainScreenScaleFactor == NULL)
ratio_ = 1.0f;
else
ratio_ = $GSMainScreenScaleFactor();
}
++clients_;
AshikaseSetEnabled(true, false);
if (SBA_available())
SBA_addStatusBarImage(const_cast<char *>("Veency"));
else if ($SBStatusBarController != nil)
[[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
else if (UIApplication *app = [$UIApplication sharedApplication])
[app addStatusBarImageNamed:@"Veency"];
}
+ (void) performSetup:(NSThread *)thread {
NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
[thread autorelease];
VNCSetup();
VNCEnabled();
[pool release];
}
@end
MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
switch (button) {
case 1:
VNCAction(RFB_CLIENT_ACCEPT);
break;
case 2:
VNCAction(RFB_CLIENT_REFUSE);
break;
}
[self dismiss];
}
MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
UIModalView *sheet([self alertSheet]);
[sheet setDelegate:self];
[sheet setTitle:DialogTitle];
[sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
[sheet addButtonWithTitle:DialogAccept];
[sheet addButtonWithTitle:DialogReject];
}
MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
[[$SBAlertItemsController sharedInstance] activateAlertItem:self];
}
static mach_port_t (*GSTakePurpleSystemEventPort)(void);
static bool PurpleAllocated;
static int Level_;
static void FixRecord(GSEventRecord *record) {
if (Level_ < 1)
memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
}
static void VNCSettings() {
@synchronized (lock_) {
for (NSValue *handler in handlers_)
rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
[handlers_ removeAllObjects];
}
@synchronized (condition_) {
if (screen_ == NULL)
return;
[(NSString *) screen_->authPasswdData release];
if (CFStringRef password = (CFStringRef) CFPreferencesCopyAppValue(CFSTR("Password"), CFSTR("com.saurik.Veency")))
if (CFStringGetLength(password) != 0)
screen_->authPasswdData = (void *) password;
else {
CFRelease(password);
screen_->authPasswdData = [@"" retain];
}
Boolean valid;
cursor_ = CFPreferencesGetAppBooleanValue(CFSTR("ShowCursor"), CFSTR("com.saurik.Veency"), &valid);
if (!valid)
cursor_ = true;
if (clients_ != 0)
AshikaseSetEnabled(cursor_, true);
}
}
static void VNCNotifySettings(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef info
) {
CFPreferencesAppSynchronize(CFSTR("com.saurik.Veency"));
VNCSettings();
}
static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
@synchronized (condition_) {
if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
if ([password length] == 0)
return TRUE;
NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
bool good(memcmp(client->authChallenge, data, size) == 0);
[pool release];
return good;
} return TRUE;
}
}
static bool iPad1_;
struct VeencyEvent {
struct GSEventRecord record;
struct {
struct GSEventRecordInfo info;
struct GSPathInfo path;
} data;
};
static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
if (ratio_ == 0)
return;
CGPoint location = {x, y};
if (width_ > height_) {
int t(x);
x = height_ - 1 - y;
y = t;
if (!iPad1_) {
x = height_ - 1 - x;
y = width_ - 1 - y;
}
}
x /= ratio_;
y /= ratio_;
x_ = x; y_ = y;
int diff = buttons_ ^ buttons;
bool twas((buttons_ & 0x1) != 0);
bool tis((buttons & 0x1) != 0);
buttons_ = buttons;
rfbDefaultPtrAddEvent(buttons, x, y, client);
if (Ashikase(false)) {
AshikaseSendEvent(x, y, buttons);
return;
}
if (kCFCoreFoundationVersionNumber >= 800)
return VNCPointerNew(buttons, x, y, location, diff, twas, tis);
else
return VNCPointerOld(buttons, x, y, location, diff, twas, tis);
}
static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
mach_port_t purple(0);
if ((diff & 0x10) != 0) {
struct GSEventRecord record;
memset(&record, 0, sizeof(record));
record.type = (buttons & 0x10) != 0 ?
GSEventTypeHeadsetButtonDown :
GSEventTypeHeadsetButtonUp;
record.timestamp = GSCurrentEventTimestamp();
FixRecord(&record);
GSSendSystemEvent(&record);
}
if ((diff & 0x04) != 0) {
struct GSEventRecord record;
memset(&record, 0, sizeof(record));
record.type = (buttons & 0x04) != 0 ?
GSEventTypeMenuButtonDown :
GSEventTypeMenuButtonUp;
record.timestamp = GSCurrentEventTimestamp();
FixRecord(&record);
GSSendSystemEvent(&record);
}
if ((diff & 0x02) != 0) {
struct GSEventRecord record;
memset(&record, 0, sizeof(record));
record.type = (buttons & 0x02) != 0 ?
GSEventTypeLockButtonDown :
GSEventTypeLockButtonUp;
record.timestamp = GSCurrentEventTimestamp();
FixRecord(&record);
GSSendSystemEvent(&record);
}
if (twas != tis || tis) {
struct VeencyEvent event;
memset(&event, 0, sizeof(event));
event.record.type = GSEventTypeMouse;
event.record.locationInWindow.x = x;
event.record.locationInWindow.y = y;
event.record.timestamp = GSCurrentEventTimestamp();
event.record.size = sizeof(event.data);
event.data.info.handInfo.type = twas == tis ?
GSMouseEventTypeDragged :
tis ?
GSMouseEventTypeDown :
GSMouseEventTypeUp;
event.data.info.handInfo.x34 = 0x1;
event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
if (Level_ < 3)
event.data.info.pathPositions = 1;
else
event.data.info.x52 = 1;
event.data.path.x00 = 0x01;
event.data.path.x01 = 0x02;
event.data.path.x02 = tis ? 0x03 : 0x00;
event.data.path.position = event.record.locationInWindow;
mach_port_t port(0);
if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
NSArray *displays([server displays]);
if (displays != nil && [displays count] != 0)
if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
port = [display clientPortAtPosition:location];
}
if (port == 0) {
if (purple == 0)
purple = (*GSTakePurpleSystemEventPort)();
port = purple;
}
FixRecord(&event.record);
GSSendEvent(&event.record, port);
}
if (purple != 0 && PurpleAllocated)
mach_port_deallocate(mach_task_self(), purple);
}
static void VNCSendHIDEvent(IOHIDEventRef event) {
static IOHIDEventSystemClientRef client_(NULL);
if (client_ == NULL)
client_ = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
IOHIDEventSetSenderID(event, 0xDEFACEDBEEFFECE5);
IOHIDEventSystemClientDispatchEvent(client_, event);
CFRelease(event);
}
static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
if ((diff & 0x10) != 0)
VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Telephony, kHIDUsage_Tfon_Flash, (buttons & 0x10) != 0, 0));
if ((diff & 0x04) != 0)
VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Menu, (buttons & 0x04) != 0, 0));
if ((diff & 0x02) != 0)
VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Power, (buttons & 0x02) != 0, 0));
uint32_t handm;
uint32_t fingerm;
if (twas == 0 && tis == 1) {
handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity;
fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
} else if (twas == 1 && tis == 1) {
handm = kIOHIDDigitizerEventPosition;
fingerm = kIOHIDDigitizerEventPosition;
} else if (twas == 1 && tis == 0) {
handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity | kIOHIDDigitizerEventPosition;
fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
} else return;
// XXX: avoid division in VNCPointer()
x *= ratio_;
y *= ratio_;
IOHIDFloat xf(x);
IOHIDFloat yf(y);
xf /= width_;
yf /= height_;
IOHIDEventRef hand(IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault, mach_absolute_time(), kIOHIDDigitizerTransducerTypeHand, 1<<22, 1, handm, 0, xf, yf, 0, 0, 0, 0, 0, 0));
IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldIsBuiltIn, true);
IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldDigitizerIsDisplayIntegrated, true);
IOHIDEventRef finger(IOHIDEventCreateDigitizerFingerEvent(kCFAllocatorDefault, mach_absolute_time(), 3, 2, fingerm, xf, yf, 0, 0, 0, tis, tis, 0));
IOHIDEventAppendEvent(hand, finger);
CFRelease(finger);
VNCSendHIDEvent(hand);
}
GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
static void VNCKeyboardNew(rfbBool down, rfbKeySym key, rfbClientPtr client) {
//NSLog(@"VNC d:%u k:%04x", down, key);
uint16_t usage;
switch (key) {
case XK_exclam: case XK_1: usage = kHIDUsage_Keyboard1; break;
case XK_at: case XK_2: usage = kHIDUsage_Keyboard2; break;
case XK_numbersign: case XK_3: usage = kHIDUsage_Keyboard3; break;
case XK_dollar: case XK_4: usage = kHIDUsage_Keyboard4; break;
case XK_percent: case XK_5: usage = kHIDUsage_Keyboard5; break;
case XK_asciicircum: case XK_6: usage = kHIDUsage_Keyboard6; break;
case XK_ampersand: case XK_7: usage = kHIDUsage_Keyboard7; break;
case XK_asterisk: case XK_8: usage = kHIDUsage_Keyboard8; break;
case XK_parenleft: case XK_9: usage = kHIDUsage_Keyboard9; break;
case XK_parenright: case XK_0: usage = kHIDUsage_Keyboard0; break;
case XK_A: case XK_a: usage = kHIDUsage_KeyboardA; break;
case XK_B: case XK_b: usage = kHIDUsage_KeyboardB; break;
case XK_C: case XK_c: usage = kHIDUsage_KeyboardC; break;
case XK_D: case XK_d: usage = kHIDUsage_KeyboardD; break;
case XK_E: case XK_e: usage = kHIDUsage_KeyboardE; break;
case XK_F: case XK_f: usage = kHIDUsage_KeyboardF; break;
case XK_G: case XK_g: usage = kHIDUsage_KeyboardG; break;
case XK_H: case XK_h: usage = kHIDUsage_KeyboardH; break;
case XK_I: case XK_i: usage = kHIDUsage_KeyboardI; break;
case XK_J: case XK_j: usage = kHIDUsage_KeyboardJ; break;
case XK_K: case XK_k: usage = kHIDUsage_KeyboardK; break;
case XK_L: case XK_l: usage = kHIDUsage_KeyboardL; break;
case XK_M: case XK_m: usage = kHIDUsage_KeyboardM; break;
case XK_N: case XK_n: usage = kHIDUsage_KeyboardN; break;
case XK_O: case XK_o: usage = kHIDUsage_KeyboardO; break;
case XK_P: case XK_p: usage = kHIDUsage_KeyboardP; break;
case XK_Q: case XK_q: usage = kHIDUsage_KeyboardQ; break;
case XK_R: case XK_r: usage = kHIDUsage_KeyboardR; break;
case XK_S: case XK_s: usage = kHIDUsage_KeyboardS; break;
case XK_T: case XK_t: usage = kHIDUsage_KeyboardT; break;
case XK_U: case XK_u: usage = kHIDUsage_KeyboardU; break;
case XK_V: case XK_v: usage = kHIDUsage_KeyboardV; break;
case XK_W: case XK_w: usage = kHIDUsage_KeyboardW; break;
case XK_X: case XK_x: usage = kHIDUsage_KeyboardX; break;
case XK_Y: case XK_y: usage = kHIDUsage_KeyboardY; break;
case XK_Z: case XK_z: usage = kHIDUsage_KeyboardZ; break;
case XK_underscore: case XK_minus: usage = kHIDUsage_KeyboardHyphen; break;
case XK_plus: case XK_equal: usage = kHIDUsage_KeyboardEqualSign; break;
case XK_braceleft: case XK_bracketleft: usage = kHIDUsage_KeyboardOpenBracket; break;
case XK_braceright: case XK_bracketright: usage = kHIDUsage_KeyboardCloseBracket; break;
case XK_bar: case XK_backslash: usage = kHIDUsage_KeyboardBackslash; break;
case XK_colon: case XK_semicolon: usage = kHIDUsage_KeyboardSemicolon; break;
case XK_quotedbl: case XK_apostrophe: usage = kHIDUsage_KeyboardQuote; break;
case XK_asciitilde: case XK_grave: usage = kHIDUsage_KeyboardGraveAccentAndTilde; break;
case XK_less: case XK_comma: usage = kHIDUsage_KeyboardComma; break;
case XK_greater: case XK_period: usage = kHIDUsage_KeyboardPeriod; break;
case XK_question: case XK_slash: usage = kHIDUsage_KeyboardSlash; break;
case XK_Return: usage = kHIDUsage_KeyboardReturnOrEnter; break;
case XK_BackSpace: usage = kHIDUsage_KeyboardDeleteOrBackspace; break;
case XK_Tab: usage = kHIDUsage_KeyboardTab; break;
case XK_space: usage = kHIDUsage_KeyboardSpacebar; break;
case XK_Shift_L: usage = kHIDUsage_KeyboardLeftShift; break;
case XK_Shift_R: usage = kHIDUsage_KeyboardRightShift; break;
case XK_Control_L: usage = kHIDUsage_KeyboardLeftControl; break;
case XK_Control_R: usage = kHIDUsage_KeyboardRightControl; break;
case XK_Meta_L: usage = kHIDUsage_KeyboardLeftAlt; break;
case XK_Meta_R: usage = kHIDUsage_KeyboardRightAlt; break;
case XK_Alt_L: usage = kHIDUsage_KeyboardLeftGUI; break;
case XK_Alt_R: usage = kHIDUsage_KeyboardRightGUI; break;
case XK_Up: usage = kHIDUsage_KeyboardUpArrow; break;
case XK_Down: usage = kHIDUsage_KeyboardDownArrow; break;
case XK_Left: usage = kHIDUsage_KeyboardLeftArrow; break;
case XK_Right: usage = kHIDUsage_KeyboardRightArrow; break;
case XK_Home: case XK_Begin: usage = kHIDUsage_KeyboardHome; break;
case XK_End: usage = kHIDUsage_KeyboardEnd; break;
case XK_Page_Up: usage = kHIDUsage_KeyboardPageUp; break;
case XK_Page_Down: usage = kHIDUsage_KeyboardPageDown; break;
default: return;
}
VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_KeyboardOrKeypad, usage, down, 0));
}
static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
if (kCFCoreFoundationVersionNumber >= 800)
return VNCKeyboardNew(down, key, client);
if (!down)
return;
switch (key) {
case XK_Return: key = '\r'; break;
case XK_BackSpace: key = 0x7f; break;
}
if (key > 0xfff)
return;
CGPoint point(CGPointMake(x_, y_));
UniChar unicode(key);
CFStringRef string(NULL);
GSEventRef event0, event1(NULL);
if ($GSEventCreateKeyEvent != NULL) {
string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
} else if ($GSCreateSyntheticKeyEvent != NULL) {
event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
GSEventRecord *record(_GSEventGetGSEventRecord(event0));
record->type = GSEventTypeKeyDown;
} else return;
mach_port_t port(0);
if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
NSArray *displays([server displays]);
if (displays != nil && [displays count] != 0)
if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
port = [display clientPortAtPosition:point];
}
mach_port_t purple(0);
if (port == 0) {
if (purple == 0)
purple = (*GSTakePurpleSystemEventPort)();
port = purple;
}
if (port != 0) {
GSSendEvent(_GSEventGetGSEventRecord(event0), port);
if (event1 != NULL)
GSSendEvent(_GSEventGetGSEventRecord(event1), port);
}
if (purple != 0 && PurpleAllocated)
mach_port_deallocate(mach_task_self(), purple);
CFRelease(event0);
if (event1 != NULL)
CFRelease(event1);
if (string != NULL)
CFRelease(string);
}
static void VNCDisconnect(rfbClientPtr client) {
@synchronized (condition_) {
if (--clients_ == 0)
[VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
}
}
static rfbNewClientAction VNCClient(rfbClientPtr client) {
[condition_ lock];
rfbNewClientAction action;
if (screen_->authPasswdData != NULL && [(NSString *) screen_->authPasswdData length] != 0)
action = RFB_CLIENT_ACCEPT;
else {
client_ = client;
[VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
while (action_ == RFB_CLIENT_ON_HOLD)
[condition_ wait];
action = action_;
action_ = RFB_CLIENT_ON_HOLD;
}
if (action == RFB_CLIENT_ACCEPT) {
[VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
client->clientGoneHook = &VNCDisconnect;
}
[condition_ unlock];
return action;
}
extern "C" bool GSSystemHasCapability(NSString *);
static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
static BOOL (*$MGGetBoolAnswer)(CFStringRef);
static void VNCLog(const char *format, ...) {
va_list args;
va_start(args, format);
NSLogv([NSString stringWithUTF8String:format], args);
va_end(args);
}
static void VNCSetup() {
if (true)
rfbLogEnable(false);
else
rfbLog = &VNCLog;
@synchronized (condition_) {
int argc(1);
char *arg0(strdup("VNCServer"));
char *argv[] = {arg0, NULL};
screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
free(arg0);
VNCSettings();
}
screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
screen_->alwaysShared = TRUE;
screen_->handleEventsEagerly = TRUE;
screen_->deferUpdateTime = 1000 / 25;
screen_->serverFormat.redShift = BitsPerSample * 2;
screen_->serverFormat.greenShift = BitsPerSample * 1;
screen_->serverFormat.blueShift = BitsPerSample * 0;
$GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
$GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
$MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
CFTypeRef opengles2;
if ($GSSystemCopyCapability != NULL) {
opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
} else if ($GSSystemGetCapability != NULL) {
opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
if (opengles2 != NULL)
CFRetain(opengles2);
} else if ($MGGetBoolAnswer != NULL) {
opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
CFRetain(opengles2);
} else
opengles2 = NULL;
bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
if (accelerated)
IOSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
if (opengles2 != NULL)
CFRelease(opengles2);
if (accelerator_ == NULL)
VNCBlack();
else {
buffer_ = IOSurfaceCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
@"PurpleEDRAM", kIOSurfaceMemoryRegion,
[NSNumber numberWithBool:YES], kIOSurfaceIsGlobal,
[NSNumber numberWithInt:(width_ * BytesPerPixel)], kIOSurfaceBytesPerRow,
[NSNumber numberWithInt:width_], kIOSurfaceWidth,
[NSNumber numberWithInt:height_], kIOSurfaceHeight,
[NSNumber numberWithInt:'BGRA'], kIOSurfacePixelFormat,
[NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kIOSurfaceAllocSize,
nil]);
screen_->frameBuffer = reinterpret_cast<char *>(IOSurfaceGetBaseAddress(buffer_));
}
screen_->kbdAddEvent = &VNCKeyboard;
screen_->ptrAddEvent = &VNCPointer;
screen_->newClientHook = &VNCClient;
screen_->passwordCheck = &VNCCheck;
screen_->cursor = NULL;
}
static void VNCEnabled() {
if (screen_ == NULL)
return;
@synchronized (lock_) {
Boolean valid;
bool enabled(CFPreferencesGetAppBooleanValue(CFSTR("Enabled"), CFSTR("com.saurik.Veency"), &valid));
if (!valid)
enabled = true;
if (enabled != running_)
if (enabled) {
running_ = true;
screen_->socketState = RFB_SOCKET_INIT;
rfbInitServer(screen_);
rfbRunEventLoop(screen_, -1, true);
} else {
rfbShutdownServer(screen_, true);
running_ = false;
}
}
}
static void VNCNotifyEnabled(
CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef info
) {
CFPreferencesAppSynchronize(CFSTR("com.saurik.Veency"));
VNCEnabled();
}
static IOMobileFramebufferRef main_;
static IOSurfaceRef layer_;
static void OnLayer(IOMobileFramebufferRef fb, IOSurfaceRef layer) {
if (_unlikely(width_ == 0 || height_ == 0)) {
CGSize size;
IOMobileFramebufferGetDisplaySize(fb, &size);