Fix headset button check, as reported by mringwal.
[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
182 if ($SBStatusBarController != nil)
183 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
184 else
185 [[UIApplication sharedApplication] removeStatusBarImageNamed:@"Veency"];
186 }
187
188 + (void) registerClient {
189 // XXX: this could find a better home
190 if (ratio_ == 0) {
191 UIScreen *screen([UIScreen mainScreen]);
192 if ([screen respondsToSelector:@selector(scale)])
193 ratio_ = [screen scale];
194 else
195 ratio_ = 1;
196 }
197
198 ++clients_;
199 AshikaseSetEnabled(true, false);
200
201 if ($SBStatusBarController != nil)
202 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
203 else
204 [[UIApplication sharedApplication] addStatusBarImageNamed:@"Veency"];
205 }
206
207 + (void) performSetup:(NSThread *)thread {
208 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
209 [thread autorelease];
210 VNCSetup();
211 VNCEnabled();
212 [pool release];
213 }
214
215 @end
216
217 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
218 [condition_ lock];
219
220 switch (button) {
221 case 1:
222 action_ = RFB_CLIENT_ACCEPT;
223
224 @synchronized (condition_) {
225 [VNCBridge registerClient];
226 }
227 break;
228
229 case 2:
230 action_ = RFB_CLIENT_REFUSE;
231 break;
232 }
233
234 [condition_ signal];
235 [condition_ unlock];
236 [self dismiss];
237 }
238
239 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
240 UIModalView *sheet([self alertSheet]);
241 [sheet setDelegate:self];
242 [sheet setTitle:@"Remote Access Request"];
243 [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]];
244 [sheet addButtonWithTitle:@"Accept"];
245 [sheet addButtonWithTitle:@"Reject"];
246 }
247
248 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
249 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
250 }
251
252 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
253 static bool PurpleAllocated;
254 static int Level_;
255
256 static void FixRecord(GSEventRecord *record) {
257 if (Level_ < 1)
258 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
259 }
260
261 static void VNCSettings() {
262 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
263
264 @synchronized (lock_) {
265 for (NSValue *handler in handlers_)
266 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
267 [handlers_ removeAllObjects];
268 }
269
270 @synchronized (condition_) {
271 if (screen_ == NULL)
272 return;
273
274 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
275 screen_->authPasswdData = NULL;
276
277 if (settings != nil)
278 if (NSString *password = [settings objectForKey:@"Password"])
279 if ([password length] != 0)
280 screen_->authPasswdData = [password retain];
281
282 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
283 cursor_ = cursor == nil ? true : [cursor boolValue];
284
285 if (clients_ != 0)
286 AshikaseSetEnabled(cursor_, true);
287 }
288 }
289
290 static void VNCNotifySettings(
291 CFNotificationCenterRef center,
292 void *observer,
293 CFStringRef name,
294 const void *object,
295 CFDictionaryRef info
296 ) {
297 VNCSettings();
298 }
299
300 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
301 @synchronized (condition_) {
302 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
303 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
304 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
305 bool good(memcmp(client->authChallenge, data, size) == 0);
306 [pool release];
307 return good;
308 } return TRUE;
309 }
310 }
311
312 static bool iPad1_;
313
314 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
315 if (ratio_ == 0)
316 return;
317
318 CGPoint location = {x, y};
319
320 if (width_ > height_) {
321 int t(x);
322 x = height_ - 1 - y;
323 y = t;
324
325 if (!iPad1_) {
326 x = height_ - 1 - x;
327 y = width_ - 1 - y;
328 }
329 }
330
331 x /= ratio_;
332 y /= ratio_;
333
334 x_ = x; y_ = y;
335 int diff = buttons_ ^ buttons;
336 bool twas((buttons_ & 0x1) != 0);
337 bool tis((buttons & 0x1) != 0);
338 buttons_ = buttons;
339
340 rfbDefaultPtrAddEvent(buttons, x, y, client);
341
342 if (Ashikase(false)) {
343 AshikaseSendEvent(x, y, buttons);
344 return;
345 }
346
347 mach_port_t purple(0);
348
349 if ((diff & 0x10) != 0) {
350 struct GSEventRecord record;
351
352 memset(&record, 0, sizeof(record));
353
354 record.type = (buttons & 0x10) != 0 ?
355 GSEventTypeHeadsetButtonDown :
356 GSEventTypeHeadsetButtonUp;
357
358 record.timestamp = GSCurrentEventTimestamp();
359
360 FixRecord(&record);
361 GSSendSystemEvent(&record);
362 }
363
364 if ((diff & 0x04) != 0) {
365 struct GSEventRecord record;
366
367 memset(&record, 0, sizeof(record));
368
369 record.type = (buttons & 0x04) != 0 ?
370 GSEventTypeMenuButtonDown :
371 GSEventTypeMenuButtonUp;
372
373 record.timestamp = GSCurrentEventTimestamp();
374
375 FixRecord(&record);
376 GSSendSystemEvent(&record);
377 }
378
379 if ((diff & 0x02) != 0) {
380 struct GSEventRecord record;
381
382 memset(&record, 0, sizeof(record));
383
384 record.type = (buttons & 0x02) != 0 ?
385 GSEventTypeLockButtonDown :
386 GSEventTypeLockButtonUp;
387
388 record.timestamp = GSCurrentEventTimestamp();
389
390 FixRecord(&record);
391 GSSendSystemEvent(&record);
392 }
393
394 if (twas != tis || tis) {
395 struct {
396 struct GSEventRecord record;
397 struct {
398 struct GSEventRecordInfo info;
399 struct GSPathInfo path;
400 } data;
401 } 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 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
803 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
804 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
805 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
806 objc_registerClassPair($VNCAlertItem);
807
808 CFNotificationCenterAddObserver(
809 CFNotificationCenterGetDarwinNotifyCenter(),
810 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
811 );
812
813 CFNotificationCenterAddObserver(
814 CFNotificationCenterGetDarwinNotifyCenter(),
815 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
816 );
817
818 condition_ = [[NSCondition alloc] init];
819 lock_ = [[NSLock alloc] init];
820 handlers_ = [[NSMutableSet alloc] init];
821
822 bool value;
823
824 value = true;
825 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
826
827 value = false;
828 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
829
830 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
831
832 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys:
833 nil] retain];
834
835 [pool release];
836 }