]> git.saurik.com Git - veency.git/blob - Tweak.mm
eb27f1528eec0cfce82f1aaaaef5a7f94f18ea29
[veency.git] / Tweak.mm
1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
3 */
4
5 /*
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
9 *
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
17 * distribution.
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 */
37
38 #define _trace() \
39 fprintf(stderr, "_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)
40 #define _likely(expr) \
41 __builtin_expect(expr, 1)
42 #define _unlikely(expr) \
43 __builtin_expect(expr, 0)
44
45 #include <CydiaSubstrate.h>
46
47 #include <rfb/rfb.h>
48 #include <rfb/keysym.h>
49
50 #include <mach/mach_port.h>
51 #include <sys/mman.h>
52 #include <sys/sysctl.h>
53
54 #import <QuartzCore/CAWindowServer.h>
55 #import <QuartzCore/CAWindowServerDisplay.h>
56
57 #import <CoreGraphics/CGGeometry.h>
58 #import <GraphicsServices/GraphicsServices.h>
59 #import <Foundation/Foundation.h>
60 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
61 #import <IOKit/IOKitLib.h>
62 #import <UIKit/UIKit.h>
63
64 #import <SpringBoard/SBAlertItemsController.h>
65 #import <SpringBoard/SBDismissOnlyAlertItem.h>
66 #import <SpringBoard/SBStatusBarController.h>
67
68 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
69
70 static size_t width_;
71 static size_t height_;
72 static NSUInteger ratio_ = 0;
73
74 static const size_t BytesPerPixel = 4;
75 static const size_t BitsPerSample = 8;
76
77 static CoreSurfaceAcceleratorRef accelerator_;
78 static CoreSurfaceBufferRef buffer_;
79 static CFDictionaryRef options_;
80
81 static NSMutableSet *handlers_;
82 static rfbScreenInfoPtr screen_;
83 static bool running_;
84 static int buttons_;
85 static int x_, y_;
86
87 static unsigned clients_;
88
89 static CFMessagePortRef ashikase_;
90 static bool cursor_;
91
92 static rfbPixel *black_;
93
94 static void VNCBlack() {
95 if (_unlikely(black_ == NULL))
96 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
97 screen_->frameBuffer = reinterpret_cast<char *>(black_);
98 }
99
100 static bool Ashikase(bool always) {
101 if (!always && !cursor_)
102 return false;
103
104 if (ashikase_ == NULL)
105 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
106 if (ashikase_ != NULL)
107 return true;
108
109 cursor_ = false;
110 return false;
111 }
112
113 static CFDataRef cfTrue_;
114 static CFDataRef cfFalse_;
115
116 typedef struct {
117 float x, y;
118 int buttons;
119 BOOL absolute;
120 } MouseEvent;
121
122 static MouseEvent event_;
123 static CFDataRef cfEvent_;
124
125 typedef enum {
126 MouseMessageTypeEvent,
127 MouseMessageTypeSetEnabled
128 } MouseMessageType;
129
130 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
131 event_.x = x;
132 event_.y = y;
133 event_.buttons = buttons;
134 event_.absolute = true;
135
136 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
137 }
138
139 static void AshikaseSetEnabled(bool enabled, bool always) {
140 if (!Ashikase(always))
141 return;
142
143 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
144
145 if (enabled)
146 AshikaseSendEvent(x_, y_);
147 }
148
149 MSClassHook(SBAlertItemsController)
150 MSClassHook(SBStatusBarController)
151
152 @class VNCAlertItem;
153 static Class $VNCAlertItem;
154
155 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
156 static NSCondition *condition_;
157 static NSLock *lock_;
158
159 static rfbClientPtr client_;
160
161 static void VNCSetup();
162 static void VNCEnabled();
163
164 @interface VNCBridge : NSObject {
165 }
166
167 + (void) askForConnection;
168 + (void) removeStatusBarItem;
169 + (void) registerClient;
170
171 @end
172
173 @implementation VNCBridge
174
175 + (void) askForConnection {
176 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
177 }
178
179 + (void) removeStatusBarItem {
180 AshikaseSetEnabled(false, false);
181 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
182 }
183
184 + (void) registerClient {
185 // XXX: this could find a better home
186 if (ratio_ == 0) {
187 UIScreen *screen([UIScreen mainScreen]);
188 if ([screen respondsToSelector:@selector(scale)])
189 ratio_ = [screen scale];
190 else
191 ratio_ = 1;
192 }
193
194 ++clients_;
195 AshikaseSetEnabled(true, false);
196 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
197 }
198
199 + (void) performSetup:(NSThread *)thread {
200 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
201 [thread autorelease];
202 VNCSetup();
203 VNCEnabled();
204 [pool release];
205 }
206
207 @end
208
209 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
210 [condition_ lock];
211
212 switch (button) {
213 case 1:
214 action_ = RFB_CLIENT_ACCEPT;
215
216 @synchronized (condition_) {
217 [VNCBridge registerClient];
218 }
219 break;
220
221 case 2:
222 action_ = RFB_CLIENT_REFUSE;
223 break;
224 }
225
226 [condition_ signal];
227 [condition_ unlock];
228 [self dismiss];
229 }
230
231 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
232 UIModalView *sheet([self alertSheet]);
233 [sheet setDelegate:self];
234 [sheet setTitle:@"Remote Access Request"];
235 [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]];
236 [sheet addButtonWithTitle:@"Accept"];
237 [sheet addButtonWithTitle:@"Reject"];
238 }
239
240 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
241 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
242 }
243
244 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
245 static bool PurpleAllocated;
246 static int Level_;
247
248 static void FixRecord(GSEventRecord *record) {
249 if (Level_ < 1)
250 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
251 }
252
253 static void VNCSettings() {
254 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
255
256 @synchronized (lock_) {
257 for (NSValue *handler in handlers_)
258 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
259 [handlers_ removeAllObjects];
260 }
261
262 @synchronized (condition_) {
263 if (screen_ == NULL)
264 return;
265
266 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
267 screen_->authPasswdData = NULL;
268
269 if (settings != nil)
270 if (NSString *password = [settings objectForKey:@"Password"])
271 if ([password length] != 0)
272 screen_->authPasswdData = [password retain];
273
274 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
275 cursor_ = cursor == nil ? true : [cursor boolValue];
276
277 if (clients_ != 0)
278 AshikaseSetEnabled(cursor_, true);
279 }
280 }
281
282 static void VNCNotifySettings(
283 CFNotificationCenterRef center,
284 void *observer,
285 CFStringRef name,
286 const void *object,
287 CFDictionaryRef info
288 ) {
289 VNCSettings();
290 }
291
292 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
293 @synchronized (condition_) {
294 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
295 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
296 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
297 bool good(memcmp(client->authChallenge, data, size) == 0);
298 [pool release];
299 return good;
300 } return TRUE;
301 }
302 }
303
304 static bool iPad1_;
305
306 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
307 if (ratio_ == 0)
308 return;
309
310 CGPoint location = {x, y};
311
312 x /= ratio_;
313 y /= ratio_;
314
315 if (width_ > height_) {
316 int t(x);
317 x = height_ / ratio_ - 1 - y;
318 y = t;
319
320 if (!iPad1_) {
321 x = height_ - x;
322 y = width_ - y;
323 }
324 }
325
326 x_ = x; y_ = y;
327 int diff = buttons_ ^ buttons;
328 bool twas((buttons_ & 0x1) != 0);
329 bool tis((buttons & 0x1) != 0);
330 buttons_ = buttons;
331
332 rfbDefaultPtrAddEvent(buttons, x, y, client);
333
334 if (Ashikase(false)) {
335 AshikaseSendEvent(x, y, buttons);
336 return;
337 }
338
339 mach_port_t purple(0);
340
341 if ((diff & 0x10) != 0) {
342 struct GSEventRecord record;
343
344 memset(&record, 0, sizeof(record));
345
346 record.type = (buttons & 0x4) != 0 ?
347 GSEventTypeHeadsetButtonDown :
348 GSEventTypeHeadsetButtonUp;
349
350 record.timestamp = GSCurrentEventTimestamp();
351
352 FixRecord(&record);
353 GSSendSystemEvent(&record);
354 }
355
356 if ((diff & 0x04) != 0) {
357 struct GSEventRecord record;
358
359 memset(&record, 0, sizeof(record));
360
361 record.type = (buttons & 0x4) != 0 ?
362 GSEventTypeMenuButtonDown :
363 GSEventTypeMenuButtonUp;
364
365 record.timestamp = GSCurrentEventTimestamp();
366
367 FixRecord(&record);
368 GSSendSystemEvent(&record);
369 }
370
371 if ((diff & 0x02) != 0) {
372 struct GSEventRecord record;
373
374 memset(&record, 0, sizeof(record));
375
376 record.type = (buttons & 0x2) != 0 ?
377 GSEventTypeLockButtonDown :
378 GSEventTypeLockButtonUp;
379
380 record.timestamp = GSCurrentEventTimestamp();
381
382 FixRecord(&record);
383 GSSendSystemEvent(&record);
384 }
385
386 if (twas != tis || tis) {
387 struct {
388 struct GSEventRecord record;
389 struct {
390 struct GSEventRecordInfo info;
391 struct GSPathInfo path;
392 } data;
393 } 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 }