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