Return-Path: X-Original-To: apmail-cordova-commits-archive@www.apache.org Delivered-To: apmail-cordova-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id D6C27119A1 for ; Tue, 22 Apr 2014 21:45:06 +0000 (UTC) Received: (qmail 70671 invoked by uid 500); 22 Apr 2014 21:45:04 -0000 Delivered-To: apmail-cordova-commits-archive@cordova.apache.org Received: (qmail 70518 invoked by uid 500); 22 Apr 2014 21:44:59 -0000 Mailing-List: contact commits-help@cordova.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@cordova.apache.org Delivered-To: mailing list commits@cordova.apache.org Received: (qmail 70360 invoked by uid 99); 22 Apr 2014 21:44:55 -0000 Received: from tyr.zones.apache.org (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 22 Apr 2014 21:44:55 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id 46AD18C2F82; Tue, 22 Apr 2014 21:44:55 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: shazron@apache.org To: commits@cordova.apache.org Date: Tue, 22 Apr 2014 21:45:01 -0000 Message-Id: <654635957926458f8dd533958cf31501@git.apache.org> In-Reply-To: <8a97197513594932ba6d193712186207@git.apache.org> References: <8a97197513594932ba6d193712186207@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [07/14] Update to modern layout http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVConfigParser.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVConfigParser.m b/CordovaLib/CordovaLib/Classes/Commands/CDVConfigParser.m new file mode 100644 index 0000000..ba71066 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVConfigParser.m @@ -0,0 +1,106 @@ +/* + 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 "CDVConfigParser.h" + +// The block below is to support NSArray/NSDictionary subscripting in 10.7 +#ifdef __MAC_10_7 + +@interface NSArray(Subscripting) +- (id)objectAtIndexedSubscript:(NSUInteger)index; +@end + +@interface NSMutableArray(Subscripting) +- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)index; +@end + +@interface NSDictionary(Subscripting) +- (id)objectForKeyedSubscript:(id)key; +@end + +@interface NSMutableDictionary(Subscripting) +- (void)setObject:(id)obj forKeyedSubscript:(id )key; +@end + +#endif + +@interface CDVConfigParser () + +@property (nonatomic, readwrite, strong) NSMutableDictionary* pluginsDict; +@property (nonatomic, readwrite, strong) NSMutableDictionary* settings; +@property (nonatomic, readwrite, strong) NSMutableArray* whitelistHosts; +@property (nonatomic, readwrite, strong) NSMutableArray* startupPluginNames; +@property (nonatomic, readwrite, strong) NSString* startPage; + +@end + +@implementation CDVConfigParser + +@synthesize pluginsDict, settings, whitelistHosts, startPage, startupPluginNames; + +- (id)init +{ + self = [super init]; + if (self != nil) { + self.pluginsDict = [[NSMutableDictionary alloc] initWithCapacity:30]; + self.settings = [[NSMutableDictionary alloc] initWithCapacity:30]; + self.whitelistHosts = [[NSMutableArray alloc] initWithCapacity:30]; + self.startupPluginNames = [[NSMutableArray alloc] initWithCapacity:8]; + featureName = nil; + } + return self; +} + +- (void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict +{ + if ([elementName isEqualToString:@"preference"]) { + settings[attributeDict[@"name"]] = attributeDict[@"value"]; + } else if ([elementName isEqualToString:@"feature"]) { // store feature name to use with correct parameter set + featureName = [attributeDict[@"name"] lowercaseString]; + } else if ((featureName != nil) && [elementName isEqualToString:@"param"]) { + NSString* paramName = [attributeDict[@"name"] lowercaseString]; + id value = attributeDict[@"value"]; + if ([paramName isEqualToString:@"ios-package"]) { + pluginsDict[featureName] = value; + } + BOOL paramIsOnload = ([paramName isEqualToString:@"onload"] && [@"true" isEqualToString : value]); + BOOL attribIsOnload = [@"true" isEqualToString : [attributeDict[@"onload"] lowercaseString]]; + if (paramIsOnload || attribIsOnload) { + [self.startupPluginNames addObject:featureName]; + } + } else if ([elementName isEqualToString:@"access"]) { + [whitelistHosts addObject:attributeDict[@"origin"]]; + } else if ([elementName isEqualToString:@"content"]) { + self.startPage = attributeDict[@"src"]; + } +} + +- (void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName +{ + if ([elementName isEqualToString:@"feature"]) { // no longer handling a feature so release + featureName = nil; + } +} + +- (void)parser:(NSXMLParser*)parser parseErrorOccurred:(NSError*)parseError +{ + NSAssert(NO, @"config.xml parse error line %d col %d", [parser lineNumber], [parser columnNumber]); +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.h b/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.h new file mode 100644 index 0000000..d3e8c5d --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.h @@ -0,0 +1,34 @@ +/* + 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 +#import "CDVPlugin.h" +#import "CDVReachability.h" + +@interface CDVConnection : CDVPlugin { + NSString* type; + NSString* _callbackId; + + CDVReachability* internetReach; +} + +@property (copy) NSString* connectionType; +@property (strong) CDVReachability* internetReach; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.m b/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.m new file mode 100644 index 0000000..61030d3 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVConnection.m @@ -0,0 +1,125 @@ +/* + 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 "CDVConnection.h" +#import "CDVReachability.h" + +@interface CDVConnection (PrivateMethods) +- (void)updateOnlineStatus; +- (void)sendPluginResult; +@end + +@implementation CDVConnection + +@synthesize connectionType, internetReach; + +- (void)getConnectionInfo:(CDVInvokedUrlCommand*)command +{ + _callbackId = command.callbackId; + [self sendPluginResult]; +} + +- (void)sendPluginResult +{ + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:self.connectionType]; + + [result setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:result callbackId:_callbackId]; +} + +- (NSString*)w3cConnectionTypeFor:(CDVReachability*)reachability +{ + NetworkStatus networkStatus = [reachability currentReachabilityStatus]; + + switch (networkStatus) { + case NotReachable: + return @"none"; + + case ReachableViaWWAN: + return @"2g"; // no generic default, so we use the lowest common denominator + + case ReachableViaWiFi: + return @"wifi"; + + default: + return @"unknown"; + } +} + +- (BOOL)isCellularConnection:(NSString*)theConnectionType +{ + return [theConnectionType isEqualToString:@"2g"] || + [theConnectionType isEqualToString:@"3g"] || + [theConnectionType isEqualToString:@"4g"]; +} + +- (void)updateReachability:(CDVReachability*)reachability +{ + if (reachability) { + // check whether the connection type has changed + NSString* newConnectionType = [self w3cConnectionTypeFor:reachability]; + if ([newConnectionType isEqualToString:self.connectionType]) { // the same as before, remove dupes + return; + } else { + self.connectionType = [self w3cConnectionTypeFor:reachability]; + } + } + [self sendPluginResult]; +} + +- (void)updateConnectionType:(NSNotification*)note +{ + CDVReachability* curReach = [note object]; + + if ((curReach != nil) && [curReach isKindOfClass:[CDVReachability class]]) { + [self updateReachability:curReach]; + } +} + +- (void)onPause +{ + [self.internetReach stopNotifier]; +} + +- (void)onResume +{ + [self.internetReach startNotifier]; + [self updateReachability:self.internetReach]; +} + +- (CDVPlugin*)initWithWebView:(WebView*)theWebView +{ + self = [super initWithWebView:theWebView]; + if (self) { + self.connectionType = @"none"; + self.internetReach = [CDVReachability reachabilityForInternetConnection]; + self.connectionType = [self w3cConnectionTypeFor:self.internetReach]; + [self.internetReach startNotifier]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:) + name:kReachabilityChangedNotification object:nil]; +// TODO: +// if (&UIApplicationDidEnterBackgroundNotification && &UIApplicationWillEnterForegroundNotification) { +// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; +// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; +// } + } + return self; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.h b/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.h new file mode 100644 index 0000000..bb44368 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.h @@ -0,0 +1,29 @@ +/* + 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 + + +@interface CDVConsole : NSObject { + +} + +- (void) log:(NSString*)message; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.m b/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.m new file mode 100644 index 0000000..fc4b879 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVConsole.m @@ -0,0 +1,75 @@ +/* + 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 "CDVConsole.h" + + +@implementation CDVConsole + + +- (void) log:(NSString*)message +{ + NSLog(@"%@", message); +} + +#pragma mark WebScripting Protocol + +/* checks whether a selector is acceptable to be called from JavaScript */ ++ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector +{ + BOOL result = YES; + + int i = 0; + static SEL * acceptableList = NULL; + SEL currentSelector; + + if (acceptableList == NULL && (acceptableList = calloc(256, sizeof(SEL)))) // up to 256 selectors + { + acceptableList[i++] = @selector(log:); + } + + i = 0; + while (result == YES && (currentSelector = acceptableList[i++])) + { + //checking for exclusions + result = !(selector == currentSelector); + } + + return result; +} + +/* helper function so we don't have to have underscores and stuff in js to refer to the right method */ ++ (NSString*) webScriptNameForSelector:(SEL)aSelector +{ + id result = nil; + + if (aSelector == @selector(log:)) { + result = @"log"; + } + + return result; +} + +// right now exclude all properties (eg keys) ++ (BOOL) isKeyExcludedFromWebScript:(const char*)name +{ + return YES; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVDebug.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVDebug.h b/CordovaLib/CordovaLib/Classes/Commands/CDVDebug.h new file mode 100644 index 0000000..4a0d9f9 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVDebug.h @@ -0,0 +1,25 @@ +/* + 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. + */ + +#ifdef DEBUG + #define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) +#else + #define DLog(...) +#endif +#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.h b/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.h new file mode 100644 index 0000000..81cffb7 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.h @@ -0,0 +1,29 @@ +/* + 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 "CDVPlugin.h" + +@interface CDVDevice : CDVPlugin +{} + ++ (NSString*)cordovaVersion; + +- (void)getDeviceInfo:(CDVInvokedUrlCommand*)command; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.m b/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.m new file mode 100644 index 0000000..0636d95 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVDevice.m @@ -0,0 +1,102 @@ +/* + 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. + */ + +#include +#include + +#import "CDVDevice.h" +#import "CDVAvailability.h" + +#define SYSTEM_VERSION_PLIST @"/System/Library/CoreServices/SystemVersion.plist" + +@implementation CDVDevice + +- (NSString*)modelVersion +{ + size_t size; + + sysctlbyname("hw.machine", NULL, &size, NULL, 0); + char* machine = malloc(size); + sysctlbyname("hw.machine", machine, &size, NULL, 0); + NSString* modelVersion = [NSString stringWithUTF8String:machine]; + free(machine); + + return modelVersion; +} + +- (NSString*)uniqueAppInstanceIdentifier +{ + NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; + static NSString* UUID_KEY = @"CDVUUID"; + + NSString* app_uuid = [userDefaults stringForKey:UUID_KEY]; + + if (app_uuid == nil) { + CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); + CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef); + + app_uuid = [NSString stringWithString:(__bridge NSString*)uuidString]; + [userDefaults setObject:app_uuid forKey:UUID_KEY]; + [userDefaults synchronize]; + + CFRelease(uuidString); + CFRelease(uuidRef); + } + + return app_uuid; +} + +- (NSString*) platform +{ + return [[NSDictionary dictionaryWithContentsOfFile:SYSTEM_VERSION_PLIST] objectForKey:@"ProductName"]; +} + +- (NSString*)systemVersion +{ + return [[NSDictionary dictionaryWithContentsOfFile:SYSTEM_VERSION_PLIST] objectForKey:@"ProductVersion"]; +} + +- (void)getDeviceInfo:(CDVInvokedUrlCommand*)command +{ + NSDictionary* deviceProperties = [self deviceProperties]; + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:deviceProperties]; + + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +} + +- (NSDictionary*)deviceProperties +{ + NSMutableDictionary* devProps = [NSMutableDictionary dictionaryWithCapacity:4]; + + [devProps setObject:[self modelVersion] forKey:@"model"]; + [devProps setObject:[self platform] forKey:@"platform"]; + [devProps setObject:[self systemVersion] forKey:@"version"]; + [devProps setObject:[self uniqueAppInstanceIdentifier] forKey:@"uuid"]; + [devProps setObject:[[self class] cordovaVersion] forKey:@"cordova"]; + + NSDictionary* devReturn = [NSDictionary dictionaryWithDictionary:devProps]; + return devReturn; +} + ++ (NSString*)cordovaVersion +{ + return CDV_VERSION; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.h b/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.h new file mode 100644 index 0000000..5f7e204 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.h @@ -0,0 +1,52 @@ +/* + 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 + +@interface CDVInvokedUrlCommand : NSObject { + NSString* __weak _callbackId; + NSString* __weak _className; + NSString* __weak _methodName; + NSArray* __weak _arguments; +} + +@property (weak, nonatomic, readonly) NSArray* arguments; +@property (weak, nonatomic, readonly) NSString* callbackId; +@property (weak, nonatomic, readonly) NSString* className; +@property (weak, nonatomic, readonly) NSString* methodName; + ++ (CDVInvokedUrlCommand*)commandFromJson:(NSArray*)jsonEntry; + +- (id)initWithArguments:(NSArray*)arguments + callbackId :(NSString*)callbackId + className :(NSString*)className + methodName :(NSString*)methodName; + +- (id)initFromJson:(NSArray*)jsonEntry; + +// Returns the argument at the given index. +// If index >= the number of arguments, returns nil. +// If the argument at the given index is NSNull, returns nil. +- (id)argumentAtIndex:(NSUInteger)index; +// Same as above, but returns defaultValue instead of nil. +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue; +// Same as above, but returns defaultValue instead of nil, and if the argument is not of the expected class, returns defaultValue +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue andClass:(Class)aClass; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.m b/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.m new file mode 100644 index 0000000..6c7a856 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVInvokedUrlCommand.m @@ -0,0 +1,140 @@ +/* + 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 "CDVInvokedUrlCommand.h" +#import "CDVJSON.h" +#import "NSData+Base64.h" + +@implementation CDVInvokedUrlCommand + +@synthesize arguments = _arguments; +@synthesize callbackId = _callbackId; +@synthesize className = _className; +@synthesize methodName = _methodName; + ++ (CDVInvokedUrlCommand*)commandFromJson:(NSArray*)jsonEntry +{ + return [[CDVInvokedUrlCommand alloc] initFromJson:jsonEntry]; +} + +- (id)initFromJson:(NSArray*)jsonEntry +{ + id tmp = [jsonEntry objectAtIndex:0]; + NSString* callbackId = tmp == [NSNull null] ? nil : tmp; + NSString* className = [jsonEntry objectAtIndex:1]; + NSString* methodName = [jsonEntry objectAtIndex:2]; + NSMutableArray* arguments = [jsonEntry objectAtIndex:3]; + + return [self initWithArguments:arguments + callbackId:callbackId + className:className + methodName:methodName]; +} + +- (id)initWithArguments:(NSArray*)arguments + callbackId:(NSString*)callbackId + className:(NSString*)className + methodName:(NSString*)methodName +{ + self = [super init]; + if (self != nil) { + _arguments = arguments; + _callbackId = callbackId; + _className = className; + _methodName = methodName; + } + [self massageArguments]; + return self; +} + +- (void)massageArguments +{ + NSMutableArray* newArgs = nil; + + for (NSUInteger i = 0, count = [_arguments count]; i < count; ++i) { + id arg = [_arguments objectAtIndex:i]; + if (![arg isKindOfClass:[NSDictionary class]]) { + continue; + } + NSDictionary* dict = arg; + NSString* type = [dict objectForKey:@"CDVType"]; + if (!type || ![type isEqualToString:@"ArrayBuffer"]) { + continue; + } + NSString* data = [dict objectForKey:@"data"]; + if (!data) { + continue; + } + if (newArgs == nil) { + newArgs = [NSMutableArray arrayWithArray:_arguments]; + _arguments = newArgs; + } + [newArgs replaceObjectAtIndex:i withObject:[NSData dataFromBase64String:data]]; + } +} + +- (void)legacyArguments:(NSMutableArray**)legacyArguments andDict:(NSMutableDictionary**)legacyDict +{ + NSMutableArray* newArguments = [NSMutableArray arrayWithArray:_arguments]; + + for (NSUInteger i = 0; i < [newArguments count]; ++i) { + if ([[newArguments objectAtIndex:i] isKindOfClass:[NSDictionary class]]) { + if (legacyDict != NULL) { + *legacyDict = [newArguments objectAtIndex:i]; + } + [newArguments removeObjectAtIndex:i]; + break; + } + } + + // Legacy (two versions back) has no callbackId. + if (_callbackId != nil) { + [newArguments insertObject:_callbackId atIndex:0]; + } + if (legacyArguments != NULL) { + *legacyArguments = newArguments; + } +} + +- (id)argumentAtIndex:(NSUInteger)index +{ + return [self argumentAtIndex:index withDefault:nil]; +} + +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue +{ + return [self argumentAtIndex:index withDefault:defaultValue andClass:nil]; +} + +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue andClass:(Class)aClass +{ + if (index >= [_arguments count]) { + return defaultValue; + } + id ret = [_arguments objectAtIndex:index]; + if (ret == [NSNull null]) { + ret = defaultValue; + } + if ((aClass != nil) && ![ret isKindOfClass:aClass]) { + ret = defaultValue; + } + return ret; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.h b/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.h new file mode 100644 index 0000000..eaa895e --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.h @@ -0,0 +1,30 @@ +/* + 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. + */ + +@interface NSArray (CDVJSONSerializing) +- (NSString*)JSONString; +@end + +@interface NSDictionary (CDVJSONSerializing) +- (NSString*)JSONString; +@end + +@interface NSString (CDVJSONSerializing) +- (id)JSONObject; +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.m b/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.m new file mode 100644 index 0000000..78267e5 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVJSON.m @@ -0,0 +1,77 @@ +/* + 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 "CDVJSON.h" +#import + +@implementation NSArray (CDVJSONSerializing) + +- (NSString*)JSONString +{ + NSError* error = nil; + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:self + options:NSJSONWritingPrettyPrinted + error:&error]; + + if (error != nil) { + NSLog(@"NSArray JSONString error: %@", [error localizedDescription]); + return nil; + } else { + return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + } +} + +@end + +@implementation NSDictionary (CDVJSONSerializing) + +- (NSString*)JSONString +{ + NSError* error = nil; + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:self + options:NSJSONWritingPrettyPrinted + error:&error]; + + if (error != nil) { + NSLog(@"NSDictionary JSONString error: %@", [error localizedDescription]); + return nil; + } else { + return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + } +} + +@end + +@implementation NSString (CDVJSONSerializing) + +- (id)JSONObject +{ + NSError* error = nil; + id object = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] + options:kNilOptions + error:&error]; + + if (error != nil) { + NSLog(@"NSString JSONObject error: %@", [error localizedDescription]); + } + + return object; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.h b/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.h new file mode 100644 index 0000000..f9debe5 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.h @@ -0,0 +1,59 @@ +/* + 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 +#import +#import "CDVPluginResult.h" +#import "CDVCommandDelegate.h" +#import "CDVViewController.h" + +NSString* const CDVPageDidLoadNotification; +NSString* const CDVPluginHandleOpenURLNotification; +NSString* const CDVPluginResetNotification; +NSString* const CDVLocalNotification; + +@interface CDVPlugin : NSObject {} + +@property (nonatomic, weak) WebView* webView; +@property (nonatomic, unsafe_unretained) CDVViewController* viewController; +@property (nonatomic, unsafe_unretained) id commandDelegate; + +@property (readonly, assign) BOOL hasPendingOperation; + +- (CDVPlugin*)initWithWebView:(WebView*)theWebView; +- (void)pluginInitialize; + +- (void)handleOpenURL:(NSNotification*)notification; +- (void)onAppTerminate; +- (void)onMemoryWarning; +- (void)onReset; +- (void)dispose; + +/* + // see initWithWebView implementation + - (void) onPause {} + - (void) onResume {} + - (void) onOrientationWillChange {} + - (void) onOrientationDidChange {} + - (void)didReceiveLocalNotification:(NSNotification *)notification; + */ + +- (id)appDelegate; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.m b/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.m new file mode 100644 index 0000000..a7d98ed --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVPlugin.m @@ -0,0 +1,129 @@ +/* + 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 "CDVPlugin.h" + +NSString* const CDVPageDidLoadNotification = @"CDVPageDidLoadNotification"; +NSString* const CDVPluginHandleOpenURLNotification = @"CDVPluginHandleOpenURLNotification"; +NSString* const CDVPluginResetNotification = @"CDVPluginResetNotification"; +NSString* const CDVLocalNotification = @"CDVLocalNotification"; + +@interface CDVPlugin () + +@property (readwrite, assign) BOOL hasPendingOperation; + +@end + +@implementation CDVPlugin +@synthesize webView, viewController, commandDelegate, hasPendingOperation; + +- (CDVPlugin*)initWithWebView:(WebView*)theWebView +{ + self = [super init]; + if (self) { +// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppTerminate) name:UIApplicationWillTerminateNotification object:nil]; +// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:CDVPluginHandleOpenURLNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReset) name:CDVPluginResetNotification object:theWebView]; + + self.webView = theWebView; + } + return self; +} + +- (void)pluginInitialize +{ + // You can listen to more app notifications, see: + // http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006728-CH3-DontLinkElementID_4 + + // NOTE: if you want to use these, make sure you uncomment the corresponding notification handler + + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onOrientationWillChange) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onOrientationDidChange) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; + + // Added in 2.3.0 + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveLocalNotification:) name:CDVLocalNotification object:nil]; + + // Added in 2.5.0 + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageDidLoad:) name:CDVPageDidLoadNotification object:self.webView]; +} + +- (void)dispose +{ + viewController = nil; + commandDelegate = nil; + webView = nil; +} + +/* +// NOTE: for onPause and onResume, calls into JavaScript must not call or trigger any blocking UI, like alerts +- (void) onPause {} +- (void) onResume {} +- (void) onOrientationWillChange {} +- (void) onOrientationDidChange {} +*/ + +/* NOTE: calls into JavaScript must not call or trigger any blocking UI, like alerts */ +- (void)handleOpenURL:(NSNotification*)notification +{ + // override to handle urls sent to your app + // register your url schemes in your App-Info.plist + + NSURL* url = [notification object]; + + if ([url isKindOfClass:[NSURL class]]) { + /* Do your thing! */ + } +} + +/* NOTE: calls into JavaScript must not call or trigger any blocking UI, like alerts */ +- (void)onAppTerminate +{ + // override this if you need to do any cleanup on app exit +} + +- (void)onMemoryWarning +{ + // override to remove caches, etc +} + +- (void)onReset +{ + // Override to cancel any long-running requests when the WebView navigates or refreshes. +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; // this will remove all notification unless added using addObserverForName:object:queue:usingBlock: +} + +- (id)appDelegate +{ + return [[NSApplication sharedApplication] delegate]; +} + +// default implementation does nothing, ideally, we are not registered for notification if we aren't going to do anything. +// - (void)didReceiveLocalNotification:(NSNotification *)notification +// { +// // UILocalNotification* localNotification = [notification object]; // get the payload as a LocalNotification +// } + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.h b/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.h new file mode 100644 index 0000000..8393df2 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.h @@ -0,0 +1,65 @@ +/* + 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 + +typedef enum { + CDVCommandStatus_NO_RESULT = 0, + CDVCommandStatus_OK, + CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION, + CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION, + CDVCommandStatus_INSTANTIATION_EXCEPTION, + CDVCommandStatus_MALFORMED_URL_EXCEPTION, + CDVCommandStatus_IO_EXCEPTION, + CDVCommandStatus_INVALID_ACTION, + CDVCommandStatus_JSON_EXCEPTION, + CDVCommandStatus_ERROR +} CDVCommandStatus; + +@interface CDVPluginResult : NSObject {} + +@property (nonatomic, strong, readonly) NSNumber* status; +@property (nonatomic, strong, readonly) id message; +@property (nonatomic, strong) NSNumber* keepCallback; + +- (CDVPluginResult*)init; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsString:(NSString*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArray:(NSArray*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsInt:(int)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDouble:(double)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsBool:(BOOL)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDictionary:(NSDictionary*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArrayBuffer:(NSData*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsMultipart:(NSArray*)theMessages; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageToErrorObject:(int)errorCode; + ++ (void)setVerbose:(BOOL)verbose; ++ (BOOL)isVerbose; + +- (void)setKeepCallbackAsBool:(BOOL)bKeepCallback; + +- (NSString*)argumentsAsJSON; + +// These methods are used by the legacy plugin return result method +- (NSString*)toJSONString; +- (NSString*)toSuccessCallbackString:(NSString*)callbackId; +- (NSString*)toErrorCallbackString:(NSString*)callbackId; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.m b/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.m new file mode 100644 index 0000000..a03e005 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVPluginResult.m @@ -0,0 +1,224 @@ +/* + 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 "CDVPluginResult.h" +#import "CDVJSON.h" +#import "CDVDebug.h" +#import "NSData+Base64.h" + +@interface CDVPluginResult () + +- (CDVPluginResult*)initWithStatus:(CDVCommandStatus)statusOrdinal message:(id)theMessage; + +@end + +@implementation CDVPluginResult +@synthesize status, message, keepCallback; + +static NSArray* org_apache_cordova_CommandStatusMsgs; + +id messageFromArrayBuffer(NSData* data) +{ + return @{ + @"CDVType" : @"ArrayBuffer", + @"data" :[data base64EncodedString] + }; +} + +id massageMessage(id message) +{ + if ([message isKindOfClass:[NSData class]]) { + return messageFromArrayBuffer(message); + } + return message; +} + +id messageFromMultipart(NSArray* theMessages) +{ + NSMutableArray* messages = [NSMutableArray arrayWithArray:theMessages]; + + for (NSUInteger i = 0; i < messages.count; ++i) { + [messages replaceObjectAtIndex:i withObject:massageMessage([messages objectAtIndex:i])]; + } + + return @{ + @"CDVType" : @"MultiPart", + @"messages" : messages + }; +} + ++ (void)initialize +{ + org_apache_cordova_CommandStatusMsgs = [[NSArray alloc] initWithObjects:@"No result", + @"OK", + @"Class not found", + @"Illegal access", + @"Instantiation error", + @"Malformed url", + @"IO error", + @"Invalid action", + @"JSON error", + @"Error", + nil]; +} + +- (CDVPluginResult*)init +{ + return [self initWithStatus:CDVCommandStatus_NO_RESULT message:nil]; +} + +- (CDVPluginResult*)initWithStatus:(CDVCommandStatus)statusOrdinal message:(id)theMessage +{ + self = [super init]; + if (self) { + status = [NSNumber numberWithInt:statusOrdinal]; + message = theMessage; + keepCallback = [NSNumber numberWithBool:NO]; + } + return self; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal +{ + return [[self alloc] initWithStatus:statusOrdinal message:[org_apache_cordova_CommandStatusMsgs objectAtIndex:statusOrdinal]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsString:(NSString*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:theMessage]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArray:(NSArray*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:theMessage]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsInt:(int)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithInt:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDouble:(double)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithDouble:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsBool:(BOOL)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithBool:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDictionary:(NSDictionary*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:theMessage]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArrayBuffer:(NSData*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:messageFromArrayBuffer(theMessage)]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsMultipart:(NSArray*)theMessages +{ + return [[self alloc] initWithStatus:statusOrdinal message:messageFromMultipart(theMessages)]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageToErrorObject:(int)errorCode +{ + NSDictionary* errDict = @{@"code": [NSNumber numberWithInt:errorCode]}; + + return [[self alloc] initWithStatus:statusOrdinal message:errDict]; +} + +- (void)setKeepCallbackAsBool:(BOOL)bKeepCallback +{ + [self setKeepCallback:[NSNumber numberWithBool:bKeepCallback]]; +} + +- (NSString*)argumentsAsJSON +{ + id arguments = (self.message == nil ? [NSNull null] : self.message); + NSArray* argumentsWrappedInArray = [NSArray arrayWithObject:arguments]; + + NSString* argumentsJSON = [argumentsWrappedInArray JSONString]; + + argumentsJSON = [argumentsJSON substringWithRange:NSMakeRange(1, [argumentsJSON length] - 2)]; + + return argumentsJSON; +} + +// These methods are used by the legacy plugin return result method +- (NSString*)toJSONString +{ + NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys: + self.status, @"status", + self.message ? self. message:[NSNull null], @"message", + self.keepCallback, @"keepCallback", + nil]; + + NSError* error = nil; + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict + options:NSJSONWritingPrettyPrinted + error:&error]; + NSString* resultString = nil; + + if (error != nil) { + NSLog(@"toJSONString error: %@", [error localizedDescription]); + } else { + resultString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + } + + if ([[self class] isVerbose]) { + NSLog(@"PluginResult:toJSONString - %@", resultString); + } + return resultString; +} + +- (NSString*)toSuccessCallbackString:(NSString*)callbackId +{ + NSString* successCB = [NSString stringWithFormat:@"cordova.callbackSuccess('%@',%@);", callbackId, [self toJSONString]]; + + if ([[self class] isVerbose]) { + NSLog(@"PluginResult toSuccessCallbackString: %@", successCB); + } + return successCB; +} + +- (NSString*)toErrorCallbackString:(NSString*)callbackId +{ + NSString* errorCB = [NSString stringWithFormat:@"cordova.callbackError('%@',%@);", callbackId, [self toJSONString]]; + + if ([[self class] isVerbose]) { + NSLog(@"PluginResult toErrorCallbackString: %@", errorCB); + } + return errorCB; +} + +static BOOL gIsVerbose = NO; ++ (void)setVerbose:(BOOL)verbose +{ + gIsVerbose = verbose; +} + ++ (BOOL)isVerbose +{ + return gIsVerbose; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.h b/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.h new file mode 100644 index 0000000..01a95c3 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.h @@ -0,0 +1,85 @@ +/* + + File: Reachability.h + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import +#import +#import + +typedef enum { + NotReachable = 0, + ReachableViaWWAN, // this value has been swapped with ReachableViaWiFi for Cordova backwards compat. reasons + ReachableViaWiFi // this value has been swapped with ReachableViaWWAN for Cordova backwards compat. reasons +} NetworkStatus; +#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification" + +@interface CDVReachability : NSObject +{ + BOOL localWiFiRef; + SCNetworkReachabilityRef reachabilityRef; +} + +// reachabilityWithHostName- Use to check the reachability of a particular host name. ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; + +// reachabilityWithAddress- Use to check the reachability of a particular IP address. ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; + +// reachabilityForInternetConnection- checks whether the default route is available. +// Should be used by applications that do not connect to a particular host ++ (CDVReachability*)reachabilityForInternetConnection; + +// reachabilityForLocalWiFi- checks whether a local wifi connection is available. ++ (CDVReachability*)reachabilityForLocalWiFi; + +// Start listening for reachability notifications on the current run loop +- (BOOL)startNotifier; +- (void)stopNotifier; + +- (NetworkStatus)currentReachabilityStatus; +// WWAN may be available, but not active until a connection has been established. +// WiFi may require a connection for VPN on Demand. +- (BOOL)connectionRequired; +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.m b/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.m new file mode 100644 index 0000000..ed1afe7 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Commands/CDVReachability.m @@ -0,0 +1,261 @@ +/* + + File: Reachability.m + Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. + Version: 2.2 + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under + Apple's copyrights in this original Apple software (the "Apple Software"), to + use, reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions + of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may be used + to endorse or promote products derived from the Apple Software without specific + prior written permission from Apple. Except as expressly stated in this notice, + no other rights or licenses, express or implied, are granted by Apple herein, + including but not limited to any patent rights that may be infringed by your + derivative works or by other works in which the Apple Software may be + incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR + DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF + CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF + APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2010 Apple Inc. All Rights Reserved. + +*/ + +#import +#import +#import +#import +#import +#import + +#import + +#import "CDVReachability.h" + +#define kShouldPrintReachabilityFlags 0 + +static void CDVPrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment) +{ +#if kShouldPrintReachabilityFlags + NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", + (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', + (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', + + (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', + (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', + (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', + (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', + (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-', + comment + ); +#endif +} + +@implementation CDVReachability + +static void CDVReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) +{ +#pragma unused (target, flags) + // NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); + // NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); + + // Converted the asserts above to conditionals, with safe return from the function + if (info == NULL) { + NSLog(@"info was NULL in ReachabilityCallback"); + return; + } + + if (![(__bridge NSObject*) info isKindOfClass:[CDVReachability class]]) { + NSLog(@"info was wrong class in ReachabilityCallback"); + return; + } + + // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively + // in case someon uses the Reachability object in a different thread. + @autoreleasepool { + CDVReachability* noteObject = (__bridge CDVReachability*)info; + // Post a notification to notify the client that the network reachability changed. + [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:noteObject]; + } +} + +- (BOOL)startNotifier +{ + BOOL retVal = NO; + SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL}; + + if (SCNetworkReachabilitySetCallback(reachabilityRef, CDVReachabilityCallback, &context)) { + if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { + retVal = YES; + } + } + return retVal; +} + +- (void)stopNotifier +{ + if (reachabilityRef != NULL) { + SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); + } +} + +- (void)dealloc +{ + [self stopNotifier]; + if (reachabilityRef != NULL) { + CFRelease(reachabilityRef); + } + +} + ++ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; +{ + CDVReachability* retVal = NULL; + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + retVal->localWiFiRef = NO; + } + } + return retVal; +} + ++ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; +{ + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); + CDVReachability* retVal = NULL; + if (reachability != NULL) { + retVal = [[self alloc] init]; + if (retVal != NULL) { + retVal->reachabilityRef = reachability; + retVal->localWiFiRef = NO; + } + } + return retVal; +} + ++ (CDVReachability*)reachabilityForInternetConnection; +{ + struct sockaddr_in zeroAddress; + bzero(&zeroAddress, sizeof(zeroAddress)); + zeroAddress.sin_len = sizeof(zeroAddress); + zeroAddress.sin_family = AF_INET; + return [self reachabilityWithAddress:&zeroAddress]; +} + ++ (CDVReachability*)reachabilityForLocalWiFi; +{ + struct sockaddr_in localWifiAddress; + bzero(&localWifiAddress, sizeof(localWifiAddress)); + localWifiAddress.sin_len = sizeof(localWifiAddress); + localWifiAddress.sin_family = AF_INET; + // IN_LINKLOCALNETNUM is defined in as 169.254.0.0 + localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); + CDVReachability* retVal = [self reachabilityWithAddress:&localWifiAddress]; + if (retVal != NULL) { + retVal->localWiFiRef = YES; + } + return retVal; +} + +#pragma mark Network Flag Handling + +- (NetworkStatus)localWiFiStatusForFlags:(SCNetworkReachabilityFlags)flags +{ + CDVPrintReachabilityFlags(flags, "localWiFiStatusForFlags"); + + BOOL retVal = NotReachable; + if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)) { + retVal = ReachableViaWiFi; + } + return retVal; +} + +- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags +{ + CDVPrintReachabilityFlags(flags, "networkStatusForFlags"); + if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { + // if target host is not reachable + return NotReachable; + } + + BOOL retVal = NotReachable; + + if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) { + // if target host is reachable and no connection is required + // then we'll assume (for now) that your on Wi-Fi + retVal = ReachableViaWiFi; + } + + if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) || + ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))) { + // ... and the connection is on-demand (or on-traffic) if the + // calling application is using the CFSocketStream or higher APIs + + if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) { + // ... and no [user] intervention is needed + retVal = ReachableViaWiFi; + } + } + + if ((flags & kSCNetworkReachabilityFlagsIsDirect) == kSCNetworkReachabilityFlagsIsDirect) { + // ... but WWAN connections are OK if the calling application + // is using the CFNetwork (CFSocketStream?) APIs. + retVal = ReachableViaWWAN; + } + return retVal; +} + +- (BOOL)connectionRequired; +{ + NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + return flags & kSCNetworkReachabilityFlagsConnectionRequired; + } + return NO; +} + +- (NetworkStatus)currentReachabilityStatus +{ + NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); + NetworkStatus retVal = NotReachable; + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { + if (localWiFiRef) { + retVal = [self localWiFiStatusForFlags:flags]; + } else { + retVal = [self networkStatusForFlags:flags]; + } + } + return retVal; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.h b/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.h new file mode 100644 index 0000000..ffe9c83 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.h @@ -0,0 +1,33 @@ +// +// NSData+Base64.h +// base64 +// +// Created by Matt Gallagher on 2009/06/03. +// Copyright 2009 Matt Gallagher. All rights reserved. +// +// Permission is given to use this source code file, free of charge, in any +// project, commercial or otherwise, entirely at your risk, with the condition +// that any redistribution (in part or whole) of source code must retain +// this copyright and permission notice. Attribution in compiled projects is +// appreciated but not required. +// + +#import + +void *CDVNewBase64Decode( + const char* inputBuffer, + size_t length, + size_t * outputLength); + +char *CDVNewBase64Encode( + const void* inputBuffer, + size_t length, + bool separateLines, + size_t * outputLength); + +@interface NSData (CDVBase64) + ++ (NSData*)dataFromBase64String:(NSString*)aString; +- (NSString*)base64EncodedString; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.m b/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.m new file mode 100644 index 0000000..08c801b --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Utils/NSData+Base64.m @@ -0,0 +1,286 @@ +// +// NSData+Base64.m +// base64 +// +// Created by Matt Gallagher on 2009/06/03. +// Copyright 2009 Matt Gallagher. All rights reserved. +// +// Permission is given to use this source code file, free of charge, in any +// project, commercial or otherwise, entirely at your risk, with the condition +// that any redistribution (in part or whole) of source code must retain +// this copyright and permission notice. Attribution in compiled projects is +// appreciated but not required. +// + +#import "NSData+Base64.h" + +// +// Mapping from 6 bit pattern to ASCII character. +// +static unsigned char cdvbase64EncodeLookup[65] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// +// Definition for "masked-out" areas of the base64DecodeLookup mapping +// +#define xx 65 + +// +// Mapping from ASCII character to 6 bit pattern. +// +static unsigned char cdvbase64DecodeLookup[256] = +{ + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, 62, xx, xx, xx, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, xx, xx, xx, xx, xx, xx, + xx, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, xx, xx, xx, xx, xx, + xx, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, + xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, +}; + +// +// Fundamental sizes of the binary and base64 encode/decode units in bytes +// +#define CDV_BINARY_UNIT_SIZE 3 +#define CDV_BASE64_UNIT_SIZE 4 + +// +// NewBase64Decode +// +// Decodes the base64 ASCII string in the inputBuffer to a newly malloced +// output buffer. +// +// inputBuffer - the source ASCII string for the decode +// length - the length of the string or -1 (to specify strlen should be used) +// outputLength - if not-NULL, on output will contain the decoded length +// +// returns the decoded buffer. Must be freed by caller. Length is given by +// outputLength. +// +void *CDVNewBase64Decode( + const char* inputBuffer, + size_t length, + size_t * outputLength) +{ + if (length == -1) { + length = strlen(inputBuffer); + } + + size_t outputBufferSize = (length / CDV_BASE64_UNIT_SIZE) * CDV_BINARY_UNIT_SIZE; + unsigned char* outputBuffer = (unsigned char*)malloc(outputBufferSize); + + size_t i = 0; + size_t j = 0; + + while (i < length) { + // + // Accumulate 4 valid characters (ignore everything else) + // + unsigned char accumulated[CDV_BASE64_UNIT_SIZE]; + bzero(accumulated, sizeof(unsigned char) * CDV_BASE64_UNIT_SIZE); + size_t accumulateIndex = 0; + + while (i < length) { + unsigned char decode = cdvbase64DecodeLookup[inputBuffer[i++]]; + if (decode != xx) { + accumulated[accumulateIndex] = decode; + accumulateIndex++; + + if (accumulateIndex == CDV_BASE64_UNIT_SIZE) { + break; + } + } + } + + // + // Store the 6 bits from each of the 4 characters as 3 bytes + // + outputBuffer[j] = (accumulated[0] << 2) | (accumulated[1] >> 4); + outputBuffer[j + 1] = (accumulated[1] << 4) | (accumulated[2] >> 2); + outputBuffer[j + 2] = (accumulated[2] << 6) | accumulated[3]; + j += accumulateIndex - 1; + } + + if (outputLength) { + *outputLength = j; + } + return outputBuffer; +} + +// +// NewBase64Decode +// +// Encodes the arbitrary data in the inputBuffer as base64 into a newly malloced +// output buffer. +// +// inputBuffer - the source data for the encode +// length - the length of the input in bytes +// separateLines - if zero, no CR/LF characters will be added. Otherwise +// a CR/LF pair will be added every 64 encoded chars. +// outputLength - if not-NULL, on output will contain the encoded length +// (not including terminating 0 char) +// +// returns the encoded buffer. Must be freed by caller. Length is given by +// outputLength. +// +char *CDVNewBase64Encode( + const void* buffer, + size_t length, + bool separateLines, + size_t * outputLength) +{ + const unsigned char* inputBuffer = (const unsigned char*)buffer; + +#define MAX_NUM_PADDING_CHARS 2 +#define OUTPUT_LINE_LENGTH 64 +#define INPUT_LINE_LENGTH ((OUTPUT_LINE_LENGTH / CDV_BASE64_UNIT_SIZE) * CDV_BINARY_UNIT_SIZE) +#define CR_LF_SIZE 0 + + // + // Byte accurate calculation of final buffer size + // + size_t outputBufferSize = + ((length / CDV_BINARY_UNIT_SIZE) + + ((length % CDV_BINARY_UNIT_SIZE) ? 1 : 0)) + * CDV_BASE64_UNIT_SIZE; + if (separateLines) { + outputBufferSize += + (outputBufferSize / OUTPUT_LINE_LENGTH) * CR_LF_SIZE; + } + + // + // Include space for a terminating zero + // + outputBufferSize += 1; + + // + // Allocate the output buffer + // + char* outputBuffer = (char*)malloc(outputBufferSize); + if (!outputBuffer) { + return NULL; + } + + size_t i = 0; + size_t j = 0; + const size_t lineLength = separateLines ? INPUT_LINE_LENGTH : length; + size_t lineEnd = lineLength; + + while (true) { + if (lineEnd > length) { + lineEnd = length; + } + + for (; i + CDV_BINARY_UNIT_SIZE - 1 < lineEnd; i += CDV_BINARY_UNIT_SIZE) { + // + // Inner loop: turn 48 bytes into 64 base64 characters + // + outputBuffer[j++] = cdvbase64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = cdvbase64EncodeLookup[((inputBuffer[i] & 0x03) << 4) + | ((inputBuffer[i + 1] & 0xF0) >> 4)]; + outputBuffer[j++] = cdvbase64EncodeLookup[((inputBuffer[i + 1] & 0x0F) << 2) + | ((inputBuffer[i + 2] & 0xC0) >> 6)]; + outputBuffer[j++] = cdvbase64EncodeLookup[inputBuffer[i + 2] & 0x3F]; + } + + if (lineEnd == length) { + break; + } + + // + // Add the newline + // + // outputBuffer[j++] = '\r'; + // outputBuffer[j++] = '\n'; + lineEnd += lineLength; + } + + if (i + 1 < length) { + // + // Handle the single '=' case + // + outputBuffer[j++] = cdvbase64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = cdvbase64EncodeLookup[((inputBuffer[i] & 0x03) << 4) + | ((inputBuffer[i + 1] & 0xF0) >> 4)]; + outputBuffer[j++] = cdvbase64EncodeLookup[(inputBuffer[i + 1] & 0x0F) << 2]; + outputBuffer[j++] = '='; + } else if (i < length) { + // + // Handle the double '=' case + // + outputBuffer[j++] = cdvbase64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2]; + outputBuffer[j++] = cdvbase64EncodeLookup[(inputBuffer[i] & 0x03) << 4]; + outputBuffer[j++] = '='; + outputBuffer[j++] = '='; + } + outputBuffer[j] = 0; + + // + // Set the output length and return the buffer + // + if (outputLength) { + *outputLength = j; + } + return outputBuffer; +} + +@implementation NSData (CDVBase64) + +// +// dataFromBase64String: +// +// Creates an NSData object containing the base64 decoded representation of +// the base64 string 'aString' +// +// Parameters: +// aString - the base64 string to decode +// +// returns the autoreleased NSData representation of the base64 string +// ++ (NSData*)dataFromBase64String:(NSString*)aString +{ + NSData* data = [aString dataUsingEncoding:NSASCIIStringEncoding]; + size_t outputLength; + void* outputBuffer = CDVNewBase64Decode([data bytes], [data length], &outputLength); + NSData* result = [NSData dataWithBytes:outputBuffer length:outputLength]; + + free(outputBuffer); + return result; +} + +// +// base64EncodedString +// +// Creates an NSString object that contains the base 64 encoding of the +// receiver's data. Lines are broken at 64 characters long. +// +// returns an autoreleased NSString being the base 64 representation of the +// receiver. +// +- (NSString*)base64EncodedString +{ + size_t outputLength = 0; + char* outputBuffer = + CDVNewBase64Encode([self bytes], [self length], true, &outputLength); + + NSString* result = + [[NSString alloc] + initWithBytes:outputBuffer + length:outputLength + encoding:NSASCIIStringEncoding]; + + free(outputBuffer); + return result; +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.h b/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.h new file mode 100644 index 0000000..03e4253 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.h @@ -0,0 +1,27 @@ +/* + 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 + +@interface NSWindow (Utils) + +- (float) titleBarHeight; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.m b/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.m new file mode 100644 index 0000000..a4b5f8c --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Utils/NSWindow+Utils.m @@ -0,0 +1,34 @@ +/* + 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 "NSWindow+Utils.h" + +@implementation NSWindow (Utils) + +- (float) titleBarHeight +{ + NSRect frame = [self frame]; + NSRect contentRect = [NSWindow contentRectForFrameRect: frame + styleMask: NSTitledWindowMask]; + + return (frame.size.height - contentRect.size.height); +} + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.h ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.h b/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.h new file mode 100644 index 0000000..ca711c0 --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.h @@ -0,0 +1,34 @@ +/* + 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 + +@class CDVPlugin; +@interface ShellUtils : NSObject + ++ (BOOL) restartComputer; ++ (void) quitApp; + ++ (NSTask*) shellTask:(NSString*)command; ++ (NSTask*) executeShellTaskAsync:(NSString*)command usingBlock:(void (^)(NSNotification *))block; ++ (void) executeShellTaskAsync:(NSString*)command withCallbackId:(NSString*)aCallbackId forPlugin:(CDVPlugin*)plugin; ++ (NSString*) executeShellTask:(NSString*)command; + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.m ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.m b/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.m new file mode 100644 index 0000000..9dcd55c --- /dev/null +++ b/CordovaLib/CordovaLib/Classes/Utils/ShellUtils.m @@ -0,0 +1,119 @@ +/* + 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 "ShellUtils.h" +#import +#import +#import "CDVPlugin.h" + +@implementation ShellUtils + ++ (BOOL) restartComputer +{ + NSAppleScript* script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to restart"]; + NSDictionary* errorInfo; + NSAppleEventDescriptor* descriptor = [script executeAndReturnError:&errorInfo]; + + return (descriptor != nil); +} + ++ (void) quitApp +{ + [[NSApplication sharedApplication] terminate:nil]; +} + ++ (NSTask*) shellTask:(NSString*)command +{ + NSTask* task = [[NSTask alloc] init]; + [task setLaunchPath: @"/bin/sh"]; + [task setStandardInput:[NSFileHandle fileHandleWithNullDevice]]; + [task setArguments: @[@"-c", command]]; + + return task; +} + ++ (NSString*) executeShellTask:(NSString*)command +{ + NSPipe* pipe = [NSPipe pipe]; + NSFileHandle* fileHandle = [pipe fileHandleForReading]; + + NSTask* task = [[self class] shellTask:command]; + [task setStandardOutput:pipe]; + [task setStandardError:pipe]; + [task launch]; + + NSData* outputData = [fileHandle readDataToEndOfFile]; + + return [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding]; +} + ++ (NSTask*) executeShellTaskAsync:(NSString*)command usingBlock:(void (^)(NSNotification *))block +{ + NSPipe* pipe = [NSPipe pipe]; + NSFileHandle* fileHandle = [pipe fileHandleForReading]; + + NSTask* task = [[self class] shellTask:command]; + [task setStandardOutput:pipe]; + [task setStandardError:pipe]; + + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + NSOperationQueue *mainQueue = [NSOperationQueue mainQueue]; + + [center addObserverForName:NSFileHandleReadCompletionNotification object:fileHandle queue:mainQueue usingBlock:block]; + [center addObserverForName:NSTaskDidTerminateNotification object:task queue:mainQueue usingBlock:block]; + + [task launch]; + [fileHandle readInBackgroundAndNotify]; + + return task; +} + ++ (void) executeShellTaskAsync:(NSString*)command withCallbackId:(NSString*)aCallbackId forPlugin:(CDVPlugin*)plugin +{ + __block NSString* callbackId = aCallbackId; + __block NSTask* task = nil; + + task = [[self class] executeShellTaskAsync:command usingBlock:^(NSNotification* notif){ + if ([notif.object isKindOfClass:[NSFileHandle class]]) { + NSFileHandle* fileHandle = (NSFileHandle*)notif.object; + NSData* data = [[notif userInfo] valueForKey:NSFileHandleNotificationDataItem]; + NSString* output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:@{ @"data": output }]; + result.keepCallback = [NSNumber numberWithBool:YES]; + [plugin.commandDelegate sendPluginResult:result callbackId:callbackId]; + + if (task && [task isRunning]) { + [fileHandle readInBackgroundAndNotify]; + } + + } else if ([notif.object isKindOfClass:[NSTask class]]) { + int status = [task terminationStatus]; + task = nil; + + CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK + messageAsDictionary:@{ @"resultcode" :[NSNumber numberWithInt:status] }]; + result.keepCallback = [NSNumber numberWithBool:NO]; + [plugin.commandDelegate sendPluginResult:result callbackId:callbackId]; + } + }]; +} + + +@end http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLib/CordovaLib-Prefix.pch ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLib/CordovaLib-Prefix.pch b/CordovaLib/CordovaLib/CordovaLib-Prefix.pch new file mode 100644 index 0000000..35d7640 --- /dev/null +++ b/CordovaLib/CordovaLib/CordovaLib-Prefix.pch @@ -0,0 +1,9 @@ +// +// Prefix header +// +// The contents of this file are implicitly included at the beginning of every source file. +// + +#ifdef __OBJC__ + #import +#endif http://git-wip-us.apache.org/repos/asf/cordova-osx/blob/18ecff57/CordovaLib/CordovaLibTests/CordovaLibTests-Info.plist ---------------------------------------------------------------------- diff --git a/CordovaLib/CordovaLibTests/CordovaLibTests-Info.plist b/CordovaLib/CordovaLibTests/CordovaLibTests-Info.plist new file mode 100644 index 0000000..b96525e --- /dev/null +++ b/CordovaLib/CordovaLibTests/CordovaLibTests-Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + org.apache.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + +