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>
40 #import <GraphicsServices/GraphicsServices.h>
41 #import <UIKit/UIKit.h>
42 #import <AddressBook/AddressBook.h>
44 #import <SpringBoardUI/SBAwayViewPluginController.h>
45 #import <TelephonyUI/TPBottomLockBar.h>
47 #import <QuartzCore/CALayer.h>
48 // XXX: fix the minimum requirement
49 extern NSString * const kCAFilterNearest;
51 #include <WebKit/DOMCSSPrimitiveValue.h>
52 #include <WebKit/DOMCSSStyleDeclaration.h>
53 #include <WebKit/DOMDocument.h>
54 #include <WebKit/DOMHTMLBodyElement.h>
55 #include <WebKit/DOMNodeList.h>
56 #include <WebKit/DOMRGBColor.h>
58 #include <WebKit/WebFrame.h>
59 #include <WebKit/WebPolicyDelegate.h>
60 #include <WebKit/WebPreferences.h>
61 #include <WebKit/WebScriptObject.h>
63 #import <WebKit/WebView.h>
64 #import <WebKit/WebView-WebPrivate.h>
66 #include <WebCore/Page.h>
67 #include <WebCore/Settings.h>
69 #include <WebCore/WebCoreThread.h>
70 #include <WebKit/WebPreferences-WebPrivate.h>
72 #include "JSGlobalData.h"
73 #include "SourceCode.h"
75 #include <apr-1/apr_pools.h>
78 @interface WebView (UICaboodle)
79 - (void) setScriptDebugDelegate:(id)delegate;
80 - (void) _setFormDelegate:(id)delegate;
81 - (void) _setUIKitDelegate:(id)delegate;
82 - (void) setWebMailDelegate:(id)delegate;
83 - (void) _setLayoutInterval:(float)interval;
87 #define _forever for (;;)
89 _disused static unsigned trace_;
91 #define _trace() do { \
92 NSLog(@"_trace(%u)@%s:%u[%s]\n", \
93 trace_++, __FILE__, __LINE__, __FUNCTION__\
97 #define _assert(test) do \
99 fprintf(stderr, "_assert(%d:%s)@%s:%u[%s]\n", errno, #test, __FILE__, __LINE__, __FUNCTION__); \
104 @protocol CydgetController
105 - (NSDictionary *) currentConfiguration;
108 static Class $CydgetController(objc_getClass("CydgetController"));
110 @interface NSString (UIKit)
111 - (NSString *) stringByAddingPercentEscapes;
114 @implementation UIWebDocumentView (WebCycript)
116 - (void) _setScrollerOffset:(CGPoint)offset {
117 UIScroller *scroller([self _scroller]);
119 CGSize size([scroller contentSize]);
120 CGSize bounds([scroller bounds].size);
123 max.x = size.width - bounds.width;
124 max.y = size.height - bounds.height;
132 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
133 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
135 [scroller setOffset:offset];
140 /* Perl-Compatible RegEx {{{ */
150 Pcre(const char *regex, int options = 0) :
155 code_ = pcre_compile(regex, options, &error, &offset, NULL);
158 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"*** Pcre(,): [%u] %s", offset, error] userInfo:nil];
160 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
161 matches_ = new int[(capture_ + 1) * 3];
169 NSString *operator [](size_t match) {
170 return [[[NSString alloc] initWithBytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2]) encoding:NSUTF8StringEncoding] autorelease];
173 bool operator ()(NSString *data) {
174 // XXX: length is for characters, not for bytes
175 return operator ()([data UTF8String], [data length]);
178 bool operator ()(const char *data, size_t size) {
180 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
184 /* WebCycript Delegate {{{ */
185 @interface WebCycriptDelegate : NSObject {
186 _transient volatile id delegate_;
189 - (void) setDelegate:(id)delegate;
190 - (id) initWithDelegate:(id)delegate;
193 @implementation WebCycriptDelegate
195 - (void) setDelegate:(id)delegate {
196 delegate_ = delegate;
199 - (id) initWithDelegate:(id)delegate {
200 delegate_ = delegate;
204 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
205 if (delegate_ != nil)
206 return [delegate_ webView:sender didClearWindowObject:window forFrame:frame];
209 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
210 if (delegate_ != nil)
211 return [delegate_ webView:sender didCommitLoadForFrame:frame];
214 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
215 if (delegate_ != nil)
216 return [delegate_ webView:sender didFailLoadWithError:error forFrame:frame];
219 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
220 if (delegate_ != nil)
221 return [delegate_ webView:sender didFailProvisionalLoadWithError:error forFrame:frame];
224 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
225 if (delegate_ != nil)
226 return [delegate_ webView:sender didFinishLoadForFrame:frame];
229 /*- (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
230 if (delegate_ != nil)
231 return [delegate_ webView:sender didReceiveTitle:title forFrame:frame];
234 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
235 if (delegate_ != nil)
236 return [delegate_ webView:sender didStartProvisionalLoadForFrame:frame];
239 /*- (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
240 if (delegate_ != nil)
241 return [delegate_ webView:sender resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:source];
244 /*- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
245 if (delegate_ != nil)
246 return [delegate_ webView:sender resource:identifier willSendRequest:request redirectResponse:redirectResponse fromDataSource:source];
250 - (IMP) methodForSelector:(SEL)sel {
251 if (IMP method = [super methodForSelector:sel])
253 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
257 - (BOOL) respondsToSelector:(SEL)sel {
258 if ([super respondsToSelector:sel])
260 // XXX: WebThreadCreateNSInvocation returns nil
261 //fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
262 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
265 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
266 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
268 //fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
269 if (delegate_ != nil)
270 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
272 // XXX: I fucking hate Apple so very very bad
273 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
276 - (void) forwardInvocation:(NSInvocation *)inv {
277 SEL sel = [inv selector];
278 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
279 [inv invokeWithTarget:delegate_];
285 @interface WebCydgetLockScreenView : UIView {
286 WebCycriptDelegate *indirect_;
287 UIProgressIndicator *indicator_;
288 UIScroller *scroller_;
289 UIWebDocumentView *document_;
300 NSMutableSet *loading_;
307 @implementation WebCydgetLockScreenView
309 //#include "UICaboodle/UCInternal.h"
314 WebView *webview([document_ webView]);
315 [webview setFrameLoadDelegate:nil];
316 [webview setResourceLoadDelegate:nil];
317 [webview setUIDelegate:nil];
318 [webview setScriptDebugDelegate:nil];
319 [webview setPolicyDelegate:nil];
321 /* XXX: these are set by UIWebDocumentView
322 [webview setDownloadDelegate:nil];
323 [webview _setFormDelegate:nil];
324 [webview _setUIKitDelegate:nil];
325 [webview setEditingDelegate:nil];*/
327 /* XXX: no one sets this, ever
328 [webview setWebMailDelegate:nil];*/
330 [document_ setDelegate:nil];
331 [document_ setGestureDelegate:nil];
332 [document_ setFormEditingDelegate:nil];
333 [document_ setInteractionDelegate:nil];
335 [indirect_ setDelegate:nil];
344 [scroller_ setDelegate:nil];
350 [indicator_ release];
355 + (float) defaultWidth {
359 - (void) _setTileDrawingEnabled:(BOOL)enabled {
360 //[document_ setTileDrawingEnabled:enabled];
363 - (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
364 [self _setTileDrawingEnabled:NO];
367 - (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
368 [self _setTileDrawingEnabled:YES];
369 [document_ redrawScaledDocument];
372 - (void) setViewportWidth:(float)width {
373 width_ = width != 0 ? width : [[self class] defaultWidth];
374 [document_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
377 - (void) scrollerWillStartDragging:(UIScroller *)scroller {
378 [self _setTileDrawingEnabled:NO];
381 - (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
382 [self _setTileDrawingEnabled:YES];
385 - (void) scrollerDidEndDragging:(UIScroller *)scroller {
386 [self _setTileDrawingEnabled:YES];
389 - (void) loadRequest:(NSURLRequest *)request {
393 [document_ loadRequest:request];
397 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
398 [self loadRequest:[NSURLRequest
405 - (void) loadURL:(NSURL *)url {
406 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
410 CGRect frame = {{0, 0}, {320, 480}};
411 frame.size.height -= GSDefaultStatusBarHeight();
413 if ((self = [super initWithFrame:frame]) != nil) {
414 loading_ = [[NSMutableSet alloc] initWithCapacity:3];
416 struct CGRect bounds([self bounds]);
418 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
419 [self addSubview:scroller_];
421 [scroller_ setFixedBackgroundPattern:YES];
422 [scroller_ setBackgroundColor:[UIColor blackColor]];
424 [scroller_ setScrollingEnabled:YES];
425 [scroller_ setClipsSubviews:YES];
426 [scroller_ setAllowsRubberBanding:YES];
428 [scroller_ setDelegate:self];
429 [scroller_ setBounces:YES];
430 [scroller_ setScrollHysteresis:8];
431 [scroller_ setThumbDetectionEnabled:NO];
432 [scroller_ setDirectionalScrolling:YES];
433 [scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
434 [scroller_ setEventMode:YES];
435 [scroller_ setShowBackgroundShadow:NO]; /* YES */
436 [scroller_ setAllowsRubberBanding:YES]; /* Vertical */
437 [scroller_ setAdjustForContentSizeChange:YES]; /* NO */
439 CGRect rect([scroller_ bounds]);
440 //rect.size.height = 0;
444 document_ = [[UIWebDocumentView alloc] initWithFrame:rect];
445 WebView *webview([document_ webView]);
447 [document_ setBackgroundColor:[UIColor blackColor]];
448 if ([document_ respondsToSelector:@selector(setDrawsBackground:)])
449 [document_ setDrawsBackground:NO];
450 [webview setDrawsBackground:NO];
452 [webview setPreferencesIdentifier:@"WebCycript"];
454 [document_ setTileSize:CGSizeMake(rect.size.width, 500)];
456 if ([document_ respondsToSelector:@selector(enableReachability)])
457 [document_ enableReachability];
459 [document_ setAllowsMessaging:YES];
461 if ([document_ respondsToSelector:@selector(useSelectionAssistantWithMode:)])
462 [document_ useSelectionAssistantWithMode:0];
464 [document_ setTilingEnabled:YES];
465 [document_ setDrawsGrid:NO];
466 [document_ setLogsTilingChanges:NO];
467 [document_ setTileMinificationFilter:kCAFilterNearest];
469 if ([document_ respondsToSelector:@selector(setDataDetectorTypes:)])
470 /* XXX: abstractify */
471 [document_ setDataDetectorTypes:0x80000000];
473 [document_ setDetectsPhoneNumbers:NO];
475 [document_ setAutoresizes:YES];
477 [document_ setMinimumScale:0.25f forDocumentTypes:0x10];
478 [document_ setMaximumScale:5.00f forDocumentTypes:0x10];
479 [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
480 //[document_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
482 [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
484 [document_ setMinimumScale:1.00f forDocumentTypes:0x8];
485 [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
486 [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
488 [document_ _setDocumentType:0x4];
490 if ([document_ respondsToSelector:@selector(setZoomsFocusedFormControl:)])
491 [document_ setZoomsFocusedFormControl:YES];
492 [document_ setContentsPosition:7];
493 [document_ setEnabledGestures:0xa];
494 [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
495 [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
497 [document_ setSmoothsFonts:YES];
498 [document_ setAllowsImageSheet:YES];
499 [webview _setUsesLoaderCache:YES];
501 [webview setGroupName:@"CydgetGroup"];
503 WebPreferences *preferences([webview preferences]);
505 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
506 [webview _setLayoutInterval:0];
508 [preferences _setLayoutInterval:0];
510 [self setViewportWidth:0];
512 [document_ setDelegate:self];
513 [document_ setGestureDelegate:self];
514 [document_ setFormEditingDelegate:self];
515 [document_ setInteractionDelegate:self];
517 [scroller_ addSubview:document_];
519 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
521 indirect_ = [[WebCycriptDelegate alloc] initWithDelegate:self];
523 [webview setFrameLoadDelegate:indirect_];
524 [webview setPolicyDelegate:indirect_];
525 [webview setResourceLoadDelegate:indirect_];
526 [webview setUIDelegate:indirect_];
528 /* XXX: do not turn this on under penalty of extreme pain */
529 [webview setScriptDebugDelegate:nil];
533 CGSize indsize([UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite]);
534 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
535 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
537 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
538 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
540 NSDictionary *configuration([$CydgetController currentConfiguration]);
542 cycript_ = [configuration objectForKey:@"CycriptURLs"];
544 scrollable_ = [[configuration objectForKey:@"Scrollable"] boolValue];
545 [scroller_ setScrollingEnabled:scrollable_];
547 NSString *homepage([configuration objectForKey:@"Homepage"]);
548 [self loadURL:[NSURL URLWithString:homepage]];
552 - (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
555 UIActionSheet *sheet = [[[UIActionSheet alloc]
557 buttons:[NSArray arrayWithObjects:@"OK", nil]
563 [sheet setBodyText:message];
564 [sheet popupAlertAnimated:YES];
567 - (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
570 UIActionSheet *sheet = [[[UIActionSheet alloc]
572 buttons:[NSArray arrayWithObjects:@"OK", @"CANCEL", nil]
578 [sheet setNumberOfRows:1];
579 [sheet setBodyText:message];
580 [sheet popupAlertAnimated:YES];
582 NSRunLoop *loop([NSRunLoop currentRunLoop]);
583 NSDate *future([NSDate distantFuture]);
585 while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
587 NSNumber *confirm([confirm_ autorelease]);
591 return [confirm boolValue];
594 /* XXX: WebThreadLock? */
595 - (void) _fixScroller:(CGRect)bounds {
600 UIFormAssistant *assistant([UIFormAssistant sharedFormAssistant]);
601 CGRect peripheral([assistant peripheralFrame]);
602 extra = peripheral.size.height;
605 CGRect subrect([scroller_ frame]);
606 subrect.size.height -= [TPBottomLockBar defaultHeight];
607 subrect.size.height -= extra;
608 [scroller_ setScrollerIndicatorSubrect:subrect];
611 NSSize visible(NSMakeSize(subrect.size.width, subrect.size.height));
612 [document_ setValue:[NSValue valueWithSize:visible] forGestureAttribute:UIGestureAttributeVisibleSize];
615 size.height += extra;
616 size.height += [TPBottomLockBar defaultHeight];
617 [scroller_ setContentSize:size];
619 [scroller_ releaseRubberBandIfNecessary];
622 - (void) fixScroller {
623 CGRect bounds([document_ documentBounds]);
624 [self _fixScroller:bounds];
627 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
629 [self _fixScroller:frame];
632 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
633 [self view:sender didSetFrame:frame];
636 - (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
640 - (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
644 - (void) webViewDidEndEditingFormElements:(WebView *)sender {
649 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
651 if (NSString *href = [[[[frame dataSource] request] URL] absoluteString])
652 if (Pcre([cycript_ UTF8String], 0 /*XXX:PCRE_UTF8*/)(href))
653 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
654 if (void (*CYSetupContext)(JSGlobalContextRef) = reinterpret_cast<void (*)(JSGlobalContextRef)>(dlsym(handle, "CydgetSetupContext"))) {
655 WebView *webview([document_ webView]);
656 WebFrame *frame([webview mainFrame]);
657 JSGlobalContextRef context([frame globalContext]);
658 CYSetupContext(context);
663 return [loading_ count] != 0;
666 - (void) reloadButtons {
667 if ([self isLoading]) {
668 [UIApp setNetworkActivityIndicatorVisible:YES];
669 [indicator_ startAnimation];
671 [UIApp setNetworkActivityIndicatorVisible:NO];
672 [indicator_ stopAnimation];
676 - (void) _finishLoading {
677 size_t count([loading_ count]);
679 [self autorelease];*/
680 if (reloading_ || count != 0)
682 [self reloadButtons];
685 - (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
686 return [document_ webView:sender shouldScrollToPoint:point forFrame:frame];
689 - (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
690 return [document_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
693 - (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
694 return [document_ webView:sender needsScrollNotifications:notifications forFrame:frame];
697 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
698 return [document_ webView:sender didCommitLoadForFrame:frame];
701 - (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
702 return [document_ webView:sender didReceiveDocTypeForFrame:frame];
705 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
706 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
707 [self _finishLoading];
708 return [document_ webView:sender didFinishLoadForFrame:frame];
711 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
712 /*if ([loading_ count] == 0)
714 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
716 if ([frame parentFrame] == nil) {
717 [document_ resignFirstResponder];
721 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
723 if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
724 [scroller_ setZoomScale:1 duration:0];
725 else if ([scroller_ respondsToSelector:@selector(_setZoomScale:duration:)])
726 [scroller_ _setZoomScale:1 duration:0];
727 /*else if ([scroller_ respondsToSelector:@selector(setZoomScale:animated:)])
728 [scroller_ setZoomScale:1 animated:NO];*/
730 CGRect rect([scroller_ bounds]);
731 //rect.size.height = 0;
732 [document_ setFrame:rect];
735 [self reloadButtons];
738 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
739 /*if ([frame parentFrame] == nil)
740 [self autorelease];*/
742 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
743 [self _finishLoading];
748 if ([frame parentFrame] == nil) {
749 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
750 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
751 [[error localizedDescription] stringByAddingPercentEscapes]
758 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
759 [self _didFailWithError:error forFrame:frame];
762 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
763 [self _didFailWithError:error forFrame:frame];
766 - (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
767 fprintf(stderr, "Console:%s\n", [[dictionary description] UTF8String]);
772 @interface WebCycriptLockScreenController : SBAwayViewPluginController {
779 static bool cycript_;
780 static bool jscript_;
782 static void SetParser(bool cycript, bool jscript) {
787 static bool GetParser0() {
791 static bool GetParser1() {
795 static void Cycriptify(apr_pool_t *pool, const uint16_t *&data, size_t &size) {
796 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
797 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")))
798 CYParseUChar(pool, &data, &size);
801 extern "C" void *_ZN3JSC7UString3Rep14nullBaseStringE __attribute__((__weak_import__));
802 extern "C" void *_ZN3JSC7UString3Rep7destroyEv __attribute__((__weak_import__));
803 extern "C" void *_ZN3JSC7UStringC1EPKti __attribute__((__weak_import__));
804 extern "C" void *_ZN3JSC7UStringC1EPKc __attribute__((__weak_import__));
805 extern "C" void *_ZNK3JSC7UString6substrEii __attribute__((__weak_import__));
806 extern "C" void *_ZN3WTF10fastMallocEm __attribute__((__weak_import__));
807 extern "C" void WTFReportAssertionFailure(const char *, int, const char *, const char *) __attribute__((__weak_import__));
808 extern "C" void *_ZN3WTF8fastFreeEPv __attribute__((__weak_import__));
812 &_ZN3JSC7UString3Rep14nullBaseStringE == NULL ||
813 &_ZN3JSC7UString3Rep7destroyEv == NULL ||
814 &_ZN3JSC7UStringC1EPKti == NULL ||
815 &_ZN3JSC7UStringC1EPKc == NULL ||
816 &_ZNK3JSC7UString6substrEii == NULL ||
817 &_ZN3WTF10fastMallocEm == NULL ||
818 &WTFReportAssertionFailure == NULL ||
819 &_ZN3WTF8fastFreeEPv == NULL ||
823 MSHook(void, _ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, JSC::SourceCode **_this, JSC::JSGlobalData *global, int *line, JSC::UString *message) {
825 return __ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE(_this, global, line, message);
827 SetParser(false, true);
829 JSC::SourceCode *source(*_this);
830 const uint16_t *data(source->data());
831 size_t size(source->length());
834 apr_pool_create(&pool, NULL);
836 Cycriptify(pool, data, size);
837 source->~SourceCode();
838 new (source) JSC::SourceCode(JSC::UStringSourceProvider::create(JSC::UString(data, size), "cycript://"), 1);
840 apr_pool_destroy(pool);
842 __ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE(_this, global, line, message);
846 MSHook(void, _ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE, void *_this, int start, const UChar *code, unsigned length, int *source, int *line, JSC::UString *message) {
848 return __ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE(_this, start, code, length, source, line, message);
850 const uint16_t *data(code);
854 apr_pool_create(&pool, NULL);
856 Cycriptify(pool, data, size);
857 __ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE(_this, start, data, size, source, line, message);
859 apr_pool_destroy(pool);
867 MSHook(State, _ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE, State state) {
868 SetParser(false, true);
869 state = __ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE(state);
870 SetParser(false, false);
874 MSHook(void, _ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE, void *resource) {
875 SetParser(false, true);
876 __ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE(resource);
877 SetParser(false, false);
880 MSHook(bool, _ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, const WebCore::String &mime) {
881 if (!GetParser1() || mime != "text/cycript")
882 return __ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE(mime);
884 static void *handle(dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL));
888 SetParser(true, true);
892 /* Cydget:// Protocol {{{ */
893 @interface CydgetURLProtocol : NSURLProtocol {
898 @implementation CydgetURLProtocol
900 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
901 NSURL *url([request URL]);
904 NSString *scheme([[url scheme] lowercaseString]);
905 if (scheme == nil || ![scheme isEqualToString:@"cydget"])
910 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
914 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
915 id<NSURLProtocolClient> client([self client]);
917 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
919 NSData *data(UIImagePNGRepresentation(icon));
921 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
922 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
923 [client URLProtocol:self didLoadData:data];
924 [client URLProtocolDidFinishLoading:self];
928 - (void) startLoading {
929 id<NSURLProtocolClient> client([self client]);
930 NSURLRequest *request([self request]);
932 NSURL *url([request URL]);
933 NSString *href([url absoluteString]);
935 NSString *path([href substringFromIndex:9]);
936 NSRange slash([path rangeOfString:@"/"]);
939 if (slash.location == NSNotFound) {
943 command = [path substringToIndex:slash.location];
944 path = [path substringFromIndex:(slash.location + 1)];
947 if ([command isEqualToString:@"_UIImageWithName"]) {
950 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
951 UIImage *icon(_UIImageWithName(path));
952 [self _returnPNGWithImage:icon forRequest:request];
954 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
958 - (void) stopLoading {
963 /* Cydget-PHP:// Protocol {{{ */
964 @interface CydgetPHPURLProtocol : NSURLProtocol {
969 @implementation CydgetPHPURLProtocol
971 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
972 NSURL *url([request URL]);
975 NSString *scheme([[url scheme] lowercaseString]);
976 if (scheme == nil || ![scheme isEqualToString:@"cydget-php"])
981 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
985 - (void) startLoading {
986 id<NSURLProtocolClient> client([self client]);
987 NSURLRequest *request([self request]);
988 NSURL *url([request URL]);
990 NSString *path([url path]);
991 if (path == nil || ![path hasSuffix:@".php"]) {
992 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
996 NSFileManager *manager([NSFileManager defaultManager]);
997 if (![manager fileExistsAtPath:path]) {
998 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
1002 NSLog(@"%@::%@", path, [url query]);
1005 _assert(pipe(fds) != -1);
1009 setenv("GATEWAY_INTERFACE", "CGI/1.1", true);
1010 setenv("SCRIPT_FILENAME", [path UTF8String], true);
1011 NSString *query([url query]);
1013 setenv("QUERY_STRING", [query UTF8String], true);
1015 _assert(dup2(fds[1], 1) != -1);
1016 _assert(close(fds[0]) != -1);
1017 _assert(close(fds[1]) != -1);
1019 execl("/usr/bin/php-cgi", "php-cgi", NULL);
1024 _assert(close(fds[1]) != -1);
1026 CFHTTPMessageRef http(CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE));
1028 CFHTTPMessageAppendBytes(http, (const uint8_t *) "HTTP/1.1 200 OK\r\n", 17);
1030 if (FILE *file = fdopen(fds[0], "r")) {
1031 uint8_t buffer[16*1024];
1033 size_t count(fread(buffer, 1, sizeof(buffer), file));
1035 fwrite(buffer, 1, count, stderr);
1036 CFHTTPMessageAppendBytes(http, buffer, count);
1038 if (count == sizeof(buffer))
1041 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorNetworkConnectionLost userInfo:nil]];
1046 } else _assert(close(fds[0]));
1049 CFStringRef mime(CFHTTPMessageCopyHeaderFieldValue(http, CFSTR("Content-type")));
1051 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:nil]];
1055 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:(NSString *)mime expectedContentLength:-1 textEncodingName:nil] autorelease]);
1058 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
1060 CFDataRef data(CFHTTPMessageCopyBody(http));
1061 [client URLProtocol:self didLoadData:(NSData *)data];
1064 [client URLProtocolDidFinishLoading:self];
1071 - (void) stopLoading {
1077 template <typename Type_>
1078 static void nlset(Type_ &function, struct nlist *nl, size_t index) {
1079 struct nlist &name(nl[index]);
1080 uintptr_t value(name.n_value);
1081 if ((name.n_desc & N_ARM_THUMB_DEF) != 0)
1082 value |= 0x00000001;
1083 function = reinterpret_cast<Type_>(value);
1086 template <typename Type_>
1087 static void dlset(Type_ &function, const char *name) {
1088 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1091 @implementation WebCycriptLockScreenController
1093 + (void) initialize {
1096 [NSURLProtocol registerClass:[CydgetURLProtocol class]];
1097 [NSURLProtocol registerClass:[CydgetPHPURLProtocol class]];
1099 void (*_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE)(JSC::SourceCode **, JSC::JSGlobalData *, int *, JSC::UString *);
1100 dlset(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, "_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE");
1101 if (_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE != NULL)
1102 MSHookFunction(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, MSHake(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE));
1104 void (*_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE)(void *, int, const UChar *, unsigned, int *, int *, JSC::UString *);
1105 dlset(_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE, "_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE");
1106 if (_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE != NULL)
1107 MSHookFunction(_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE, MSHake(_ZN3KJS6Parser5parseEiPKNS_5UCharEjPiS4_PNS_7UStringE));
1110 memset(nl, 0, sizeof(nl));
1111 nl[0].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE";
1112 nl[1].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE";
1113 nl[2].n_un.n_name = (char *) "__ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE";
1114 nlist("/System/Library/PrivateFrameworks/WebCore.framework/WebCore", nl);
1116 State (*_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE)(State);
1117 nlset(_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE, nl, 0);
1118 MSHookFunction(_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE, MSHake(_ZN7WebCore13HTMLTokenizer13scriptHandlerENS0_5StateE));
1120 void (*_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE)(void *);
1121 nlset(_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE, nl, 1);
1122 MSHookFunction(_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE, MSHake(_ZN7WebCore13HTMLTokenizer14notifyFinishedEPNS_14CachedResourceE));
1124 bool (*_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE)(const WebCore::String &);
1125 nlset(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, nl, 2);
1126 MSHookFunction(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, MSHake(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE));
1129 + (id) rootViewController {
1130 return [[[self alloc] init] autorelease];
1134 [self setView:[[[WebCydgetLockScreenView alloc] init] autorelease]];