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