]> git.saurik.com Git - veency.git/blob - Tweak.mm
9c1ae76751fd8abcc8261f53cdc16fed305a560c
[veency.git] / Tweak.mm
1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2012 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 <CydiaSubstrate.h>
30
31 #include <rfb/rfb.h>
32 #include <rfb/keysym.h>
33
34 #include <mach/mach_port.h>
35 #include <sys/mman.h>
36 #include <sys/sysctl.h>
37
38 #import <QuartzCore/CAWindowServer.h>
39 #import <QuartzCore/CAWindowServerDisplay.h>
40
41 #import <CoreGraphics/CGGeometry.h>
42 #import <GraphicsServices/GraphicsServices.h>
43 #import <Foundation/Foundation.h>
44 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
45 #import <IOKit/IOKitLib.h>
46 #import <UIKit/UIKit.h>
47
48 #import <SpringBoard/SBAlertItemsController.h>
49 #import <SpringBoard/SBDismissOnlyAlertItem.h>
50 #import <SpringBoard/SBStatusBarController.h>
51
52 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
53
54 static size_t width_;
55 static size_t height_;
56 static NSUInteger ratio_ = 0;
57
58 static const size_t BytesPerPixel = 4;
59 static const size_t BitsPerSample = 8;
60
61 static CoreSurfaceAcceleratorRef accelerator_;
62 static CoreSurfaceBufferRef buffer_;
63 static CFDictionaryRef options_;
64
65 static NSMutableSet *handlers_;
66 static rfbScreenInfoPtr screen_;
67 static bool running_;
68 static int buttons_;
69 static int x_, y_;
70
71 static unsigned clients_;
72
73 static CFMessagePortRef ashikase_;
74 static bool cursor_;
75
76 static rfbPixel *black_;
77
78 static void VNCBlack() {
79 if (_unlikely(black_ == NULL))
80 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
81 screen_->frameBuffer = reinterpret_cast<char *>(black_);
82 }
83
84 static bool Ashikase(bool always) {
85 if (!always && !cursor_)
86 return false;
87
88 if (ashikase_ == NULL)
89 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
90 if (ashikase_ != NULL)
91 return true;
92
93 cursor_ = false;
94 return false;
95 }
96
97 static CFDataRef cfTrue_;
98 static CFDataRef cfFalse_;
99
100 typedef struct {
101 float x, y;
102 int buttons;
103 BOOL absolute;
104 } MouseEvent;
105
106 static MouseEvent event_;
107 static CFDataRef cfEvent_;
108
109 typedef enum {
110 MouseMessageTypeEvent,
111 MouseMessageTypeSetEnabled
112 } MouseMessageType;
113
114 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
115 event_.x = x;
116 event_.y = y;
117 event_.buttons = buttons;
118 event_.absolute = true;
119
120 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
121 }
122
123 static void AshikaseSetEnabled(bool enabled, bool always) {
124 if (!Ashikase(always))
125 return;
126
127 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
128
129 if (enabled)
130 AshikaseSendEvent(x_, y_);
131 }
132
133 MSClassHook(SBAlertItemsController)
134 MSClassHook(SBStatusBarController)
135
136 @class VNCAlertItem;
137 static Class $VNCAlertItem;
138
139 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
140 static NSCondition *condition_;
141 static NSLock *lock_;
142
143 static rfbClientPtr client_;
144
145 static void VNCSetup();
146 static void VNCEnabled();
147
148 @interface VNCBridge : NSObject {
149 }
150
151 + (void) askForConnection;
152 + (void) removeStatusBarItem;
153 + (void) registerClient;
154
155 @end
156
157 @implementation VNCBridge
158
159 + (void) askForConnection {
160 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
161 }
162
163 + (void) removeStatusBarItem {
164 AshikaseSetEnabled(false, false);
165
166 if ($SBStatusBarController != nil)
167 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
168 else
169 [[UIApplication sharedApplication] removeStatusBarImageNamed:@"Veency"];
170 }
171
172 + (void) registerClient {
173 // XXX: this could find a better home
174 if (ratio_ == 0) {
175 UIScreen *screen([UIScreen mainScreen]);
176 if ([screen respondsToSelector:@selector(scale)])
177 ratio_ = [screen scale];
178 else
179 ratio_ = 1;
180 }
181
182 ++clients_;
183 AshikaseSetEnabled(true, false);
184
185 if ($SBStatusBarController != nil)
186 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
187 else
188 [[UIApplication sharedApplication] addStatusBarImageNamed:@"Veency"];
189 }
190
191 + (void) performSetup:(NSThread *)thread {
192 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
193 [thread autorelease];
194 VNCSetup();
195 VNCEnabled();
196 [pool release];
197 }
198
199 @end
200
201 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
202 [condition_ lock];
203
204 switch (button) {
205 case 1:
206 action_ = RFB_CLIENT_ACCEPT;
207
208 @synchronized (condition_) {
209 [VNCBridge registerClient];
210 }
211 break;
212
213 case 2:
214 action_ = RFB_CLIENT_REFUSE;
215 break;
216 }
217
218 [condition_ signal];
219 [condition_ unlock];
220 [self dismiss];
221 }
222
223 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
224 UIModalView *sheet([self alertSheet]);
225 [sheet setDelegate:self];
226 [sheet setTitle:@"Remote Access Request"];
227 [sheet setBodyText:[NSString stringWithFormat:@"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!", client_->host]];
228 [sheet addButtonWithTitle:@"Accept"];
229 [sheet addButtonWithTitle:@"Reject"];
230 }
231
232 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
233 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
234 }
235
236 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
237 static bool PurpleAllocated;
238 static int Level_;
239
240 static void FixRecord(GSEventRecord *record) {
241 if (Level_ < 1)
242 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
243 }
244
245 static void VNCSettings() {
246 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
247
248 @synchronized (lock_) {
249 for (NSValue *handler in handlers_)
250 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
251 [handlers_ removeAllObjects];
252 }
253
254 @synchronized (condition_) {
255 if (screen_ == NULL)
256 return;
257
258 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
259 screen_->authPasswdData = NULL;
260
261 if (settings != nil)
262 if (NSString *password = [settings objectForKey:@"Password"])
263 if ([password length] != 0)
264 screen_->authPasswdData = [password retain];
265
266 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
267 cursor_ = cursor == nil ? true : [cursor boolValue];
268
269 if (clients_ != 0)
270 AshikaseSetEnabled(cursor_, true);
271 }
272 }
273
274 static void VNCNotifySettings(
275 CFNotificationCenterRef center,
276 void *observer,
277 CFStringRef name,
278 const void *object,
279 CFDictionaryRef info
280 ) {
281 VNCSettings();
282 }
283
284 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
285 @synchronized (condition_) {
286 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
287 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
288 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
289 bool good(memcmp(client->authChallenge, data, size) == 0);
290 [pool release];
291 return good;
292 } return TRUE;
293 }
294 }
295
296 static bool iPad1_;
297
298 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
299 if (ratio_ == 0)
300 return;
301
302 CGPoint location = {x, y};
303
304 if (width_ > height_) {
305 int t(x);
306 x = height_ - 1 - y;
307 y = t;
308
309 if (!iPad1_) {
310 x = height_ - 1 - x;
311 y = width_ - 1 - y;
312 }
313 }
314
315 x /= ratio_;
316 y /= ratio_;
317
318 x_ = x; y_ = y;
319 int diff = buttons_ ^ buttons;
320 bool twas((buttons_ & 0x1) != 0);
321 bool tis((buttons & 0x1) != 0);
322 buttons_ = buttons;
323
324 rfbDefaultPtrAddEvent(buttons, x, y, client);
325
326 if (Ashikase(false)) {
327 AshikaseSendEvent(x, y, buttons);
328 return;
329 }
330
331 mach_port_t purple(0);
332
333 if ((diff & 0x10) != 0) {
334 struct GSEventRecord record;
335
336 memset(&record, 0, sizeof(record));
337
338 record.type = (buttons & 0x10) != 0 ?
339 GSEventTypeHeadsetButtonDown :
340 GSEventTypeHeadsetButtonUp;
341
342 record.timestamp = GSCurrentEventTimestamp();
343
344 FixRecord(&record);
345 GSSendSystemEvent(&record);
346 }
347
348 if ((diff & 0x04) != 0) {
349 struct GSEventRecord record;
350
351 memset(&record, 0, sizeof(record));
352
353 record.type = (buttons & 0x04) != 0 ?
354 GSEventTypeMenuButtonDown :
355 GSEventTypeMenuButtonUp;
356
357 record.timestamp = GSCurrentEventTimestamp();
358
359 FixRecord(&record);
360 GSSendSystemEvent(&record);
361 }
362
363 if ((diff & 0x02) != 0) {
364 struct GSEventRecord record;
365
366 memset(&record, 0, sizeof(record));
367
368 record.type = (buttons & 0x02) != 0 ?
369 GSEventTypeLockButtonDown :
370 GSEventTypeLockButtonUp;
371
372 record.timestamp = GSCurrentEventTimestamp();
373
374 FixRecord(&record);
375 GSSendSystemEvent(&record);
376 }
377
378 if (twas != tis || tis) {
379 struct {
380 struct GSEventRecord record;
381 struct {
382 struct GSEventRecordInfo info;
383 struct GSPathInfo path;
384 } data;
385 } event;
386
387 memset(&event, 0, sizeof(event));
388
389 event.record.type = GSEventTypeMouse;
390 event.record.locationInWindow.x = x;
391 event.record.locationInWindow.y = y;
392 event.record.timestamp = GSCurrentEventTimestamp();
393 event.record.size = sizeof(event.data);
394
395 event.data.info.handInfo.type = twas == tis ?
396 GSMouseEventTypeDragged :
397 tis ?
398 GSMouseEventTypeDown :
399 GSMouseEventTypeUp;
400
401 event.data.info.handInfo.x34 = 0x1;
402 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
403
404 if (Level_ < 3)
405 event.data.info.pathPositions = 1;
406 else
407 event.data.info.x52 = 1;
408
409 event.data.path.x00 = 0x01;
410 event.data.path.x01 = 0x02;
411 event.data.path.x02 = tis ? 0x03 : 0x00;
412 event.data.path.position = event.record.locationInWindow;
413
414 mach_port_t port(0);
415
416 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
417 NSArray *displays([server displays]);
418 if (displays != nil && [displays count] != 0)
419 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
420 port = [display clientPortAtPosition:location];
421 }
422
423 if (port == 0) {
424 if (purple == 0)
425 purple = (*GSTakePurpleSystemEventPort)();
426 port = purple;
427 }
428
429 FixRecord(&event.record);
430 GSSendEvent(&event.record, port);
431 }
432
433 if (purple != 0 && PurpleAllocated)
434 mach_port_deallocate(mach_task_self(), purple);
435 }
436
437 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
438 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
439
440 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
441 if (!down)
442 return;
443
444 switch (key) {
445 case XK_Return: key = '\r'; break;
446 case XK_BackSpace: key = 0x7f; break;
447 }
448
449 if (key > 0xfff)
450 return;
451
452 CGPoint point(CGPointMake(x_, y_));
453
454 UniChar unicode(key);
455 CFStringRef string(NULL);
456
457 GSEventRef event0, event1(NULL);
458 if ($GSEventCreateKeyEvent != NULL) {
459 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
460 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
461 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
462 } else if ($GSCreateSyntheticKeyEvent != NULL) {
463 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
464 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
465 record->type = GSEventTypeKeyDown;
466 } else return;
467
468 mach_port_t port(0);
469
470 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
471 NSArray *displays([server displays]);
472 if (displays != nil && [displays count] != 0)
473 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
474 port = [display clientPortAtPosition:point];
475 }
476
477 mach_port_t purple(0);
478
479 if (port == 0) {
480 if (purple == 0)
481 purple = (*GSTakePurpleSystemEventPort)();
482 port = purple;
483 }
484
485 if (port != 0) {
486 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
487 if (event1 != NULL)
488 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
489 }
490
491 if (purple != 0 && PurpleAllocated)
492 mach_port_deallocate(mach_task_self(), purple);
493
494 CFRelease(event0);
495 if (event1 != NULL)
496 CFRelease(event1);
497 if (string != NULL)
498 CFRelease(string);
499 }
500
501 static void VNCDisconnect(rfbClientPtr client) {
502 @synchronized (condition_) {
503 if (--clients_ == 0)
504 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
505 }
506 }
507
508 static rfbNewClientAction VNCClient(rfbClientPtr client) {
509 @synchronized (condition_) {
510 if (screen_->authPasswdData != NULL) {
511 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
512 client->clientGoneHook = &VNCDisconnect;
513 return RFB_CLIENT_ACCEPT;
514 }
515 }
516
517 [condition_ lock];
518 client_ = client;
519 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
520 while (action_ == RFB_CLIENT_ON_HOLD)
521 [condition_ wait];
522 rfbNewClientAction action(action_);
523 action_ = RFB_CLIENT_ON_HOLD;
524 [condition_ unlock];
525
526 if (action == RFB_CLIENT_ACCEPT)
527 client->clientGoneHook = &VNCDisconnect;
528 return action;
529 }
530
531 extern "C" bool GSSystemHasCapability(NSString *);
532
533 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
534 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
535
536 static void VNCSetup() {
537 rfbLogEnable(false);
538
539 @synchronized (condition_) {
540 int argc(1);
541 char *arg0(strdup("VNCServer"));
542 char *argv[] = {arg0, NULL};
543 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
544 free(arg0);
545
546 VNCSettings();
547 }
548
549 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
550
551 screen_->alwaysShared = TRUE;
552 screen_->handleEventsEagerly = TRUE;
553 screen_->deferUpdateTime = 1000 / 25;
554
555 screen_->serverFormat.redShift = BitsPerSample * 2;
556 screen_->serverFormat.greenShift = BitsPerSample * 1;
557 screen_->serverFormat.blueShift = BitsPerSample * 0;
558
559 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
560 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
561
562 CFTypeRef opengles2;
563
564 if ($GSSystemCopyCapability != NULL) {
565 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
566 } else if ($GSSystemGetCapability != NULL) {
567 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
568 if (opengles2 != NULL)
569 CFRetain(opengles2);
570 } else
571 opengles2 = NULL;
572
573 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
574
575 if (accelerated)
576 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
577
578 if (opengles2 != NULL)
579 CFRelease(opengles2);
580
581 if (accelerator_ != NULL)
582 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
583 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
584 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
585 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
586 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
587 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
588 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
589 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
590 nil]);
591 else
592 VNCBlack();
593
594 //screen_->frameBuffer = reinterpret_cast<char *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
595
596 CoreSurfaceBufferLock(buffer_, 3);
597 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
598 CoreSurfaceBufferUnlock(buffer_);
599
600 screen_->kbdAddEvent = &VNCKeyboard;
601 screen_->ptrAddEvent = &VNCPointer;
602
603 screen_->newClientHook = &VNCClient;
604 screen_->passwordCheck = &VNCCheck;
605
606 screen_->cursor = NULL;
607 }
608
609 static void VNCEnabled() {
610 [lock_ lock];
611
612 bool enabled(true);
613 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
614 if (NSNumber *number = [settings objectForKey:@"Enabled"])
615 enabled = [number boolValue];
616
617 if (enabled != running_)
618 if (enabled) {
619 running_ = true;
620 screen_->socketState = RFB_SOCKET_INIT;
621 rfbInitServer(screen_);
622 rfbRunEventLoop(screen_, -1, true);
623 } else {
624 rfbShutdownServer(screen_, true);
625 running_ = false;
626 }
627
628 [lock_ unlock];
629 }
630
631 static void VNCNotifyEnabled(
632 CFNotificationCenterRef center,
633 void *observer,
634 CFStringRef name,
635 const void *object,
636 CFDictionaryRef info
637 ) {
638 VNCEnabled();
639 }
640
641 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, int *);
642
643 static IOMobileFramebufferRef main_;
644 static CoreSurfaceBufferRef layer_;
645
646 static void OnLayer(IOMobileFramebufferRef fb, CoreSurfaceBufferRef layer) {
647 if (_unlikely(width_ == 0 || height_ == 0)) {
648 CGSize size;
649 IOMobileFramebufferGetDisplaySize(fb, &size);
650
651 width_ = size.width;
652 height_ = size.height;
653
654 if (width_ == 0 || height_ == 0)
655 return;
656
657 NSThread *thread([NSThread alloc]);
658
659 [thread
660 initWithTarget:[VNCBridge class]
661 selector:@selector(performSetup:)
662 object:thread
663 ];
664
665 [thread start];
666 } else if (_unlikely(clients_ != 0)) {
667 if (layer == NULL) {
668 if (accelerator_ != NULL)
669 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
670 else
671 VNCBlack();
672 } else {
673 if (accelerator_ != NULL)
674 CoreSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, options_);
675 else {
676 CoreSurfaceBufferLock(layer, 2);
677 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(layer)));
678
679 CoreSurfaceBufferFlushProcessorCaches(layer);
680
681 /*rfbPixel corner(data[0]);
682 data[0] = 0;
683 data[0] = corner;*/
684
685 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
686 CoreSurfaceBufferUnlock(layer);
687 }
688 }
689
690 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
691 }
692 }
693
694 static bool wait_ = false;
695
696 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
697 IOMobileFramebufferRef fb,
698 int layer,
699 CoreSurfaceBufferRef buffer,
700 CGRect bounds,
701 CGRect frame,
702 int flags
703 ) {
704 int main(false);
705
706 if (_unlikely(buffer == NULL))
707 main = fb == main_;
708 else if (_unlikely(fb == NULL))
709 main = false;
710 else if ($IOMobileFramebufferIsMainDisplay == NULL)
711 main = true;
712 else
713 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
714
715 if (_likely(main)) {
716 main_ = fb;
717 if (wait_)
718 layer_ = buffer;
719 else
720 OnLayer(fb, buffer);
721 }
722
723 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
724 }
725
726 // XXX: beg rpetrich for the type of this function
727 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
728
729 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
730 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
731 if (fb == main_)
732 OnLayer(fb, layer_);
733 return value;
734 }
735
736 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
737 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
738
739 @synchronized (lock_) {
740 [handlers_ addObject:[NSValue valueWithPointer:handler]];
741 _rfbRegisterSecurityHandler(handler);
742 }
743
744 [pool release];
745 }
746
747 template <typename Type_>
748 static void dlset(Type_ &function, const char *name) {
749 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
750 }
751
752 MSInitialize {
753 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
754
755 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
756 if (GSTakePurpleSystemEventPort == NULL) {
757 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
758 PurpleAllocated = true;
759 }
760
761 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
762 Level_ = 3;
763 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
764 Level_ = 2;
765 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
766 Level_ = 1;
767 else
768 Level_ = 0;
769
770 size_t size;
771 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
772 char machine[size];
773 sysctlbyname("hw.machine", machine, &size, NULL, 0);
774 iPad1_ = strcmp(machine, "iPad1,1") == 0;
775
776 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
777 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
778 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
779
780 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
781 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
782
783 if (wait_)
784 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
785
786 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
787 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
788 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
789 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
790 objc_registerClassPair($VNCAlertItem);
791
792 CFNotificationCenterAddObserver(
793 CFNotificationCenterGetDarwinNotifyCenter(),
794 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
795 );
796
797 CFNotificationCenterAddObserver(
798 CFNotificationCenterGetDarwinNotifyCenter(),
799 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
800 );
801
802 condition_ = [[NSCondition alloc] init];
803 lock_ = [[NSLock alloc] init];
804 handlers_ = [[NSMutableSet alloc] init];
805
806 bool value;
807
808 value = true;
809 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
810
811 value = false;
812 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
813
814 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
815
816 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys:
817 nil] retain];
818
819 [pool release];
820 }