cordova-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From agri...@apache.org
Subject [07/21] git commit: Code clean-up of AppBundle's JS & Obj-C
Date Thu, 24 Oct 2013 01:55:46 GMT
Code clean-up of AppBundle's JS & Obj-C


Project: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/commit/8ed807ca
Tree: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/tree/8ed807ca
Diff: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/diff/8ed807ca

Branch: refs/heads/master
Commit: 8ed807cac13ae07ce3545ce5b04781986b0f859e
Parents: 41e2b4d
Author: Andrew Grieve <agrieve@chromium.org>
Authored: Tue Oct 15 22:52:51 2013 -0400
Committer: Andrew Grieve <agrieve@chromium.org>
Committed: Wed Oct 23 21:55:17 2013 -0400

----------------------------------------------------------------------
 AppBundle/README.md                  |   8 +-
 AppBundle/appBundle.js               |  32 +++--
 AppBundle/plugin.xml                 |  34 +++--
 AppBundle/src/android/AppBundle.java |   2 +-
 AppBundle/src/ios/AppBundle.h        |  80 -----------
 AppBundle/src/ios/AppBundle.m        | 215 ++++++++++++------------------
 6 files changed, 133 insertions(+), 238 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/8ed807ca/AppBundle/README.md
----------------------------------------------------------------------
diff --git a/AppBundle/README.md b/AppBundle/README.md
index 4d852ea..d1b55e0 100644
--- a/AppBundle/README.md
+++ b/AppBundle/README.md
@@ -1,13 +1,11 @@
 AppBundle
 =========
 
-This plugin allows any uri's that are loaded to be replaced with modified uri's
-These include uri's being loaded by the browser such as page navigation, script tags.
-This also includes file uris being opened by file api etc. (currently android only)
+Enables dynamic rerouting or URLs.
 
 ##AppBundle Uri's
 This plugin allows the use of "app-bundle://" instead of platform specific urls such "file:///android_asset"
etc.
-For example to refer to an index.html file in the "www" folder with an absolute path, you
can use
+For example, to refer to an index.html file in the "www" folder with an absolute path, you
can use
 
     "app-bundle:///index.html"
 
@@ -70,5 +68,3 @@ Apply recursive replacements. A request to http://mysite.com/blah should
give ht
     appBundle.addAlias("^http://mysite\.com/.*", "^http://mysite\.com/", "http:///mysiteproxy.com/",
false, function(succeded){});
     appBundle.addAlias("^http:///mysiteproxy\.com/.*", "^http:///mysiteproxy\.com/", "http:///mysiteproxy2.com/",
false, function(succeded){});
 
-##Installation - Cordova  2.7 or later
-        cordova plugin add directory-of-the-AppBundle-plugin

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/8ed807ca/AppBundle/appBundle.js
----------------------------------------------------------------------
diff --git a/AppBundle/appBundle.js b/AppBundle/appBundle.js
index 469ed7a..cde9ce3 100644
--- a/AppBundle/appBundle.js
+++ b/AppBundle/appBundle.js
@@ -1,3 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+*/
 var exec = cordova.require('cordova/exec');
 
 exports.addAlias = function(sourceUriMatchRegex, sourceUriReplaceRegex, replaceString, redirectToReplacedUrl,
callback) {
@@ -5,19 +24,12 @@ exports.addAlias = function(sourceUriMatchRegex, sourceUriReplaceRegex,
replaceS
         callback(true);
     };
     var fail = callback && function(error) {
-        callback(false);
         console.error("AppBundle error: " + error);
+        callback(false);
     };
     exec(win, fail, 'AppBundle', 'addAlias', [sourceUriMatchRegex, sourceUriReplaceRegex,
replaceString, redirectToReplacedUrl]);
 };
 
 exports.clearAllAliases = function(callback){
-    var win = callback && function() {
-        callback(true);
-    };
-    var fail = callback && function(error) {
-        callback(false);
-        console.error("AppBundle error: " + error);
-    };
-    exec(win, fail, 'AppBundle', 'clearAllAliases', []);
-};
\ No newline at end of file
+    exec(callback, null, 'AppBundle', 'clearAllAliases', []);
+};

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/8ed807ca/AppBundle/plugin.xml
----------------------------------------------------------------------
diff --git a/AppBundle/plugin.xml b/AppBundle/plugin.xml
index d1cb1c2..375730b 100644
--- a/AppBundle/plugin.xml
+++ b/AppBundle/plugin.xml
@@ -1,23 +1,42 @@
 <?xml version="1.0" encoding="UTF-8" ?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied.  See the License for the
+  specific language governing permissions and limitations
+  under the License.
+-->
 <plugin xmlns="http://phonegap.com/ns/plugins/1.0"
     xmlns:android="http://schemas.android.com/apk/res/android"
-    id="AppBundle"
+    id="org.apache.cordova.AppBundle"
     version="1.0.0">
   <engines>
-    <engine name="cordova" version=">=2.6.0" />
+    <engine name="cordova" version=">=3.0.0" />
   </engines>
 
-  <name>App Bundle Url's</name>
+  <name>App Bundle URLs</name>
 
   <js-module src="appBundle.js" name="AppBundle">
+    <clobbers target="cordova.plugins.appBundle" />
   </js-module>
 
   <platform name="android">
-    <source-file src="src/android/AppBundle.java" target-dir="src/org/apache/cordova"
/>
+    <source-file src="src/android/AppBundle.java" target-dir="src/org/apache/cordova/appbundle"
/>
 
-    <config-file target="res/xml/config.xml" parent="/widget">
+    <config-file target="res/xml/config.xml" parent="/*">
       <feature name="AppBundle">
-        <param name="android-package" value="org.apache.cordova.AppBundle"/>
+        <param name="android-package" value="org.apache.cordova.appbundle.AppBundle"/>
         <param name="onload" value="true"/>
       </feature>
       <access origin="app-bundle://*" />
@@ -26,9 +45,8 @@
 
   <platform name="ios">
     <source-file src="src/ios/AppBundle.m" />
-    <header-file src="src/ios/AppBundle.h" />
 
-    <config-file target="config.xml" parent="/widget">
+    <config-file target="config.xml" parent="/*">
       <feature name="AppBundle">
         <param name="ios-package" value="AppBundle"/>
         <param name="onload" value="true"/>

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/8ed807ca/AppBundle/src/android/AppBundle.java
----------------------------------------------------------------------
diff --git a/AppBundle/src/android/AppBundle.java b/AppBundle/src/android/AppBundle.java
index 6fa1f3a..308f360 100644
--- a/AppBundle/src/android/AppBundle.java
+++ b/AppBundle/src/android/AppBundle.java
@@ -16,7 +16,7 @@
        specific language governing permissions and limitations
        under the License.
 */
-package org.apache.cordova;
+package org.apache.cordova.appbundle;
 
 import java.util.ArrayList;
 import java.util.List;

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/8ed807ca/AppBundle/src/ios/AppBundle.h
----------------------------------------------------------------------
diff --git a/AppBundle/src/ios/AppBundle.h b/AppBundle/src/ios/AppBundle.h
deleted file mode 100644
index 4d07487..0000000
--- a/AppBundle/src/ios/AppBundle.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements.  See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership.  The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License.  You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied.  See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-#import <Foundation/Foundation.h>
-#import <Cordova/CDVPlugin.h>
-
-/*
-This plugin allows any uri's that are loaded to be replaced with modified uri's
-These include uri's being loaded by the browser such as page navigation, script tags.
-*******************TODO: shravanrn************************
-There is currently a DataResource mechanism bering reviewed for ios. This mechanism will
provide a unified way to load and listen to all uri requets.
-Once this goes through, this plugin can be modified to be able listen to oading of other
uris such file uris being opened by file api as well.
-*******************TODO: shravanrn************************
-
-There are 4 parameters here that affect the replacement.
-The matchRegex, replaceRegex, replacerString, shouldRedirect
-
-The algorithm operates as follows
-
-currently loading 'url'
-if(url matches matchRegex){
-    newUrl = url.replace(replaceRegex, replacerString)
-    if(this is topLevelRequest){
-        stopLoadingUrl()
-        loadUrl(newUrl)
-        return
-    } else {
-        url = newUrl
-    }
-}
-continue loading 'url'
-
-There are some implementation details involved here such as the ability to distinguish between
top level requests and other requests.
-Please see the code for details regarding this.
-
-There is an array of {matchRegex, replaceRegex, replacerString, shouldRedirect} stored referred
to as the reroute map
-
-"app-bundle:" uri's are absolute uri's that point to your bundle.
-By default the rerouteMap contains the parameters required to redirect
-    app-bundle:///blah -> file:///android_asset/www/blah
-
-The rerouteMap can be modified from javascript by calling the addAlias and clearAlias methods
-
-Recursive replacements are supported by this plugin as well.
-Consider the reroute map contains
-     1) http://mysite.com/ -> file:///android_asset/www/
-     2) file:///android_asset/www/blah -> file:///storage/www/
-     3) http://mysite.com/ -> http:///mysiteproxy.com/
-     4) http://mysiteproxy.com/ -> http:///mysiteproxy2.com/
-A request to http://mysite.com/blah should give http:///mysiteproxy2.com/blah
-Also note that the recursive replacements apply the rules last to first.
-
-*******************TODO: shravanrn************************
-Recursive replacements to app-bundle: should not occur
-For example lets say the we have the rerouteParams set up as
-     1) app-bundle:/// -> file:///android_asset/www/
-     2) file:///android_asset/www/ -> file:///storage/www/
-A request to app-bundle:///blah should give file:///android_asset/www/ NOT file:///storage/www/
-This requirement is required by the definition of app-bundle: uris.
-*******************TODO: shravanrn************************
-*/
-@interface AppBundle : CDVPlugin {}
-- (void)addAlias:(CDVInvokedUrlCommand*)command;
-- (void)clearAllAliases:(CDVInvokedUrlCommand*)command;
-@end

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/8ed807ca/AppBundle/src/ios/AppBundle.m
----------------------------------------------------------------------
diff --git a/AppBundle/src/ios/AppBundle.m b/AppBundle/src/ios/AppBundle.m
index 6776b8c..3106531 100644
--- a/AppBundle/src/ios/AppBundle.m
+++ b/AppBundle/src/ios/AppBundle.m
@@ -16,28 +16,36 @@
  specific language governing permissions and limitations
  under the License.
  */
-#import "AppBundle.h"
+#import <UIKit/UIKit.h>
+#import <Cordova/CDVPlugin.h>
 
-// Note: See header for details about this plugin's behaviour
+@class RouteParams;
 
-#pragma mark declare
+static NSString* const kAppBundlePrefix = @"app-bundle:///";
+static NSString* gPathPrefix;
+static UIWebView* gWebView;
+static NSMutableArray* gRerouteParams;
+static RouteParams* gAppBundleParams;
+
+@interface AppBundle : CDVPlugin {}
+- (void)addAlias:(CDVInvokedUrlCommand*)command;
+- (void)clearAllAliases:(CDVInvokedUrlCommand*)command;
+@end
 
 @interface AppBundle()
 {}
-+ (NSString*) insertFileScheme:(NSString*)path;
 - (void) resetMap;
-+ (NSString*) getRegex:(NSString*)string;
 @end
 
 @interface RouteParams : NSObject
 {
+@public
+    NSRegularExpression* _matchRegex;
+    NSRegularExpression* _replaceRegex;
+    NSString* _replacer;
+    BOOL _redirectToReplacedUrl;
 }
-@property (nonatomic, readwrite, strong) NSRegularExpression* matchRegex;
-@property (nonatomic, readwrite, strong) NSRegularExpression* replaceRegex;
-@property (nonatomic, readwrite, strong) NSString* replacer;
-@property (nonatomic, readwrite, assign) BOOL redirectToReplacedUrl;
-- (RouteParams*)initWithMatchRegex:(NSRegularExpression*) matchRegex1 ReplaceRegex:(NSRegularExpression*)replaceRegex1
Replacer:(NSString*) replacer1 ShouldRedirect:(BOOL) redirectToReplacedUrl1;
-
+- (RouteParams*)initWithMatchRegex:(NSRegularExpression*)matchRegex replaceRegex:(NSRegularExpression*)replaceRegex
replacer:(NSString*)replacer shouldRedirect:(BOOL)redirectToReplacedUrl;
 @end
 
 @interface AppBundleURLProtocol : NSURLProtocol
@@ -47,107 +55,65 @@
 - (void)issueNotFoundResponse;
 @end
 
-NSString* const appBundlePrefix = @"app-bundle:///";
-static NSString* pathPrefix;
-static UIWebView* uiwebview;
-static NSMutableArray* rerouteParams;
-static RouteParams* appBundleParams;
 
 #pragma mark AppBundle
 
 @implementation AppBundle
 
-+ (NSString*) insertFileScheme:(NSString*)path
-{
-    NSRange wholeStringRange = NSMakeRange(0, [path length]);
-    NSRegularExpression* schemeRegex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9a-zA-Z+.-]+:"
options:0 error:nil];
-    NSRange range = [schemeRegex rangeOfFirstMatchInString:path options:0 range:wholeStringRange];
-    if(NSEqualRanges(range, NSMakeRange(NSNotFound, 0)))
-    {
-        return [NSString stringWithFormat:@"file://%@", path];
-    }
-    return path;
-}
-
-- (void) resetMap
+- (void)resetMap
 {
     NSError *error = NULL;
     NSRegularExpression* bundleMatchRegex = [NSRegularExpression regularExpressionWithPattern:@"^app-bundle:///.*"
options:0 error:&error];
     NSRegularExpression* bundleReplaceRegex = [NSRegularExpression regularExpressionWithPattern:@"^app-bundle:///"
options:0 error:&error];
-    appBundleParams = [[RouteParams alloc] initWithMatchRegex:bundleMatchRegex ReplaceRegex:bundleReplaceRegex
Replacer:pathPrefix ShouldRedirect:YES];
-    rerouteParams = [[NSMutableArray alloc] init];
-    [rerouteParams addObject:appBundleParams];
-}
-+ (NSString*) getRegex:(NSString*)string
-{
-    return [NSRegularExpression escapedPatternForString:string];
+    gAppBundleParams = [[RouteParams alloc] initWithMatchRegex:bundleMatchRegex replaceRegex:bundleReplaceRegex
replacer:gPathPrefix shouldRedirect:YES];
+    gRerouteParams = [[NSMutableArray alloc] init];
+    [gRerouteParams addObject:gAppBundleParams];
 }
 
 - (CDVPlugin*)initWithWebView:(UIWebView*)theWebView
 {
     self = [super initWithWebView:theWebView];
-    uiwebview = theWebView;
+    gWebView = theWebView;
     if (self) {
         [NSURLProtocol registerClass:[AppBundleURLProtocol class]];
-        pathPrefix = [[NSBundle mainBundle] pathForResource:@"cordova.js" ofType:@"" inDirectory:@"www"];
-        NSRange range = [pathPrefix rangeOfString:@"/www/"];
-        pathPrefix = [[pathPrefix substringToIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceCharacterSet]];
-        pathPrefix = [[AppBundle insertFileScheme:pathPrefix] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
+        gPathPrefix = [[NSBundle mainBundle] pathForResource:@"cordova.js" ofType:@"" inDirectory:@"www"];
+        gPathPrefix = [gPathPrefix stringByDeletingLastPathComponent];
+        gPathPrefix = [[NSURL fileURLWithPath:gPathPrefix] absoluteString];
         [self resetMap];
     }
     return self;
 }
+
 - (void)addAlias:(CDVInvokedUrlCommand*)command
 {
     CDVPluginResult* pluginResult = nil;
-    @try {
-        NSError* error;
-        NSString* sourceUrlMatchRegexString = [[command.arguments objectAtIndex:0] stringByReplacingOccurrencesOfString:@"{BUNDLE_WWW}"
withString:[AppBundle getRegex:pathPrefix]];
-        NSRegularExpression* sourceUrlMatchRegex = [NSRegularExpression regularExpressionWithPattern:sourceUrlMatchRegexString
options:0 error:&error];
-        if(error) {
-            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Match
regex is invalid"];
-            return;
-        }
-        NSString* sourceUrlReplaceRegexString = [[command.arguments objectAtIndex:1] stringByReplacingOccurrencesOfString:@"{BUNDLE_WWW}"
withString:[AppBundle getRegex:pathPrefix]];
+    NSError* error = nil;
+    NSString* sourceUrlMatchRegexString = [[command.arguments objectAtIndex:0] stringByReplacingOccurrencesOfString:@"{BUNDLE_WWW}"
withString:[NSRegularExpression escapedPatternForString:gPathPrefix]];
+    NSRegularExpression* sourceUrlMatchRegex = [NSRegularExpression regularExpressionWithPattern:sourceUrlMatchRegexString
options:0 error:&error];
+    if(error) {
+        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Match
regex is invalid"];
+    } else {
+        NSString* sourceUrlReplaceRegexString = [[command.arguments objectAtIndex:1] stringByReplacingOccurrencesOfString:@"{BUNDLE_WWW}"
withString:[NSRegularExpression escapedPatternForString:gPathPrefix]];
         NSRegularExpression* sourceUrlReplaceRegex = [NSRegularExpression regularExpressionWithPattern:sourceUrlReplaceRegexString
options:0 error:&error];
         if(error) {
             pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Replace
regex is invalid"];
-            return;
-        }
-        NSString* replaceString = [[command.arguments objectAtIndex:2] stringByReplacingOccurrencesOfString:@"{BUNDLE_WWW}"
withString:pathPrefix];
-        replaceString = [replaceString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
-        BOOL redirectToReplacedUrl = [[command.arguments objectAtIndex:3] boolValue];
-
-        NSRange wholeStringRange = NSMakeRange(0, [replaceString length]);
-        NSRange range = [sourceUrlMatchRegex rangeOfFirstMatchInString:replaceString options:0
range:wholeStringRange];
-        if(!NSEqualRanges(range, NSMakeRange(NSNotFound, 0))) {
-            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"The
replaceString cannot match the match regex. This would lead to recursive replacements."];
         } else {
-            RouteParams* params = [[RouteParams alloc] initWithMatchRegex:sourceUrlMatchRegex
ReplaceRegex:sourceUrlReplaceRegex Replacer:replaceString ShouldRedirect:redirectToReplacedUrl];
-            [rerouteParams addObject:params];
+            NSString* replaceString = [[command.arguments objectAtIndex:2] stringByReplacingOccurrencesOfString:@"{BUNDLE_WWW}"
withString:gPathPrefix];
+            BOOL redirectToReplacedUrl = [[command.arguments objectAtIndex:3] boolValue];
+
+            RouteParams* params = [[RouteParams alloc] initWithMatchRegex:sourceUrlMatchRegex
replaceRegex:sourceUrlReplaceRegex replacer:replaceString shouldRedirect:redirectToReplacedUrl];
+            [gRerouteParams addObject:params];
             pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
         }
-    } @catch(NSException *exception) {
-        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could
not add alias"];
-        NSLog(@"Could not add alias - %@", [exception debugDescription]);
-    } @finally {
-        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
     }
+    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
 }
+
 - (void)clearAllAliases:(CDVInvokedUrlCommand*)command
 {
-    CDVPluginResult* pluginResult = nil;
-    @try {
-        [self resetMap];
-        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
-    }
-    @catch (NSException *exception) {
-        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could
not clear aliases"];
-        NSLog(@"Could not clear aliases - %@", [exception debugDescription]);
-    }
-    @finally {
-        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
-    }
+    [self resetMap];
+    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
+    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
 }
 @end
 
@@ -155,20 +121,15 @@ static RouteParams* appBundleParams;
 
 @implementation RouteParams
 
-@synthesize matchRegex;
-@synthesize replaceRegex;
-@synthesize replacer;
-@synthesize redirectToReplacedUrl;
-
-- (RouteParams*)initWithMatchRegex:(NSRegularExpression*) matchRegex1 ReplaceRegex:(NSRegularExpression*)replaceRegex1
Replacer:(NSString*) replacer1 ShouldRedirect:(BOOL) redirectToReplacedUrl1
+- (RouteParams*)initWithMatchRegex:(NSRegularExpression*)matchRegex replaceRegex:(NSRegularExpression*)replaceRegex
replacer:(NSString*)replacer shouldRedirect:(BOOL)redirectToReplacedUrl
 {
     self = [super init];
     if(self)
     {
-        [self setMatchRegex:matchRegex1];
-        [self setReplaceRegex:replaceRegex1];
-        [self setReplacer:replacer1];
-        [self setRedirectToReplacedUrl:redirectToReplacedUrl1];
+        _matchRegex = matchRegex;
+        _replaceRegex = replaceRegex;
+        _replacer = replacer;
+        _redirectToReplacedUrl = redirectToReplacedUrl;
     }
     return self;
 }
@@ -179,12 +140,12 @@ static RouteParams* appBundleParams;
 
 @implementation AppBundleURLProtocol
 
-+ (RouteParams*) getChosenParams:(NSString*)uriString
++ (RouteParams*)getChosenParams:(NSString*)uriString
 {
     NSRange wholeStringRange = NSMakeRange(0, [uriString length]);
-    for(RouteParams* param in rerouteParams) {
-        NSRange rangeOfMatch = [param.matchRegex rangeOfFirstMatchInString:uriString options:0
range:wholeStringRange];
-        if (NSEqualRanges(rangeOfMatch, wholeStringRange)) {
+    for(RouteParams* param in gRerouteParams) {
+        NSInteger numMatches = [param->_matchRegex numberOfMatchesInString:uriString options:0
range:wholeStringRange];
+        if (numMatches > 0) {
             return param;
         }
     }
@@ -196,16 +157,7 @@ static RouteParams* appBundleParams;
     NSURL* url = [request URL];
     NSString* urlString = [url absoluteString];
     RouteParams* params = [AppBundleURLProtocol getChosenParams:urlString];
-    if(params != nil) {
-        NSURL* mainUrl = [request mainDocumentURL];
-        NSString* mainUrlString = [mainUrl absoluteString];
-        if([mainUrlString isEqualToString:urlString]){
-            return params.redirectToReplacedUrl;
-        } else {
-            return YES;
-        }
-    }
-    return NO;
+    return params != nil;
 }
 
 + (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request
@@ -226,48 +178,47 @@ static RouteParams* appBundleParams;
     NSURL* uri = [[self request] URL];
     NSString* uriString = [uri absoluteString];
     RouteParams* params = [AppBundleURLProtocol getChosenParams:uriString];
-    if(params != nil) {
-        NSRange wholeStringRange = NSMakeRange(0, [uriString length]);
-        NSString* newUrlString = [params.replaceRegex stringByReplacingMatchesInString:uriString
options:0 range:wholeStringRange withTemplate:params.replacer];
-        if([newUrlString hasPrefix:@"file://"]) {
-            NSURL *newUrl = [NSURL URLWithString:newUrlString];
-            NSString* path = [newUrl path];
-            FILE* fp = fopen([path UTF8String], "r");
-            if (fp) {
-                NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:uri statusCode:200
HTTPVersion:@"HTTP/1.1" headerFields:@{}];
-                [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
-
-                char buf[32768];
-                size_t len;
-                while ((len = fread(buf,1,sizeof(buf),fp))) {
-                    [[self client] URLProtocol:self didLoadData:[NSData dataWithBytes:buf
length:len]];
-                }
-                fclose(fp);
-
-                [[self client] URLProtocolDidFinishLoading:self];
-            } else {
-                [self issueNotFoundResponse];
+    NSRange wholeStringRange = NSMakeRange(0, [uriString length]);
+    NSString* newUrlString = [params->_replaceRegex stringByReplacingMatchesInString:uriString
options:0 range:wholeStringRange withTemplate:params->_replacer];
+    if ([newUrlString hasPrefix:@"file://"]) {
+        NSURL *newUrl = [NSURL URLWithString:newUrlString];
+        NSString* path = [newUrl path];
+        FILE* fp = fopen([path UTF8String], "r");
+        if (fp) {
+            NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:uri statusCode:200
HTTPVersion:@"HTTP/1.1" headerFields:@{}];
+            [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
+
+            char* buf = malloc(32768);
+            size_t len;
+            while ((len = fread(buf,1,32768,fp))) {
+                [[self client] URLProtocol:self didLoadData:[NSData dataWithBytes:buf length:len]];
             }
+            free(buf);
+            fclose(fp);
+
+            [[self client] URLProtocolDidFinishLoading:self];
         } else {
-            NSLog(@"Cannot redirect to %@. You can only redirect to file: uri's", newUrlString);
             [self issueNotFoundResponse];
         }
+    } else {
+        NSLog(@"Cannot redirect to %@. You can only redirect to file: uri's", newUrlString);
+        [self issueNotFoundResponse];
     }
 }
 
 - (void)issueRedirectResponseForFile:(NSString*)uriString
 {
     RouteParams* params = [AppBundleURLProtocol getChosenParams:uriString];
-    if(params != nil && params.redirectToReplacedUrl)
+    if(params != nil && params->_redirectToReplacedUrl)
     {
-        if([uiwebview isLoading]) {
-            [uiwebview stopLoading];
+        if([gWebView isLoading]) {
+            [gWebView stopLoading];
         }
         NSRange wholeStringRange = NSMakeRange(0, [uriString length]);
-        NSString* newUrlString = [params.replaceRegex stringByReplacingMatchesInString:uriString
options:0 range:wholeStringRange withTemplate:params.replacer];
+        NSString* newUrlString = [params->_replaceRegex stringByReplacingMatchesInString:uriString
options:0 range:wholeStringRange withTemplate:params->_replacer];
         NSURL *newUrl = [NSURL URLWithString:newUrlString];
         NSURLRequest *request = [NSURLRequest requestWithURL:newUrl];
-        [uiwebview loadRequest:request];
+        [gWebView loadRequest:request];
     }
 }
 
@@ -286,8 +237,6 @@ static RouteParams* appBundleParams;
 }
 
 - (void)stopLoading
-{
-    // do any cleanup here
-}
+{}
 
 @end


Mime
View raw message