]> git.saurik.com Git - veency.git/blob - Tweak.mm
bbe03389fbe885f3854149a98bc180770901c216
[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
571 if (accelerated)
572 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
573
574 if (opengles2 != NULL)
575 CFRelease(opengles2);
576
577 if (accelerator_ != NULL)
578 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
579 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
580 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
581 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
582 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
583 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
584 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
585 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
586 nil]);
587 else
588 VNCBlack();
589
590 //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));
591
592 CoreSurfaceBufferLock(buffer_, 3);
593 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
594 CoreSurfaceBufferUnlock(buffer_);
595
596 screen_->kbdAddEvent = &VNCKeyboard;
597 screen_->ptrAddEvent = &VNCPointer;
598
599 screen_->newClientHook = &VNCClient;
600 screen_->passwordCheck = &VNCCheck;
601
602 screen_->cursor = NULL;
603 }
604
605 static void VNCEnabled() {
606 [lock_ lock];
607
608 bool enabled(true);
609 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
610 if (NSNumber *number = [settings objectForKey:@"Enabled"])
611 enabled = [number boolValue];
612
613 if (enabled != running_)
614 if (enabled) {
615 running_ = true;
616 screen_->socketState = RFB_SOCKET_INIT;
617 rfbInitServer(screen_);
618 rfbRunEventLoop(screen_, -1, true);
619 } else {
620 rfbShutdownServer(screen_, true);
621 running_ = false;
622 }
623
624 [lock_ unlock];
625 }
626
627 static void VNCNotifyEnabled(
628 CFNotificationCenterRef center,
629 void *observer,
630 CFStringRef name,
631 const void *object,
632 CFDictionaryRef info
633 ) {
634 VNCEnabled();
635 }
636
637 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, bool *);
638
639 static IOMobileFramebufferRef main_;
640 static CoreSurfaceBufferRef layer_;
641
642 static void OnLayer(IOMobileFramebufferRef fb, CoreSurfaceBufferRef layer) {
643 if (_unlikely(width_ == 0 || height_ == 0)) {
644 CGSize size;
645 IOMobileFramebufferGetDisplaySize(fb, &size);
646
647 width_ = size.width;
648 height_ = size.height;
649
650 if (width_ == 0 || height_ == 0)
651 return;
652
653 NSThread *thread([NSThread alloc]);
654
655 [thread
656 initWithTarget:[VNCBridge class]
657 selector:@selector(performSetup:)
658 object:thread
659 ];
660
661 [thread start];
662 } else if (_unlikely(clients_ != 0)) {
663 if (layer == NULL) {
664 if (accelerator_ != NULL)
665 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
666 else
667 VNCBlack();
668 } else {
669 if (accelerator_ != NULL)
670 CoreSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, options_);
671 else {
672 CoreSurfaceBufferLock(layer, 2);
673 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(layer)));
674
675 CoreSurfaceBufferFlushProcessorCaches(layer);
676
677 /*rfbPixel corner(data[0]);
678 data[0] = 0;
679 data[0] = corner;*/
680
681 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
682 CoreSurfaceBufferUnlock(layer);
683 }
684 }
685
686 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
687 }
688 }
689
690 static bool wait_ = false;
691
692 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
693 IOMobileFramebufferRef fb,
694 int layer,
695 CoreSurfaceBufferRef buffer,
696 CGRect bounds,
697 CGRect frame,
698 int flags
699 ) {
700 bool main(false);
701
702 if (_unlikely(buffer == NULL))
703 main = fb == main_;
704 else if (_unlikely(fb == NULL))
705 main = false;
706 else if ($IOMobileFramebufferIsMainDisplay == NULL)
707 main = true;
708 else
709 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
710
711 if (_likely(main)) {
712 main_ = fb;
713 if (wait_)
714 layer_ = buffer;
715 else
716 OnLayer(fb, buffer);
717 }
718
719 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
720 }
721
722 // XXX: beg rpetrich for the type of this function
723 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
724
725 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
726 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
727 if (fb == main_)
728 OnLayer(fb, layer_);
729 return value;
730 }
731
732 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
733 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
734
735 @synchronized (lock_) {
736 [handlers_ addObject:[NSValue valueWithPointer:handler]];
737 _rfbRegisterSecurityHandler(handler);
738 }
739
740 [pool release];
741 }
742
743 template <typename Type_>
744 static void dlset(Type_ &function, const char *name) {
745 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
746 }
747
748 MSInitialize {
749 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
750
751 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
752 if (GSTakePurpleSystemEventPort == NULL) {
753 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
754 PurpleAllocated = true;
755 }
756
757 if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
758 Level_ = 2;
759 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
760 Level_ = 1;
761 else
762 Level_ = 0;
763
764 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
765 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
766 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
767
768 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
769 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
770
771 if (wait_)
772 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
773
774 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
775 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
776 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
777 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
778 objc_registerClassPair($VNCAlertItem);
779
780 CFNotificationCenterAddObserver(
781 CFNotificationCenterGetDarwinNotifyCenter(),
782 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
783 );
784
785 CFNotificationCenterAddObserver(
786 CFNotificationCenterGetDarwinNotifyCenter(),
787 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
788 );
789
790 condition_ = [[NSCondition alloc] init];
791 lock_ = [[NSLock alloc] init];
792 handlers_ = [[NSMutableSet alloc] init];
793
794 bool value;
795
796 value = true;
797 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
798
799 value = false;
800 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
801
802 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
803
804 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys:
805 nil] retain];
806
807 [pool release];
808 }