1 /* CydgetScript - open-source IntelliDial replacement
2 * Copyright (C) 2009 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
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
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.
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.
38 #include <substrate.h>
39 #include <sys/sysctl.h>
41 #import <GraphicsServices/GraphicsServices.h>
42 #import <UIKit/UIKit.h>
43 #import <AddressBook/AddressBook.h>
45 #import <SpringBoardUI/SBAwayViewPluginController.h>
46 #import <TelephonyUI/TPBottomLockBar.h>
48 #import <QuartzCore/CALayer.h>
49 // XXX: fix the minimum requirement
50 extern NSString * const kCAFilterNearest;
52 #include <WebKit/DOMCSSPrimitiveValue.h>
53 #include <WebKit/DOMCSSStyleDeclaration.h>
54 #include <WebKit/DOMDocument.h>
55 #include <WebKit/DOMHTMLBodyElement.h>
56 #include <WebKit/DOMNodeList.h>
57 #include <WebKit/DOMRGBColor.h>
59 #include <WebKit/WebFrame.h>
60 #include <WebKit/WebPolicyDelegate.h>
61 #include <WebKit/WebPreferences.h>
62 #include <WebKit/WebScriptObject.h>
64 #import <WebKit/WebView.h>
65 #import <WebKit/WebView-WebPrivate.h>
67 #include <WebCore/Page.h>
68 #include <WebCore/Settings.h>
70 #include <WebCore/WebCoreThread.h>
71 #include <WebKit/WebPreferences-WebPrivate.h>
73 #include "JSGlobalData.h"
74 #include "SourceCode.h"
76 #include <apr-1/apr_pools.h>
79 @interface WebView (UICaboodle)
80 - (void) setScriptDebugDelegate:(id)delegate;
81 - (void) _setFormDelegate:(id)delegate;
82 - (void) _setUIKitDelegate:(id)delegate;
83 - (void) setWebMailDelegate:(id)delegate;
84 - (void) _setLayoutInterval:(float)interval;
88 #define _forever for (;;)
90 _disused static unsigned trace_;
92 #define _trace() do { \
93 NSLog(@"_trace(%u)@%s:%u[%s]\n", \
94 trace_++, __FILE__, __LINE__, __FUNCTION__\
98 #define _assert(test) do \
100 fprintf(stderr, "_assert(%d:%s)@%s:%u[%s]\n", errno, #test, __FILE__, __LINE__, __FUNCTION__); \
105 #define _syscall(expr) \
106 do if ((long) (expr) != -1) \
108 else switch (errno) { \
115 @protocol CydgetController
116 - (NSDictionary *) currentConfiguration;
119 static Class $CydgetController(objc_getClass("CydgetController"));
121 @interface NSString (UIKit)
122 - (NSString *) stringByAddingPercentEscapes;
125 @implementation UIWebDocumentView (WebCycript)
127 - (void) _setScrollerOffset:(CGPoint)offset {
128 UIScroller *scroller([self _scroller]);
130 CGSize size([scroller contentSize]);
131 CGSize bounds([scroller bounds].size);
134 max.x = size.width - bounds.width;
135 max.y = size.height - bounds.height;
143 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
144 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
146 [scroller setOffset:offset];
151 /* Perl-Compatible RegEx {{{ */
161 Pcre(const char *regex, int options = 0) :
166 code_ = pcre_compile(regex, options, &error, &offset, NULL);
169 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"*** Pcre(,): [%u] %s", offset, error] userInfo:nil];
171 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
172 matches_ = new int[(capture_ + 1) * 3];
180 NSString *operator [](size_t match) {
181 return [[[NSString alloc] initWithBytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2]) encoding:NSUTF8StringEncoding] autorelease];
184 bool operator ()(NSString *data) {
185 // XXX: length is for characters, not for bytes
186 return operator ()([data UTF8String], [data length]);
189 bool operator ()(const char *data, size_t size) {
191 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
195 /* WebCycript Delegate {{{ */
196 @interface WebCycriptDelegate : NSObject {
197 _transient volatile id delegate_;
200 - (void) setDelegate:(id)delegate;
201 - (id) initWithDelegate:(id)delegate;
204 @implementation WebCycriptDelegate
206 - (void) setDelegate:(id)delegate {
207 delegate_ = delegate;
210 - (id) initWithDelegate:(id)delegate {
211 delegate_ = delegate;
215 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
216 if (delegate_ != nil)
217 return [delegate_ webView:sender didClearWindowObject:window forFrame:frame];
220 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
221 if (delegate_ != nil)
222 return [delegate_ webView:sender didCommitLoadForFrame:frame];
225 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
226 if (delegate_ != nil)
227 return [delegate_ webView:sender didFailLoadWithError:error forFrame:frame];
230 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
231 if (delegate_ != nil)
232 return [delegate_ webView:sender didFailProvisionalLoadWithError:error forFrame:frame];
235 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
236 if (delegate_ != nil)
237 return [delegate_ webView:sender didFinishLoadForFrame:frame];
240 /*- (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
241 if (delegate_ != nil)
242 return [delegate_ webView:sender didReceiveTitle:title forFrame:frame];
245 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
246 if (delegate_ != nil)
247 return [delegate_ webView:sender didStartProvisionalLoadForFrame:frame];
250 /*- (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
251 if (delegate_ != nil)
252 return [delegate_ webView:sender resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:source];
255 /*- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
256 if (delegate_ != nil)
257 return [delegate_ webView:sender resource:identifier willSendRequest:request redirectResponse:redirectResponse fromDataSource:source];
261 - (IMP) methodForSelector:(SEL)sel {
262 if (IMP method = [super methodForSelector:sel])
264 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
268 - (BOOL) respondsToSelector:(SEL)sel {
269 if ([super respondsToSelector:sel])
271 // XXX: WebThreadCreateNSInvocation returns nil
272 //fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
273 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
276 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
277 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
279 //fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
280 if (delegate_ != nil)
281 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
283 // XXX: I fucking hate Apple so very very bad
284 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
287 - (void) forwardInvocation:(NSInvocation *)inv {
288 SEL sel = [inv selector];
289 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
290 [inv invokeWithTarget:delegate_];
296 @interface WebCydgetLockScreenView : UIView {
297 WebCycriptDelegate *indirect_;
298 UIProgressIndicator *indicator_;
299 UIScroller *scroller_;
300 UIWebDocumentView *document_;
311 NSMutableSet *loading_;
318 @implementation WebCydgetLockScreenView
320 //#include "UICaboodle/UCInternal.h"
325 WebView *webview([document_ webView]);
326 [webview setFrameLoadDelegate:nil];
327 [webview setResourceLoadDelegate:nil];
328 [webview setUIDelegate:nil];
329 [webview setScriptDebugDelegate:nil];
330 [webview setPolicyDelegate:nil];
332 /* XXX: these are set by UIWebDocumentView
333 [webview setDownloadDelegate:nil];
334 [webview _setFormDelegate:nil];
335 [webview _setUIKitDelegate:nil];
336 [webview setEditingDelegate:nil];*/
338 /* XXX: no one sets this, ever
339 [webview setWebMailDelegate:nil];*/
341 [document_ setDelegate:nil];
342 [document_ setGestureDelegate:nil];
343 [document_ setFormEditingDelegate:nil];
344 [document_ setInteractionDelegate:nil];
346 [indirect_ setDelegate:nil];
355 [scroller_ setDelegate:nil];
361 [indicator_ release];
366 + (float) defaultWidth {
370 - (void) _setTileDrawingEnabled:(BOOL)enabled {
371 //[document_ setTileDrawingEnabled:enabled];
374 - (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
375 [self _setTileDrawingEnabled:NO];
378 - (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
379 [self _setTileDrawingEnabled:YES];
380 [document_ redrawScaledDocument];
383 - (void) setViewportWidth:(float)width {
384 width_ = width != 0 ? width : [[self class] defaultWidth];
385 [document_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
388 - (void) scrollerWillStartDragging:(UIScroller *)scroller {
389 [self _setTileDrawingEnabled:NO];
392 - (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
393 [self _setTileDrawingEnabled:YES];
396 - (void) scrollerDidEndDragging:(UIScroller *)scroller {
397 [self _setTileDrawingEnabled:YES];
400 - (void) loadRequest:(NSURLRequest *)request {
404 [document_ loadRequest:request];
408 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
409 [self loadRequest:[NSURLRequest
416 - (void) loadURL:(NSURL *)url {
417 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
421 CGRect frame = {{0, 0}, {320, 480}};
422 frame.size.height -= GSDefaultStatusBarHeight();
424 if ((self = [super initWithFrame:frame]) != nil) {
425 loading_ = [[NSMutableSet alloc] initWithCapacity:3];
427 struct CGRect bounds([self bounds]);
429 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
430 [self addSubview:scroller_];
432 [scroller_ setFixedBackgroundPattern:YES];
433 [scroller_ setBackgroundColor:[UIColor blackColor]];
435 [scroller_ setScrollingEnabled:YES];
436 [scroller_ setClipsSubviews:YES];
437 [scroller_ setAllowsRubberBanding:YES];
439 [scroller_ setDelegate:self];
440 [scroller_ setBounces:YES];
441 [scroller_ setScrollHysteresis:8];
442 [scroller_ setThumbDetectionEnabled:NO];
443 [scroller_ setDirectionalScrolling:YES];
444 [scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
445 [scroller_ setEventMode:YES];
446 [scroller_ setShowBackgroundShadow:NO]; /* YES */
447 [scroller_ setAllowsRubberBanding:YES]; /* Vertical */
448 [scroller_ setAdjustForContentSizeChange:YES]; /* NO */
450 CGRect rect([scroller_ bounds]);
451 //rect.size.height = 0;
455 document_ = [[UIWebDocumentView alloc] initWithFrame:rect];
456 WebView *webview([document_ webView]);
458 [document_ setBackgroundColor:[UIColor blackColor]];
459 if ([document_ respondsToSelector:@selector(setDrawsBackground:)])
460 [document_ setDrawsBackground:NO];
461 [webview setDrawsBackground:NO];
463 [webview setPreferencesIdentifier:@"WebCycript"];
465 [document_ setTileSize:CGSizeMake(rect.size.width, 500)];
467 if ([document_ respondsToSelector:@selector(enableReachability)])
468 [document_ enableReachability];
470 [document_ setAllowsMessaging:YES];
472 if ([document_ respondsToSelector:@selector(useSelectionAssistantWithMode:)])
473 [document_ useSelectionAssistantWithMode:0];
475 [document_ setTilingEnabled:YES];
476 [document_ setDrawsGrid:NO];
477 [document_ setLogsTilingChanges:NO];
478 [document_ setTileMinificationFilter:kCAFilterNearest];
480 if ([document_ respondsToSelector:@selector(setDataDetectorTypes:)])
481 /* XXX: abstractify */
482 [document_ setDataDetectorTypes:0x80000000];
484 [document_ setDetectsPhoneNumbers:NO];
486 [document_ setAutoresizes:YES];
488 [document_ setMinimumScale:0.25f forDocumentTypes:0x10];
489 [document_ setMaximumScale:5.00f forDocumentTypes:0x10];
490 [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
491 //[document_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
493 [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
495 [document_ setMinimumScale:1.00f forDocumentTypes:0x8];
496 [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
497 [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
499 [document_ _setDocumentType:0x4];
501 if ([document_ respondsToSelector:@selector(setZoomsFocusedFormControl:)])
502 [document_ setZoomsFocusedFormControl:YES];
503 [document_ setContentsPosition:7];
504 [document_ setEnabledGestures:0xa];
505 [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
506 [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
508 [document_ setSmoothsFonts:YES];
509 [document_ setAllowsImageSheet:YES];
510 [webview _setUsesLoaderCache:YES];
512 [webview setGroupName:@"CydgetGroup"];
514 WebPreferences *preferences([webview preferences]);
516 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
517 [webview _setLayoutInterval:0];
519 [preferences _setLayoutInterval:0];
521 [self setViewportWidth:0];
523 [document_ setDelegate:self];
524 [document_ setGestureDelegate:self];
525 [document_ setFormEditingDelegate:self];
526 [document_ setInteractionDelegate:self];
528 [scroller_ addSubview:document_];
530 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
532 indirect_ = [[WebCycriptDelegate alloc] initWithDelegate:self];
534 [webview setFrameLoadDelegate:indirect_];
535 [webview setPolicyDelegate:indirect_];
536 [webview setResourceLoadDelegate:indirect_];
537 [webview setUIDelegate:indirect_];
539 /* XXX: do not turn this on under penalty of extreme pain */
540 [webview setScriptDebugDelegate:nil];
544 CGSize indsize([UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite]);
545 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
546 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
548 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
549 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
551 NSDictionary *configuration([$CydgetController currentConfiguration]);
553 cycript_ = [configuration objectForKey:@"CycriptURLs"];
555 scrollable_ = [[configuration objectForKey:@"Scrollable"] boolValue];
556 [scroller_ setScrollingEnabled:scrollable_];
558 NSString *homepage([configuration objectForKey:@"Homepage"]);
559 [self loadURL:[NSURL URLWithString:homepage]];
563 - (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
566 UIActionSheet *sheet = [[[UIActionSheet alloc]
568 buttons:[NSArray arrayWithObjects:@"OK", nil]
574 [sheet setBodyText:message];
575 [sheet popupAlertAnimated:YES];
578 - (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
581 UIActionSheet *sheet = [[[UIActionSheet alloc]
583 buttons:[NSArray arrayWithObjects:@"OK", @"CANCEL", nil]
589 [sheet setNumberOfRows:1];
590 [sheet setBodyText:message];
591 [sheet popupAlertAnimated:YES];
593 NSRunLoop *loop([NSRunLoop currentRunLoop]);
594 NSDate *future([NSDate distantFuture]);
596 while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
598 NSNumber *confirm([confirm_ autorelease]);
602 return [confirm boolValue];
605 /* XXX: WebThreadLock? */
606 - (void) _fixScroller:(CGRect)bounds {
611 UIFormAssistant *assistant([UIFormAssistant sharedFormAssistant]);
612 CGRect peripheral([assistant peripheralFrame]);
613 extra = peripheral.size.height;
616 CGRect subrect([scroller_ frame]);
617 subrect.size.height -= [TPBottomLockBar defaultHeight];
618 subrect.size.height -= extra;
619 [scroller_ setScrollerIndicatorSubrect:subrect];
622 NSSize visible(NSMakeSize(subrect.size.width, subrect.size.height));
623 [document_ setValue:[NSValue valueWithSize:visible] forGestureAttribute:UIGestureAttributeVisibleSize];
626 size.height += extra;
627 size.height += [TPBottomLockBar defaultHeight];
628 [scroller_ setContentSize:size];
630 [scroller_ releaseRubberBandIfNecessary];
633 - (void) fixScroller {
634 CGRect bounds([document_ documentBounds]);
635 [self _fixScroller:bounds];
638 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
640 [self _fixScroller:frame];
643 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
644 [self view:sender didSetFrame:frame];
647 - (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
651 - (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
655 - (void) webViewDidEndEditingFormElements:(WebView *)sender {
660 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
662 if (NSString *href = [[[[frame dataSource] request] URL] absoluteString])
663 if (Pcre([cycript_ UTF8String], 0 /*XXX:PCRE_UTF8*/)(href))
664 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
665 if (void (*CYSetupContext)(JSGlobalContextRef) = reinterpret_cast<void (*)(JSGlobalContextRef)>(dlsym(handle, "CydgetSetupContext"))) {
666 WebView *webview([document_ webView]);
667 WebFrame *frame([webview mainFrame]);
668 JSGlobalContextRef context([frame globalContext]);
669 CYSetupContext(context);
674 return [loading_ count] != 0;
677 - (void) reloadButtons {
678 if ([self isLoading]) {
679 [UIApp setNetworkActivityIndicatorVisible:YES];
680 [indicator_ startAnimation];
682 [UIApp setNetworkActivityIndicatorVisible:NO];
683 [indicator_ stopAnimation];
687 - (void) _finishLoading {
688 size_t count([loading_ count]);
690 [self autorelease];*/
691 if (reloading_ || count != 0)
693 [self reloadButtons];
696 - (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
697 return [document_ webView:sender shouldScrollToPoint:point forFrame:frame];
700 - (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
701 return [document_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
704 - (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
705 return [document_ webView:sender needsScrollNotifications:notifications forFrame:frame];
708 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
709 return [document_ webView:sender didCommitLoadForFrame:frame];
712 - (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
713 return [document_ webView:sender didReceiveDocTypeForFrame:frame];
716 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
717 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
718 [self _finishLoading];
719 return [document_ webView:sender didFinishLoadForFrame:frame];
722 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
723 /*if ([loading_ count] == 0)
725 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
727 if ([frame parentFrame] == nil) {
728 [document_ resignFirstResponder];
732 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
734 if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
735 [scroller_ setZoomScale:1 duration:0];
736 else if ([scroller_ respondsToSelector:@selector(_setZoomScale:duration:)])
737 [scroller_ _setZoomScale:1 duration:0];
738 /*else if ([scroller_ respondsToSelector:@selector(setZoomScale:animated:)])
739 [scroller_ setZoomScale:1 animated:NO];*/
741 CGRect rect([scroller_ bounds]);
742 //rect.size.height = 0;
743 [document_ setFrame:rect];
746 [self reloadButtons];
749 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
750 /*if ([frame parentFrame] == nil)
751 [self autorelease];*/
753 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
754 [self _finishLoading];
759 if ([frame parentFrame] == nil) {
760 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
761 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
762 [[error localizedDescription] stringByAddingPercentEscapes]
769 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
770 [self _didFailWithError:error forFrame:frame];
773 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
774 [self _didFailWithError:error forFrame:frame];
777 - (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
778 fprintf(stderr, "Console:%s\n", [[dictionary description] UTF8String]);
783 @interface WebCycriptLockScreenController : SBAwayViewPluginController {
790 static bool cycript_;
791 static bool jscript_;
793 static void SetParser(bool cycript, bool jscript) {
798 static bool GetParser0() {
802 static bool GetParser1() {
806 static void Cycriptify(apr_pool_t *pool, const uint16_t *&data, size_t &size) {
807 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
808 if (void (*CYParseUChar)(apr_pool_t *, const uint16_t **, size_t *) = reinterpret_cast<void (*)(apr_pool_t *, const uint16_t **, size_t *)>(dlsym(handle, "CydgetPoolParse")))
809 CYParseUChar(pool, &data, &size);
812 extern "C" void *_ZN3JSC7UString3Rep14nullBaseStringE __attribute__((__weak_import__));
813 extern "C" void *_ZN3JSC7UString3Rep7destroyEv __attribute__((__weak_import__));
814 extern "C" void *_ZN3JSC7UStringC1EPKti __attribute__((__weak_import__));
815 extern "C" void *_ZN3JSC7UStringC1EPKc __attribute__((__weak_import__));
816 extern "C" void *_ZNK3JSC7UString6substrEii __attribute__((__weak_import__));
817 extern "C" void *_ZN3WTF10fastMallocEm __attribute__((__weak_import__));
818 extern "C" void WTFReportAssertionFailure(const char *, int, const char *, const char *) __attribute__((__weak_import__));
819 extern "C" void *_ZN3WTF8fastFreeEPv __attribute__((__weak_import__));
823 &_ZN3JSC7UString3Rep14nullBaseStringE == NULL ||
824 &_ZN3JSC7UString3Rep7destroyEv == NULL ||
825 &_ZN3JSC7UStringC1EPKti == NULL ||
826 &_ZN3JSC7UStringC1EPKc == NULL ||
827 &_ZNK3JSC7UString6substrEii == NULL ||
828 &_ZN3WTF10fastMallocEm == NULL ||
829 &WTFReportAssertionFailure == NULL ||
830 &_ZN3WTF8fastFreeEPv == NULL ||
834 MSHook(void, _ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, JSC::SourceCode **_this, JSC::JSGlobalData *global, int *line, JSC::UString *message) {
836 return __ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE(_this, global, line, message);
838 SetParser(false, true);
840 JSC::SourceCode *source(*_this);
841 const uint16_t *data(source->data());
842 size_t size(source->length());
845 apr_pool_create(&pool, NULL);
847 Cycriptify(pool, data, size);
848 source->~SourceCode();
849 new (source) JSC::SourceCode(JSC::UStringSourceProvider::create(JSC::UString(data, size), "cycript://"), 1);
851 apr_pool_destroy(pool);
853 __ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE(_this, global, line, message);
857 MSHook(void, _ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE, void *_this, int start, const UChar *code, unsigned length, int *source, int *line, JSC::UString *message) {
859 return __ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE(_this, start, code, length, source, line, message);
861 const uint16_t *data(code);
865 apr_pool_create(&pool, NULL);
867 Cycriptify(pool, data, size);
868 __ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE(_this, start, data, size, source, line, message);
870 apr_pool_destroy(pool);
878 MSHook(State, _ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE, State state) {
879 SetParser(false, true);
880 state = __ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE(state);
881 SetParser(false, false);
885 MSHook(void, _ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE, void *resource) {
886 SetParser(false, true);
887 __ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE(resource);
888 SetParser(false, false);
891 MSHook(bool, _ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, const WebCore::String &mime) {
892 if (!GetParser1() || mime != "text/cycript")
893 return __ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE(mime);
895 static void *handle(dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL));
899 SetParser(true, true);
903 /* Cydget:// Protocol {{{ */
904 @interface CydgetURLProtocol : NSURLProtocol {
909 @implementation CydgetURLProtocol
911 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
912 NSURL *url([request URL]);
915 NSString *scheme([[url scheme] lowercaseString]);
916 if (scheme == nil || ![scheme isEqualToString:@"cydget"])
921 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
925 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
926 id<NSURLProtocolClient> client([self client]);
928 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
930 NSData *data(UIImagePNGRepresentation(icon));
932 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
933 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
934 [client URLProtocol:self didLoadData:data];
935 [client URLProtocolDidFinishLoading:self];
939 - (void) startLoading {
940 id<NSURLProtocolClient> client([self client]);
941 NSURLRequest *request([self request]);
943 NSURL *url([request URL]);
944 NSString *href([url absoluteString]);
946 NSString *path([href substringFromIndex:9]);
947 NSRange slash([path rangeOfString:@"/"]);
950 if (slash.location == NSNotFound) {
954 command = [path substringToIndex:slash.location];
955 path = [path substringFromIndex:(slash.location + 1)];
958 if ([command isEqualToString:@"_UIImageWithName"]) {
961 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
962 UIImage *icon(_UIImageWithName(path));
963 [self _returnPNGWithImage:icon forRequest:request];
965 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
969 - (void) stopLoading {
974 /* Cydget-PHP:// Protocol {{{ */
975 @interface CydgetPHPURLProtocol : NSURLProtocol {
977 CFHTTPMessageRef http_;
982 @implementation CydgetPHPURLProtocol
984 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
985 NSURL *url([request URL]);
988 NSString *scheme([[url scheme] lowercaseString]);
989 if (scheme == nil || ![scheme isEqualToString:@"cydget-php"])
994 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
998 - (id) initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)response client:(id<NSURLProtocolClient>)client {
999 if ((self = [super initWithRequest:request cachedResponse:response client:client]) != nil) {
1004 - (void) startLoading {
1005 id<NSURLProtocolClient> client([self client]);
1006 NSURLRequest *request([self request]);
1007 NSURL *url([request URL]);
1009 NSString *path([url path]);
1010 if (path == nil || ![path hasSuffix:@".php"]) {
1011 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
1015 NSFileManager *manager([NSFileManager defaultManager]);
1016 if (![manager fileExistsAtPath:path]) {
1017 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
1022 _assert(pipe(fds) != -1);
1024 _assert(pid_ == -1);
1027 _assert(close(fds[0]) != -1);
1028 _assert(close(fds[1]) != -1);
1029 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
1034 setenv("GATEWAY_INTERFACE", "CGI/1.1", true);
1035 setenv("SCRIPT_FILENAME", [path UTF8String], true);
1036 NSString *query([url query]);
1038 setenv("QUERY_STRING", [query UTF8String], true);
1040 _assert(dup2(fds[1], 1) != -1);
1041 _assert(close(fds[0]) != -1);
1042 _assert(close(fds[1]) != -1);
1044 execl("/usr/bin/php-cgi", "php-cgi", NULL);
1049 _assert(close(fds[1]) != -1);
1051 _assert(http_ == NULL);
1052 http_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE);
1053 CFHTTPMessageAppendBytes(http_, (const uint8_t *) "HTTP/1.1 200 OK\r\n", 17);
1055 NSFileHandle *handle([[NSFileHandle alloc] initWithFileDescriptor:fds[0] closeOnDealloc:YES]);
1057 [[NSNotificationCenter defaultCenter]
1059 selector:@selector(onRead:)
1060 name:@"NSFileHandleReadCompletionNotification"
1064 [handle readInBackgroundAndNotify];
1069 - (void) onRead:(NSNotification *)notification {
1070 NSFileHandle *handle([notification object]);
1072 NSData *data([[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]);
1074 if (size_t length = [data length]) {
1075 CFHTTPMessageAppendBytes(http_, reinterpret_cast<const UInt8 *>([data bytes]), length);
1076 [handle readInBackgroundAndNotify];
1078 id<NSURLProtocolClient> client([self client]);
1080 CFStringRef mime(CFHTTPMessageCopyHeaderFieldValue(http_, CFSTR("Content-type")));
1082 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:nil]];
1084 NSURLRequest *request([self request]);
1086 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:(NSString *)mime expectedContentLength:-1 textEncodingName:nil] autorelease]);
1089 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1091 CFDataRef body(CFHTTPMessageCopyBody(http_));
1092 [client URLProtocol:self didLoadData:(NSData *)body];
1095 [client URLProtocolDidFinishLoading:self];
1103 //[client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorNetworkConnectionLost userInfo:nil]];
1105 - (void) stopLoading {
1107 kill(pid_, SIGTERM);
1109 _syscall(waitpid(pid_, &status, 0));
1117 template <typename Type_>
1118 static void nlset(Type_ &function, struct nlist *nl, size_t index) {
1119 struct nlist &name(nl[index]);
1120 uintptr_t value(name.n_value);
1121 if ((name.n_desc & N_ARM_THUMB_DEF) != 0)
1122 value |= 0x00000001;
1123 function = reinterpret_cast<Type_>(value);
1126 template <typename Type_>
1127 static void dlset(Type_ &function, const char *name) {
1128 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1131 @implementation WebCycriptLockScreenController
1133 + (void) initialize {
1135 size_t size(sizeof(maxproc));
1136 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
1137 NSLog(@"sysctlbyname(\"kern.maxproc\", ?)");
1138 else if (maxproc < 72) {
1140 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
1141 NSLog(@"sysctlbyname(\"kern.maxproc\", #)");
1146 [NSURLProtocol registerClass:[CydgetURLProtocol class]];
1147 [NSURLProtocol registerClass:[CydgetPHPURLProtocol class]];
1149 void (*_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE)(JSC::SourceCode **, JSC::JSGlobalData *, int *, JSC::UString *);
1150 dlset(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, "_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE");
1151 if (_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE != NULL)
1152 MSHookFunction(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, MSHake(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE));
1154 void (*_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE)(void *, int, const UChar *, unsigned, int *, int *, JSC::UString *);
1155 dlset(_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE, "_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE");
1156 if (_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE != NULL)
1157 MSHookFunction(_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE, MSHake(_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE));
1160 memset(nl, 0, sizeof(nl));
1161 nl[0].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE";
1162 nl[1].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE";
1163 nl[2].n_un.n_name = (char *) "__ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE";
1164 nlist("/System/Library/PrivateFrameworks/WebCore.framework/WebCore", nl);
1166 State (*_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE)(State);
1167 nlset(_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE, nl, 0);
1168 MSHookFunction(_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE, MSHake(_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE));
1170 void (*_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE)(void *);
1171 nlset(_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE, nl, 1);
1172 MSHookFunction(_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE, MSHake(_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE));
1174 bool (*_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE)(const WebCore::String &);
1175 nlset(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, nl, 2);
1176 MSHookFunction(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, MSHake(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE));
1179 + (id) rootViewController {
1180 return [[[self alloc] init] autorelease];
1184 [self setView:[[[WebCydgetLockScreenView alloc] init] autorelease]];