Add some debug logic to get the internal RFB logs.
[veency.git] / Tweak.mm
1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2014 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #define _trace() \
23 fprintf(stderr, "_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)
24 #define _likely(expr) \
25 __builtin_expect(expr, 1)
26 #define _unlikely(expr) \
27 __builtin_expect(expr, 0)
28
29 #include <substrate.h>
30
31 #include <rfb/rfb.h>
32 #include <rfb/keysym.h>
33
34 #include <mach/mach.h>
35 #include <mach/mach_time.h>
36
37 #include <sys/mman.h>
38 #include <sys/sysctl.h>
39
40 #undef assert
41
42 #include <CoreFoundation/CFUserNotification.h>
43 #import <CoreGraphics/CGGeometry.h>
44 #import <GraphicsServices/GraphicsServices.h>
45 #import <Foundation/Foundation.h>
46 #import <UIKit/UIKit.h>
47
48 #include <IOKit/hid/IOHIDEventTypes.h>
49 #include <IOKit/hidsystem/IOHIDUsageTables.h>
50
51 extern "C" {
52 #include "SpringBoardAccess.h"
53 }
54
55 typedef CFTypeRef IOHIDEventRef;
56 typedef CFTypeRef IOHIDEventSystemClientRef;
57 typedef CFTypeRef IOHIDEventSystemConnectionRef;
58
59 MSClassHook(BKAccessibility)
60 MSClassHook(UIApplication)
61
62 @interface UIApplication (Apple)
63 - (void) addStatusBarImageNamed:(NSString *)name;
64 - (void) removeStatusBarImageNamed:(NSString *)name;
65 @end
66
67 @interface CAWindowServerDisplay : NSObject
68 - (mach_port_t) clientPortAtPosition:(CGPoint)position;
69 @end
70
71 @interface CAWindowServer : NSObject
72 + (CAWindowServer *) serverIfRunning;
73 - (NSArray *) displays;
74 @end
75
76 @interface UIModalView : UIView
77 - (id) addButtonWithTitle:(NSString *)title;
78 - (void) setBodyText:(NSString *)text;
79 - (void) setDelegate:(id)delegate;
80 - (void) setTitle:(NSString *)title;
81 @end
82
83 @interface SBAlertItem : NSObject
84 - (void) dismiss;
85 - (UIModalView *) alertSheet;
86 @end
87
88 @interface SBAlertItemsController : NSObject
89 + (SBAlertItemsController *) sharedInstance;
90 - (void) activateAlertItem:(SBAlertItem *)item;
91 @end
92
93 @interface SBStatusBarController : NSObject
94 + (SBStatusBarController *) sharedStatusBarController;
95 - (void) addStatusBarItem:(NSString *)item;
96 - (void) removeStatusBarItem:(NSString *)item;
97 @end
98
99 #if defined(_ARM_ARCH_6) && !defined(_ARM_ARCH_7)
100
101 #define kIOSurfaceAllocSize kCoreSurfaceBufferAllocSize
102 #define kIOSurfaceBytesPerRow kCoreSurfaceBufferPitch
103 #define kIOSurfaceHeight kCoreSurfaceBufferHeight
104 #define kIOSurfaceIsGlobal kCoreSurfaceBufferGlobal
105 #define kIOSurfaceMemoryRegion kCoreSurfaceBufferMemoryRegion
106 #define kIOSurfacePixelFormat kCoreSurfaceBufferPixelFormat
107 #define kIOSurfaceWidth kCoreSurfaceBufferWidth
108
109 #define IOSurfaceRef CoreSurfaceBufferRef
110 #define IOSurfaceAcceleratorRef CoreSurfaceAcceleratorRef
111
112 #define IOSurfaceCreate CoreSurfaceBufferCreate
113 #define IOSurfaceFlushProcessorCaches CoreSurfaceBufferFlushProcessorCaches
114 #define IOSurfaceGetBaseAddress CoreSurfaceBufferGetBaseAddress
115 #define IOSurfaceLock CoreSurfaceBufferLock
116 #define IOSurfaceUnlock CoreSurfaceBufferUnlock
117
118 #define IOSurfaceAcceleratorCreate CoreSurfaceAcceleratorCreate
119 #define IOSurfaceAcceleratorTransferSurface CoreSurfaceAcceleratorTransferSurface
120
121 #endif
122
123 typedef void *IOSurfaceRef;
124
125 extern CFStringRef kIOSurfaceIsGlobal;
126 extern CFStringRef kIOSurfaceMemoryRegion;
127 extern CFStringRef kIOSurfaceBytesPerRow;
128 extern CFStringRef kIOSurfaceWidth;
129 extern CFStringRef kIOSurfaceHeight;
130 extern CFStringRef kIOSurfacePixelFormat;
131 extern CFStringRef kIOSurfaceAllocSize;
132
133 #define kIOSurfaceLockReadOnly 1
134 #define kIOSurfaceLockAvoidSync 2
135
136 extern "C" IOSurfaceRef IOSurfaceCreate(CFDictionaryRef dict);
137 extern "C" int IOSurfaceLock(IOSurfaceRef surface, uint32_t options, uint32_t *seed);
138 extern "C" int IOSurfaceUnlock(IOSurfaceRef surface, uint32_t options, uint32_t *seed);
139 extern "C" void *IOSurfaceGetBaseAddress(IOSurfaceRef surface);
140
141 extern "C" void IOSurfaceFlushProcessorCaches(IOSurfaceRef buffer);
142
143 typedef void *IOSurfaceAcceleratorRef;
144
145 extern "C" int IOSurfaceAcceleratorCreate(CFAllocatorRef allocator, void *type, IOSurfaceAcceleratorRef *accel);
146 extern "C" unsigned int IOSurfaceAcceleratorTransferSurface(IOSurfaceAcceleratorRef accelerator, IOSurfaceRef dest, IOSurfaceRef src, void *, void *, void *, void *);
147
148 #if defined(_ARM_ARCH_6) && !defined(_ARM_ARCH_7)
149 #define CoreSurfaceBufferLock(surface, options, seed) \
150 CoreSurfaceBufferLock(surface, 3, NULL)
151 #define CoreSurfaceBufferUnlock(surface, options, seed) \
152 CoreSurfaceBufferUnlock(surface, 3, NULL)
153 #endif
154
155 typedef void *IOMobileFramebufferRef;
156
157 extern "C" kern_return_t IOMobileFramebufferSwapSetLayer(
158 IOMobileFramebufferRef fb,
159 int layer,
160 IOSurfaceRef buffer,
161 CGRect bounds,
162 CGRect frame,
163 int flags
164 );
165
166 extern "C" void IOMobileFramebufferGetDisplaySize(IOMobileFramebufferRef connect, CGSize *size);
167 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, BOOL *);
168
169 extern "C" {
170 IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint16_t page, uint16_t usage, Boolean down, IOHIDEventOptionBits flags);
171
172 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);
173 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);
174
175 IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
176
177 void IOHIDEventAppendEvent(IOHIDEventRef parent, IOHIDEventRef child);
178 void IOHIDEventSetIntegerValue(IOHIDEventRef event, IOHIDEventField field, int value);
179 void IOHIDEventSetSenderID(IOHIDEventRef event, uint64_t sender);
180
181 void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef client, IOHIDEventRef event);
182 void IOHIDEventSystemConnectionDispatchEvent(IOHIDEventSystemConnectionRef connection, IOHIDEventRef event);
183 }
184
185 static size_t width_;
186 static size_t height_;
187 static NSUInteger ratio_ = 0;
188
189 static const size_t BytesPerPixel = 4;
190 static const size_t BitsPerSample = 8;
191
192 static IOSurfaceAcceleratorRef accelerator_;
193 static IOSurfaceRef buffer_;
194
195 static NSMutableSet *handlers_;
196 static rfbScreenInfoPtr screen_;
197 static bool running_;
198 static int buttons_;
199 static int x_, y_;
200
201 static unsigned clients_;
202
203 static CFMessagePortRef ashikase_;
204 static bool cursor_;
205
206 static rfbPixel *black_;
207
208 static void VNCBlack() {
209 if (_unlikely(black_ == NULL))
210 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
211 screen_->frameBuffer = reinterpret_cast<char *>(black_);
212 }
213
214 static bool Ashikase(bool always) {
215 if (!always && !cursor_)
216 return false;
217
218 if (ashikase_ == NULL)
219 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
220 if (ashikase_ != NULL)
221 return true;
222
223 cursor_ = false;
224 return false;
225 }
226
227 static CFDataRef cfTrue_;
228 static CFDataRef cfFalse_;
229
230 typedef struct {
231 float x, y;
232 int buttons;
233 BOOL absolute;
234 } MouseEvent;
235
236 static MouseEvent event_;
237 static CFDataRef cfEvent_;
238
239 typedef enum {
240 MouseMessageTypeEvent,
241 MouseMessageTypeSetEnabled
242 } MouseMessageType;
243
244 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
245 event_.x = x;
246 event_.y = y;
247 event_.buttons = buttons;
248 event_.absolute = true;
249
250 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
251 }
252
253 static void AshikaseSetEnabled(bool enabled, bool always) {
254 if (!Ashikase(always))
255 return;
256
257 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
258
259 if (enabled)
260 AshikaseSendEvent(x_, y_);
261 }
262
263 MSClassHook(SBAlertItem)
264 MSClassHook(SBAlertItemsController)
265 MSClassHook(SBStatusBarController)
266
267 @interface VNCAlertItem : SBAlertItem
268 @end
269
270 static Class $VNCAlertItem;
271
272 static NSString *DialogTitle(@"Remote Access Request");
273 static NSString *DialogFormat(@"Accept connection from\n%s?\n\nVeency VNC Server\nby Jay Freeman (saurik)\nsaurik@saurik.com\nhttp://www.saurik.com/\n\nSet a VNC password in Settings!");
274 static NSString *DialogAccept(@"Accept");
275 static NSString *DialogReject(@"Reject");
276
277 static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
278 static NSCondition *condition_;
279 static NSLock *lock_;
280
281 static rfbClientPtr client_;
282
283 static void VNCSetup();
284 static void VNCEnabled();
285
286 float (*$GSMainScreenScaleFactor)();
287
288 static void VNCAction(rfbNewClientAction action) {
289 [condition_ lock];
290 action_ = action;
291 [condition_ signal];
292 [condition_ unlock];
293 }
294
295 static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
296 if ((flags & 0x3) == 1)
297 VNCAction(RFB_CLIENT_ACCEPT);
298 else
299 VNCAction(RFB_CLIENT_REFUSE);
300
301 CFRelease(notification);
302 }
303
304 @interface VNCBridge : NSObject {
305 }
306
307 + (void) askForConnection;
308 + (void) removeStatusBarItem;
309 + (void) registerClient;
310
311 @end
312
313 @implementation VNCBridge
314
315 + (void) askForConnection {
316 if ($VNCAlertItem != nil) {
317 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
318 return;
319 }
320
321 SInt32 error;
322 CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
323 DialogTitle, kCFUserNotificationAlertHeaderKey,
324 [NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
325 DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
326 DialogReject, kCFUserNotificationDefaultButtonTitleKey,
327 nil]));
328
329 if (error != 0) {
330 CFRelease(notification);
331 notification = NULL;
332 }
333
334 if (notification == NULL) {
335 VNCAction(RFB_CLIENT_REFUSE);
336 return;
337 }
338
339 CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
340 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
341 }
342
343 + (void) removeStatusBarItem {
344 AshikaseSetEnabled(false, false);
345
346 if (SBA_available())
347 SBA_removeStatusBarImage(const_cast<char *>("Veency"));
348 else if ($SBStatusBarController != nil)
349 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
350 else if (UIApplication *app = [$UIApplication sharedApplication])
351 [app removeStatusBarImageNamed:@"Veency"];
352 }
353
354 + (void) registerClient {
355 // XXX: this could find a better home
356 if (ratio_ == 0) {
357 if ($GSMainScreenScaleFactor == NULL)
358 ratio_ = 1.0f;
359 else
360 ratio_ = $GSMainScreenScaleFactor();
361 }
362
363 ++clients_;
364 AshikaseSetEnabled(true, false);
365
366 if (SBA_available())
367 SBA_addStatusBarImage(const_cast<char *>("Veency"));
368 else if ($SBStatusBarController != nil)
369 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
370 else if (UIApplication *app = [$UIApplication sharedApplication])
371 [app addStatusBarImageNamed:@"Veency"];
372 }
373
374 + (void) performSetup:(NSThread *)thread {
375 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
376 [thread autorelease];
377 VNCSetup();
378 VNCEnabled();
379 [pool release];
380 }
381
382 @end
383
384 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
385 switch (button) {
386 case 1:
387 VNCAction(RFB_CLIENT_ACCEPT);
388 break;
389
390 case 2:
391 VNCAction(RFB_CLIENT_REFUSE);
392 break;
393 }
394
395 [self dismiss];
396 }
397
398 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
399 UIModalView *sheet([self alertSheet]);
400 [sheet setDelegate:self];
401 [sheet setTitle:DialogTitle];
402 [sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
403 [sheet addButtonWithTitle:DialogAccept];
404 [sheet addButtonWithTitle:DialogReject];
405 }
406
407 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
408 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
409 }
410
411 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
412 static bool PurpleAllocated;
413 static int Level_;
414
415 static void FixRecord(GSEventRecord *record) {
416 if (Level_ < 1)
417 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
418 }
419
420 static void VNCSettings() {
421 @synchronized (lock_) {
422 for (NSValue *handler in handlers_)
423 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
424 [handlers_ removeAllObjects];
425 }
426
427 @synchronized (condition_) {
428 if (screen_ == NULL)
429 return;
430
431 [(NSString *) screen_->authPasswdData release];
432 screen_->authPasswdData = NULL;
433
434 if (CFStringRef password = (CFStringRef) CFPreferencesCopyAppValue(CFSTR("Password"), CFSTR("com.saurik.Veency")))
435 if (CFStringGetLength(password) == 0)
436 CFRelease(password);
437 else
438 screen_->authPasswdData = (void *) password;
439
440 Boolean valid;
441 cursor_ = CFPreferencesGetAppBooleanValue(CFSTR("ShowCursor"), CFSTR("com.saurik.Veency"), &valid);
442 if (!valid)
443 cursor_ = true;
444
445 if (clients_ != 0)
446 AshikaseSetEnabled(cursor_, true);
447 }
448 }
449
450 static void VNCNotifySettings(
451 CFNotificationCenterRef center,
452 void *observer,
453 CFStringRef name,
454 const void *object,
455 CFDictionaryRef info
456 ) {
457 CFPreferencesAppSynchronize(CFSTR("com.saurik.Veency"));
458 VNCSettings();
459 }
460
461 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
462 @synchronized (condition_) {
463 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
464 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
465 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
466 bool good(memcmp(client->authChallenge, data, size) == 0);
467 [pool release];
468 return good;
469 } return TRUE;
470 }
471 }
472
473 static bool iPad1_;
474
475 struct VeencyEvent {
476 struct GSEventRecord record;
477 struct {
478 struct GSEventRecordInfo info;
479 struct GSPathInfo path;
480 } data;
481 };
482
483 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
484 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
485
486 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
487 if (ratio_ == 0)
488 return;
489
490 CGPoint location = {x, y};
491
492 if (width_ > height_) {
493 int t(x);
494 x = height_ - 1 - y;
495 y = t;
496
497 if (!iPad1_) {
498 x = height_ - 1 - x;
499 y = width_ - 1 - y;
500 }
501 }
502
503 x /= ratio_;
504 y /= ratio_;
505
506 x_ = x; y_ = y;
507 int diff = buttons_ ^ buttons;
508 bool twas((buttons_ & 0x1) != 0);
509 bool tis((buttons & 0x1) != 0);
510 buttons_ = buttons;
511
512 rfbDefaultPtrAddEvent(buttons, x, y, client);
513
514 if (Ashikase(false)) {
515 AshikaseSendEvent(x, y, buttons);
516 return;
517 }
518
519 if (kCFCoreFoundationVersionNumber >= 800)
520 return VNCPointerNew(buttons, x, y, location, diff, twas, tis);
521 else
522 return VNCPointerOld(buttons, x, y, location, diff, twas, tis);
523 }
524
525 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
526 mach_port_t purple(0);
527
528 if ((diff & 0x10) != 0) {
529 struct GSEventRecord record;
530
531 memset(&record, 0, sizeof(record));
532
533 record.type = (buttons & 0x10) != 0 ?
534 GSEventTypeHeadsetButtonDown :
535 GSEventTypeHeadsetButtonUp;
536
537 record.timestamp = GSCurrentEventTimestamp();
538
539 FixRecord(&record);
540 GSSendSystemEvent(&record);
541 }
542
543 if ((diff & 0x04) != 0) {
544 struct GSEventRecord record;
545
546 memset(&record, 0, sizeof(record));
547
548 record.type = (buttons & 0x04) != 0 ?
549 GSEventTypeMenuButtonDown :
550 GSEventTypeMenuButtonUp;
551
552 record.timestamp = GSCurrentEventTimestamp();
553
554 FixRecord(&record);
555 GSSendSystemEvent(&record);
556 }
557
558 if ((diff & 0x02) != 0) {
559 struct GSEventRecord record;
560
561 memset(&record, 0, sizeof(record));
562
563 record.type = (buttons & 0x02) != 0 ?
564 GSEventTypeLockButtonDown :
565 GSEventTypeLockButtonUp;
566
567 record.timestamp = GSCurrentEventTimestamp();
568
569 FixRecord(&record);
570 GSSendSystemEvent(&record);
571 }
572
573 if (twas != tis || tis) {
574 struct VeencyEvent event;
575
576 memset(&event, 0, sizeof(event));
577
578 event.record.type = GSEventTypeMouse;
579 event.record.locationInWindow.x = x;
580 event.record.locationInWindow.y = y;
581 event.record.timestamp = GSCurrentEventTimestamp();
582 event.record.size = sizeof(event.data);
583
584 event.data.info.handInfo.type = twas == tis ?
585 GSMouseEventTypeDragged :
586 tis ?
587 GSMouseEventTypeDown :
588 GSMouseEventTypeUp;
589
590 event.data.info.handInfo.x34 = 0x1;
591 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
592
593 if (Level_ < 3)
594 event.data.info.pathPositions = 1;
595 else
596 event.data.info.x52 = 1;
597
598 event.data.path.x00 = 0x01;
599 event.data.path.x01 = 0x02;
600 event.data.path.x02 = tis ? 0x03 : 0x00;
601 event.data.path.position = event.record.locationInWindow;
602
603 mach_port_t port(0);
604
605 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
606 NSArray *displays([server displays]);
607 if (displays != nil && [displays count] != 0)
608 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
609 port = [display clientPortAtPosition:location];
610 }
611
612 if (port == 0) {
613 if (purple == 0)
614 purple = (*GSTakePurpleSystemEventPort)();
615 port = purple;
616 }
617
618 FixRecord(&event.record);
619 GSSendEvent(&event.record, port);
620 }
621
622 if (purple != 0 && PurpleAllocated)
623 mach_port_deallocate(mach_task_self(), purple);
624 }
625
626 static void VNCSendHIDEvent(IOHIDEventRef event) {
627 static IOHIDEventSystemClientRef client_(NULL);
628 if (client_ == NULL)
629 client_ = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
630
631 IOHIDEventSetSenderID(event, 0xDEFACEDBEEFFECE5);
632 IOHIDEventSystemClientDispatchEvent(client_, event);
633 CFRelease(event);
634 }
635
636 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
637 if ((diff & 0x10) != 0)
638 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Telephony, kHIDUsage_Tfon_Flash, (buttons & 0x10) != 0, 0));
639 if ((diff & 0x04) != 0)
640 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Menu, (buttons & 0x04) != 0, 0));
641 if ((diff & 0x02) != 0)
642 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Power, (buttons & 0x02) != 0, 0));
643
644 uint32_t handm;
645 uint32_t fingerm;
646
647 if (twas == 0 && tis == 1) {
648 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity;
649 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
650 } else if (twas == 1 && tis == 1) {
651 handm = kIOHIDDigitizerEventPosition;
652 fingerm = kIOHIDDigitizerEventPosition;
653 } else if (twas == 1 && tis == 0) {
654 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity | kIOHIDDigitizerEventPosition;
655 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
656 } else return;
657
658 // XXX: avoid division in VNCPointer()
659 x *= ratio_;
660 y *= ratio_;
661
662 IOHIDFloat xf(x);
663 IOHIDFloat yf(y);
664
665 xf /= width_;
666 yf /= height_;
667
668 IOHIDEventRef hand(IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault, mach_absolute_time(), kIOHIDDigitizerTransducerTypeHand, 1<<22, 1, handm, 0, xf, yf, 0, 0, 0, 0, 0, 0));
669 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldIsBuiltIn, true);
670 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldDigitizerIsDisplayIntegrated, true);
671
672 IOHIDEventRef finger(IOHIDEventCreateDigitizerFingerEvent(kCFAllocatorDefault, mach_absolute_time(), 3, 2, fingerm, xf, yf, 0, 0, 0, tis, tis, 0));
673 IOHIDEventAppendEvent(hand, finger);
674 CFRelease(finger);
675
676 VNCSendHIDEvent(hand);
677 }
678
679 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
680 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
681
682 static void VNCKeyboardNew(rfbBool down, rfbKeySym key, rfbClientPtr client) {
683 //NSLog(@"VNC d:%u k:%04x", down, key);
684
685 uint16_t usage;
686
687 switch (key) {
688 case XK_exclam: case XK_1: usage = kHIDUsage_Keyboard1; break;
689 case XK_at: case XK_2: usage = kHIDUsage_Keyboard2; break;
690 case XK_numbersign: case XK_3: usage = kHIDUsage_Keyboard3; break;
691 case XK_dollar: case XK_4: usage = kHIDUsage_Keyboard4; break;
692 case XK_percent: case XK_5: usage = kHIDUsage_Keyboard5; break;
693 case XK_asciicircum: case XK_6: usage = kHIDUsage_Keyboard6; break;
694 case XK_ampersand: case XK_7: usage = kHIDUsage_Keyboard7; break;
695 case XK_asterisk: case XK_8: usage = kHIDUsage_Keyboard8; break;
696 case XK_parenleft: case XK_9: usage = kHIDUsage_Keyboard9; break;
697 case XK_parenright: case XK_0: usage = kHIDUsage_Keyboard0; break;
698
699 case XK_A: case XK_a: usage = kHIDUsage_KeyboardA; break;
700 case XK_B: case XK_b: usage = kHIDUsage_KeyboardB; break;
701 case XK_C: case XK_c: usage = kHIDUsage_KeyboardC; break;
702 case XK_D: case XK_d: usage = kHIDUsage_KeyboardD; break;
703 case XK_E: case XK_e: usage = kHIDUsage_KeyboardE; break;
704 case XK_F: case XK_f: usage = kHIDUsage_KeyboardF; break;
705 case XK_G: case XK_g: usage = kHIDUsage_KeyboardG; break;
706 case XK_H: case XK_h: usage = kHIDUsage_KeyboardH; break;
707 case XK_I: case XK_i: usage = kHIDUsage_KeyboardI; break;
708 case XK_J: case XK_j: usage = kHIDUsage_KeyboardJ; break;
709 case XK_K: case XK_k: usage = kHIDUsage_KeyboardK; break;
710 case XK_L: case XK_l: usage = kHIDUsage_KeyboardL; break;
711 case XK_M: case XK_m: usage = kHIDUsage_KeyboardM; break;
712 case XK_N: case XK_n: usage = kHIDUsage_KeyboardN; break;
713 case XK_O: case XK_o: usage = kHIDUsage_KeyboardO; break;
714 case XK_P: case XK_p: usage = kHIDUsage_KeyboardP; break;
715 case XK_Q: case XK_q: usage = kHIDUsage_KeyboardQ; break;
716 case XK_R: case XK_r: usage = kHIDUsage_KeyboardR; break;
717 case XK_S: case XK_s: usage = kHIDUsage_KeyboardS; break;
718 case XK_T: case XK_t: usage = kHIDUsage_KeyboardT; break;
719 case XK_U: case XK_u: usage = kHIDUsage_KeyboardU; break;
720 case XK_V: case XK_v: usage = kHIDUsage_KeyboardV; break;
721 case XK_W: case XK_w: usage = kHIDUsage_KeyboardW; break;
722 case XK_X: case XK_x: usage = kHIDUsage_KeyboardX; break;
723 case XK_Y: case XK_y: usage = kHIDUsage_KeyboardY; break;
724 case XK_Z: case XK_z: usage = kHIDUsage_KeyboardZ; break;
725
726 case XK_underscore: case XK_minus: usage = kHIDUsage_KeyboardHyphen; break;
727 case XK_plus: case XK_equal: usage = kHIDUsage_KeyboardEqualSign; break;
728 case XK_braceleft: case XK_bracketleft: usage = kHIDUsage_KeyboardOpenBracket; break;
729 case XK_braceright: case XK_bracketright: usage = kHIDUsage_KeyboardCloseBracket; break;
730 case XK_bar: case XK_backslash: usage = kHIDUsage_KeyboardBackslash; break;
731 case XK_colon: case XK_semicolon: usage = kHIDUsage_KeyboardSemicolon; break;
732 case XK_quotedbl: case XK_apostrophe: usage = kHIDUsage_KeyboardQuote; break;
733 case XK_asciitilde: case XK_grave: usage = kHIDUsage_KeyboardGraveAccentAndTilde; break;
734 case XK_less: case XK_comma: usage = kHIDUsage_KeyboardComma; break;
735 case XK_greater: case XK_period: usage = kHIDUsage_KeyboardPeriod; break;
736 case XK_question: case XK_slash: usage = kHIDUsage_KeyboardSlash; break;
737
738 case XK_Return: usage = kHIDUsage_KeyboardReturnOrEnter; break;
739 case XK_BackSpace: usage = kHIDUsage_KeyboardDeleteOrBackspace; break;
740 case XK_Tab: usage = kHIDUsage_KeyboardTab; break;
741 case XK_space: usage = kHIDUsage_KeyboardSpacebar; break;
742
743 case XK_Shift_L: usage = kHIDUsage_KeyboardLeftShift; break;
744 case XK_Shift_R: usage = kHIDUsage_KeyboardRightShift; break;
745 case XK_Control_L: usage = kHIDUsage_KeyboardLeftControl; break;
746 case XK_Control_R: usage = kHIDUsage_KeyboardRightControl; break;
747 case XK_Meta_L: usage = kHIDUsage_KeyboardLeftAlt; break;
748 case XK_Meta_R: usage = kHIDUsage_KeyboardRightAlt; break;
749 case XK_Alt_L: usage = kHIDUsage_KeyboardLeftGUI; break;
750 case XK_Alt_R: usage = kHIDUsage_KeyboardRightGUI; break;
751
752 case XK_Up: usage = kHIDUsage_KeyboardUpArrow; break;
753 case XK_Down: usage = kHIDUsage_KeyboardDownArrow; break;
754 case XK_Left: usage = kHIDUsage_KeyboardLeftArrow; break;
755 case XK_Right: usage = kHIDUsage_KeyboardRightArrow; break;
756
757 case XK_Home: case XK_Begin: usage = kHIDUsage_KeyboardHome; break;
758 case XK_End: usage = kHIDUsage_KeyboardEnd; break;
759 case XK_Page_Up: usage = kHIDUsage_KeyboardPageUp; break;
760 case XK_Page_Down: usage = kHIDUsage_KeyboardPageDown; break;
761
762 default: return;
763 }
764
765 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_KeyboardOrKeypad, usage, down, 0));
766 }
767
768 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
769 if (kCFCoreFoundationVersionNumber >= 800)
770 return VNCKeyboardNew(down, key, client);
771
772 if (!down)
773 return;
774
775 switch (key) {
776 case XK_Return: key = '\r'; break;
777 case XK_BackSpace: key = 0x7f; break;
778 }
779
780 if (key > 0xfff)
781 return;
782
783 CGPoint point(CGPointMake(x_, y_));
784
785 UniChar unicode(key);
786 CFStringRef string(NULL);
787
788 GSEventRef event0, event1(NULL);
789 if ($GSEventCreateKeyEvent != NULL) {
790 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
791 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
792 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
793 } else if ($GSCreateSyntheticKeyEvent != NULL) {
794 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
795 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
796 record->type = GSEventTypeKeyDown;
797 } else return;
798
799 mach_port_t port(0);
800
801 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
802 NSArray *displays([server displays]);
803 if (displays != nil && [displays count] != 0)
804 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
805 port = [display clientPortAtPosition:point];
806 }
807
808 mach_port_t purple(0);
809
810 if (port == 0) {
811 if (purple == 0)
812 purple = (*GSTakePurpleSystemEventPort)();
813 port = purple;
814 }
815
816 if (port != 0) {
817 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
818 if (event1 != NULL)
819 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
820 }
821
822 if (purple != 0 && PurpleAllocated)
823 mach_port_deallocate(mach_task_self(), purple);
824
825 CFRelease(event0);
826 if (event1 != NULL)
827 CFRelease(event1);
828 if (string != NULL)
829 CFRelease(string);
830 }
831
832 static void VNCDisconnect(rfbClientPtr client) {
833 @synchronized (condition_) {
834 if (--clients_ == 0)
835 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
836 }
837 }
838
839 static rfbNewClientAction VNCClient(rfbClientPtr client) {
840 [condition_ lock];
841
842 rfbNewClientAction action;
843 if (screen_->authPasswdData != NULL)
844 action = RFB_CLIENT_ACCEPT;
845 else {
846 client_ = client;
847 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
848 while (action_ == RFB_CLIENT_ON_HOLD)
849 [condition_ wait];
850 action = action_;
851 action_ = RFB_CLIENT_ON_HOLD;
852 }
853
854 if (action == RFB_CLIENT_ACCEPT) {
855 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
856 client->clientGoneHook = &VNCDisconnect;
857 }
858
859 [condition_ unlock];
860 return action;
861 }
862
863 extern "C" bool GSSystemHasCapability(NSString *);
864
865 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
866 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
867 static BOOL (*$MGGetBoolAnswer)(CFStringRef);
868
869 static void VNCLog(const char *format, ...) {
870 va_list args;
871 va_start(args, format);
872 NSLogv([NSString stringWithUTF8String:format], args);
873 va_end(args);
874 }
875
876 static void VNCSetup() {
877 if (true)
878 rfbLogEnable(false);
879 else
880 rfbLog = &VNCLog;
881
882 @synchronized (condition_) {
883 int argc(1);
884 char *arg0(strdup("VNCServer"));
885 char *argv[] = {arg0, NULL};
886 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
887 free(arg0);
888
889 VNCSettings();
890 }
891
892 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
893
894 screen_->alwaysShared = TRUE;
895 screen_->handleEventsEagerly = TRUE;
896 screen_->deferUpdateTime = 1000 / 25;
897
898 screen_->serverFormat.redShift = BitsPerSample * 2;
899 screen_->serverFormat.greenShift = BitsPerSample * 1;
900 screen_->serverFormat.blueShift = BitsPerSample * 0;
901
902 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
903 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
904 $MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
905
906 CFTypeRef opengles2;
907
908 if ($GSSystemCopyCapability != NULL) {
909 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
910 } else if ($GSSystemGetCapability != NULL) {
911 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
912 if (opengles2 != NULL)
913 CFRetain(opengles2);
914 } else if ($MGGetBoolAnswer != NULL) {
915 opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
916 CFRetain(opengles2);
917 } else
918 opengles2 = NULL;
919
920 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
921
922 if (accelerated)
923 IOSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
924
925 if (opengles2 != NULL)
926 CFRelease(opengles2);
927
928 if (accelerator_ == NULL)
929 VNCBlack();
930 else {
931 buffer_ = IOSurfaceCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
932 @"PurpleEDRAM", kIOSurfaceMemoryRegion,
933 [NSNumber numberWithBool:YES], kIOSurfaceIsGlobal,
934 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kIOSurfaceBytesPerRow,
935 [NSNumber numberWithInt:width_], kIOSurfaceWidth,
936 [NSNumber numberWithInt:height_], kIOSurfaceHeight,
937 [NSNumber numberWithInt:'BGRA'], kIOSurfacePixelFormat,
938 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kIOSurfaceAllocSize,
939 nil]);
940
941 screen_->frameBuffer = reinterpret_cast<char *>(IOSurfaceGetBaseAddress(buffer_));
942 }
943
944 screen_->kbdAddEvent = &VNCKeyboard;
945 screen_->ptrAddEvent = &VNCPointer;
946
947 screen_->newClientHook = &VNCClient;
948 screen_->passwordCheck = &VNCCheck;
949
950 screen_->cursor = NULL;
951 }
952
953 static void VNCEnabled() {
954 if (screen_ == NULL)
955 return;
956
957 @synchronized (lock_) {
958
959 Boolean valid;
960 bool enabled(CFPreferencesGetAppBooleanValue(CFSTR("Enabled"), CFSTR("com.saurik.Veency"), &valid));
961 if (!valid)
962 enabled = true;
963
964 if (enabled != running_)
965 if (enabled) {
966 running_ = true;
967 screen_->socketState = RFB_SOCKET_INIT;
968 rfbInitServer(screen_);
969 rfbRunEventLoop(screen_, -1, true);
970 } else {
971 rfbShutdownServer(screen_, true);
972 running_ = false;
973 }
974
975 }
976 }
977
978 static void VNCNotifyEnabled(
979 CFNotificationCenterRef center,
980 void *observer,
981 CFStringRef name,
982 const void *object,
983 CFDictionaryRef info
984 ) {
985 CFPreferencesAppSynchronize(CFSTR("com.saurik.Veency"));
986 VNCEnabled();
987 }
988
989
990 static IOMobileFramebufferRef main_;
991 static IOSurfaceRef layer_;
992
993 static void OnLayer(IOMobileFramebufferRef fb, IOSurfaceRef layer) {
994 if (_unlikely(width_ == 0 || height_ == 0)) {
995 CGSize size;
996 IOMobileFramebufferGetDisplaySize(fb, &size);
997
998 width_ = size.width;
999 height_ = size.height;
1000
1001 if (width_ == 0 || height_ == 0)
1002 return;
1003
1004 NSThread *thread([NSThread alloc]);
1005
1006 [thread
1007 initWithTarget:[VNCBridge class]
1008 selector:@selector(performSetup:)
1009 object:thread
1010 ];
1011
1012 [thread start];
1013 } else if (_unlikely(clients_ != 0)) {
1014 if (layer == NULL) {
1015 if (accelerator_ != NULL) {
1016 IOSurfaceLock(layer, 0, NULL);
1017 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
1018 IOSurfaceUnlock(layer, 0, NULL);
1019 } else
1020 VNCBlack();
1021 } else {
1022 if (accelerator_ != NULL)
1023 IOSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, NULL, NULL, NULL, NULL);
1024 else {
1025 IOSurfaceLock(layer, kIOSurfaceLockReadOnly, NULL);
1026 rfbPixel *data(reinterpret_cast<rfbPixel *>(IOSurfaceGetBaseAddress(layer)));
1027
1028 IOSurfaceFlushProcessorCaches(layer);
1029
1030 /*rfbPixel corner(data[0]);
1031 data[0] = 0;
1032 data[0] = corner;*/
1033
1034 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
1035 IOSurfaceUnlock(layer, kIOSurfaceLockReadOnly, NULL);
1036 }
1037 }
1038
1039 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
1040 }
1041 }
1042
1043 static bool wait_ = false;
1044
1045 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
1046 IOMobileFramebufferRef fb,
1047 int layer,
1048 IOSurfaceRef buffer,
1049 CGRect bounds,
1050 CGRect frame,
1051 int flags
1052 ) {
1053 BOOL main;
1054
1055 if (false);
1056 else if (_unlikely(layer != 0))
1057 main = false;
1058 else if (_unlikely(buffer == NULL))
1059 main = fb == main_;
1060 else if (_unlikely(fb == NULL))
1061 main = false;
1062 else if ($IOMobileFramebufferIsMainDisplay == NULL)
1063 main = true;
1064 else
1065 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
1066
1067 if (_likely(main)) {
1068 main_ = fb;
1069 if (wait_)
1070 layer_ = buffer;
1071 else
1072 OnLayer(fb, buffer);
1073 }
1074
1075 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
1076 }
1077
1078 // XXX: beg rpetrich for the type of this function
1079 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
1080
1081 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
1082 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
1083 if (fb == main_)
1084 OnLayer(fb, layer_);
1085 return value;
1086 }
1087
1088 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
1089 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1090
1091 @synchronized (lock_) {
1092 [handlers_ addObject:[NSValue valueWithPointer:handler]];
1093 _rfbRegisterSecurityHandler(handler);
1094 }
1095
1096 [pool release];
1097 }
1098
1099 template <typename Type_>
1100 static void dlset(Type_ &function, const char *name) {
1101 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1102 }
1103
1104 MSInitialize {
1105 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1106
1107 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
1108 if (GSTakePurpleSystemEventPort == NULL) {
1109 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
1110 PurpleAllocated = true;
1111 }
1112
1113 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
1114 Level_ = 3;
1115 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
1116 Level_ = 2;
1117 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
1118 Level_ = 1;
1119 else
1120 Level_ = 0;
1121
1122 size_t size;
1123 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1124 char machine[size];
1125 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1126 iPad1_ = strcmp(machine, "iPad1,1") == 0;
1127
1128 dlset($GSMainScreenScaleFactor, "GSMainScreenScaleFactor");
1129 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
1130 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
1131 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
1132
1133 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
1134 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
1135
1136 if (wait_)
1137 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
1138
1139 if ($SBAlertItem != nil) {
1140 $VNCAlertItem = objc_allocateClassPair($SBAlertItem, "VNCAlertItem", 0);
1141 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
1142 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
1143 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
1144 objc_registerClassPair($VNCAlertItem);
1145 }
1146
1147 CFNotificationCenterAddObserver(
1148 CFNotificationCenterGetDarwinNotifyCenter(),
1149 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
1150 );
1151
1152 CFNotificationCenterAddObserver(
1153 CFNotificationCenterGetDarwinNotifyCenter(),
1154 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
1155 );
1156
1157 condition_ = [[NSCondition alloc] init];
1158 lock_ = [[NSLock alloc] init];
1159 handlers_ = [[NSMutableSet alloc] init];
1160
1161 bool value;
1162
1163 value = true;
1164 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1165
1166 value = false;
1167 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1168
1169 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
1170
1171 [pool release];
1172 }