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