TagSpaces is an offline, open source, document manager with tagging support
TSN431 - Cordova add platform iOS
stanimir64755050722d
diff --git a/app/components/dialogs/ConfirmDialog.tsx b/app/components/dialogs/ConfirmDialog.tsxindex a2a69099a..2faecc5b3 100644--- a/app/components/dialogs/ConfirmDialog.tsx+++ b/app/components/dialogs/ConfirmDialog.tsx@@ -54,7 +54,7 @@ const ConfirmDialog = (props: Props) => {<Dialog open={open} onClose={onClose} keepMounted scroll="paper"><DialogTitle>{props.title}</DialogTitle><DialogContent>- <DialogContentText data-tid={props.confirmDialogContentTID}>+ <DialogContentText data-tid={props.confirmDialogContentTID} component="span">{props.content}{props.list && (<List dense>diff --git a/app/perspectives/grid-perspective/components/CellContent.tsx b/app/perspectives/grid-perspective/components/CellContent.tsxindex 786172d1a..c596656ec 100644--- a/app/perspectives/grid-perspective/components/CellContent.tsx+++ b/app/perspectives/grid-perspective/components/CellContent.tsx@@ -36,6 +36,7 @@ import TagContainer from '-/components/TagContainer';import i18n from '-/services/i18n';import { Tag } from '-/reducers/taglibrary';import PlatformIO from '-/services/platform-io';+import { AppConfig } from '-/config';const maxDescriptionPreviewLength = 100;@@ -392,7 +393,11 @@ const CellContent = (props: Props) => {}}onContextMenu={event => handleGridContextMenu(event, fsEntry)}onDoubleClick={event => handleGridCellDblClick(event, fsEntry)}- onClick={event => handleGridCellClick(event, fsEntry)}+ onClick={event =>+ AppConfig.isCordovaiOS // TODO DoubleClick not fired in Cordova IOS+ ? handleGridCellDblClick(event, fsEntry)+ : handleGridCellClick(event, fsEntry)+ }>{gridCell}</Paper>diff --git a/app/reducers/io-actions.ts b/app/reducers/io-actions.tsindex cdb5a69ed..d62075b97 100644--- a/app/reducers/io-actions.ts+++ b/app/reducers/io-actions.ts@@ -173,7 +173,7 @@ const actions = {targetPath: string,onUploadProgress?: (progress: Progress, response: any) => void) => (dispatch: (actions: Object) => void) => {- if (AppConfig.isElectron) {+ if (AppConfig.isElectron || AppConfig.isCordova) {const arrFiles = [];for (let i = 0; i < files.length; i += 1) {arrFiles.push(files[i].path);diff --git a/app/services/cordova-io.ts b/app/services/cordova-io.tsindex 114a95a71..4a0a61af0 100644--- a/app/services/cordova-io.ts+++ b/app/services/cordova-io.ts@@ -17,7 +17,7 @@*//* globals cordova */-+import path from 'path';import AppConfig from '../config';import { b64toBlob } from '../utils/misc';import {@@ -48,6 +48,21 @@ export default class CordovaIO {loadedSettings: any;loadedSettingsTags: any;+ cordovaFileError = {+ 1: 'NOT_FOUND_ERR',+ 2: 'SECURITY_ERR',+ 3: 'ABORT_ERR',+ 4: 'NOT_READABLE_ERR',+ 5: 'ENCODING_ERR',+ 6: 'NO_MODIFICATION_ALLOWED_ERR',+ 7: 'INVALID_STATE_ERR',+ 8: 'SYNTAX_ERR',+ 9: 'INVALID_MODIFICATION_ERR',+ 10: 'QUOTA_EXCEEDED_ERR',+ 11: 'TYPE_MISMATCH_ERR',+ 12: 'PATH_EXISTS_ERR'+ };+onDeviceReady = () => {console.log('Device Ready: ' + window.device.platform + ' - ' + window.device.version@@ -160,18 +175,23 @@ export default class CordovaIO {}};- getFileSystemPromise = (path: string): Promise<any> => {- console.log('getFileSystemPromise: ' + path);- if (path.indexOf(cordova.file.applicationDirectory) === 0) {+ getFileSystemPromise = (localPath: string): Promise<any> => {+ console.log('getFileSystemPromise: ' + localPath);+ if (+ localPath &&+ (localPath.indexOf(cordova.file.applicationDirectory) === 0 || localPath.startsWith('file:///'))+ ) {} else {- path = AppConfig.isCordovaiOS- ? cordova.file.documentsDirectory + '/' + path- : 'file:///' + path;+ localPath = AppConfig.isCordovaiOS+ ? path.join(cordova.file.documentsDirectory, localPath).replace(':/',':///')+ : 'file:///' + localPath;}- path = encodeURI(path);+ localPath = encodeURI(localPath);return new Promise((resolve, reject) => {- window.resolveLocalFileSystemURL(path, resolve, error => {- console.error('Error getting FileSystem: ' + JSON.stringify(error));+ window.resolveLocalFileSystemURL(localPath, resolve, error => {+ console.error(+ 'Error getting FileSystem: ' + this.cordovaFileError[error.code]+ ); //JSON.stringify(error));reject(error);});});@@ -358,14 +378,22 @@ export default class CordovaIO {// Platform APIgetDevicePaths = (): Object => {- const paths = {- Photos: 'sdcard/DCIM/',- Pictures: 'sdcard/Pictures/',- Download: 'sdcard/Download/',- Music: 'sdcard/Music/',- Movies: 'sdcard/Movies/',- SDCard: 'sdcard/'- };+ let paths;+ if (AppConfig.isCordovaiOS) {+ paths = {+ Documents: '/',+ iCloud: cordova.file.syncedDataDirectory+ };+ } else {+ paths = {+ Photos: 'sdcard/DCIM/',+ Pictures: 'sdcard/Pictures/',+ Download: 'sdcard/Download/',+ Music: 'sdcard/Music/',+ Movies: 'sdcard/Movies/',+ SDCard: cordova.file.externalRootDirectory // 'sdcard/'+ };+ }return paths;};diff --git a/cordova/package.json b/cordova/package.jsonindex 2c45fa4ae..3f9054019 100644--- a/cordova/package.json+++ b/cordova/package.json@@ -11,6 +11,7 @@"license": "Apache-2.0","dependencies": {"cordova-android": "^7.1.4",+ "cordova-ios": "^5.1.1","cordova-plugin-background-mode": "^0.7.3","cordova-plugin-camera": "4.1.0","cordova-plugin-device": "^2.0.3",@@ -34,7 +35,8 @@}},"platforms": [- "android"+ "android",+ "ios"]}}\ No newline at end of filediff --git a/cordova/platforms/ios/.gitignore b/cordova/platforms/ios/.gitignorenew file mode 100644index 000000000..cc76483f6--- /dev/null+++ b/cordova/platforms/ios/.gitignore@@ -0,0 +1,5 @@+*.mode1v3+*.perspectivev3+*.pbxuser+.DS_Store+build/diff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/CDVDebug.h b/cordova/platforms/ios/CordovaLib/Classes/Private/CDVDebug.hnew file mode 100644index 000000000..4a0d9f929--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/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__)diff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/CDVJSON_private.h b/cordova/platforms/ios/CordovaLib/Classes/Private/CDVJSON_private.hnew file mode 100644index 000000000..afb5cc661--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/CDVJSON_private.h@@ -0,0 +1,31 @@+/*+ 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 (CDVJSONSerializingPrivate)+- (NSString*)cdv_JSONString;+@end++@interface NSDictionary (CDVJSONSerializingPrivate)+- (NSString*)cdv_JSONString;+@end++@interface NSString (CDVJSONSerializingPrivate)+- (id)cdv_JSONObject;+- (id)cdv_JSONFragment;+@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/CDVJSON_private.m b/cordova/platforms/ios/CordovaLib/Classes/Private/CDVJSON_private.mnew file mode 100644index 000000000..175ed3984--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/CDVJSON_private.m@@ -0,0 +1,99 @@+/*+ 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_private.h"+#import <Foundation/NSJSONSerialization.h>++@implementation NSArray (CDVJSONSerializingPrivate)++- (NSString*)cdv_JSONString+{+ @autoreleasepool {+ NSError* error = nil;+ NSData* jsonData = [NSJSONSerialization dataWithJSONObject:self+ options:0+ error:&error];++ if (error != nil) {+ NSLog(@"NSArray JSONString error: %@", [error localizedDescription]);+ return nil;+ } else {+ return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];+ }+ }+}++@end++@implementation NSDictionary (CDVJSONSerializingPrivate)++- (NSString*)cdv_JSONString+{+ @autoreleasepool {+ 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 (CDVJSONSerializingPrivate)++- (id)cdv_JSONObject+{+ @autoreleasepool {+ NSError* error = nil;+ id object = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding]+ options:NSJSONReadingMutableContainers+ error:&error];++ if (error != nil) {+ NSLog(@"NSString JSONObject error: %@, Malformed Data: %@", [error localizedDescription], self);+ }++ return object;+ }+}++- (id)cdv_JSONFragment+{+ @autoreleasepool {+ NSError* error = nil;+ id object = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding]+ options:NSJSONReadingAllowFragments+ error:&error];++ if (error != nil) {+ NSLog(@"NSString JSONObject error: %@", [error localizedDescription]);+ }++ return object;+ }+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/CDVPlugin+Private.h b/cordova/platforms/ios/CordovaLib/Classes/Private/CDVPlugin+Private.hnew file mode 100644index 000000000..f88638c20--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/CDVPlugin+Private.h@@ -0,0 +1,24 @@+/*+ 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 CDVPlugin (Private)++- (instancetype)initWithWebViewEngine:(id <CDVWebViewEngineProtocol>)theWebViewEngine;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVGestureHandler/CDVGestureHandler.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVGestureHandler/CDVGestureHandler.hnew file mode 100644index 000000000..f39e066a2--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVGestureHandler/CDVGestureHandler.h@@ -0,0 +1,26 @@+/*+ 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 <Cordova/CDVPlugin.h>++@interface CDVGestureHandler : CDVPlugin++@property (nonatomic, strong) UILongPressGestureRecognizer* lpgr;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVGestureHandler/CDVGestureHandler.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVGestureHandler/CDVGestureHandler.mnew file mode 100644index 000000000..34ed46339--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVGestureHandler/CDVGestureHandler.m@@ -0,0 +1,70 @@+/*+ 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 "CDVGestureHandler.h"++@implementation CDVGestureHandler++- (void)pluginInitialize+{+ [self applyLongPressFix];+}++- (void)applyLongPressFix+{+ // You can't suppress 3D Touch and still have regular longpress,+ // so if this is false, let's not consider the 3D Touch setting at all.+ if (![self.commandDelegate.settings objectForKey:@"suppresseslongpressgesture"] ||+ ![[self.commandDelegate.settings objectForKey:@"suppresseslongpressgesture"] boolValue]) {+ return;+ }++ self.lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];+ self.lpgr.minimumPressDuration = 0.45f;+ self.lpgr.allowableMovement = 200.0f;++ // 0.45 is ok for 'regular longpress', 0.05-0.08 is required for '3D Touch longpress',+ // but since this will also kill onclick handlers (not ontouchend) it's optional.+ if ([self.commandDelegate.settings objectForKey:@"suppresses3dtouchgesture"] &&+ [[self.commandDelegate.settings objectForKey:@"suppresses3dtouchgesture"] boolValue]) {+ self.lpgr.minimumPressDuration = 0.15f;+ }++ NSArray *views = self.webView.subviews;+ if (views.count == 0) {+ NSLog(@"No webview subviews found, not applying the longpress fix.");+ return;+ }+ for (int i=0; i<views.count; i++) {+ UIView *webViewScrollView = views[i];+ if ([webViewScrollView isKindOfClass:[UIScrollView class]]) {+ NSArray *webViewScrollViewSubViews = webViewScrollView.subviews;+ UIView *browser = webViewScrollViewSubViews[0];+ [browser addGestureRecognizer:self.lpgr];+ break;+ }+ }+}++- (void)handleLongPressGestures:(UILongPressGestureRecognizer*)sender+{++}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVHandleOpenURL/CDVHandleOpenURL.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVHandleOpenURL/CDVHandleOpenURL.hnew file mode 100644index 000000000..37dab40b2--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVHandleOpenURL/CDVHandleOpenURL.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 <Cordova/CDVPlugin.h>++@interface CDVHandleOpenURL : CDVPlugin++@property (nonatomic, strong) NSURL* url;+@property (nonatomic, assign) BOOL pageLoaded;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVHandleOpenURL/CDVHandleOpenURL.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVHandleOpenURL/CDVHandleOpenURL.mnew file mode 100644index 000000000..400cb9dea--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVHandleOpenURL/CDVHandleOpenURL.m@@ -0,0 +1,86 @@+/*+ 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 "CDVHandleOpenURL.h"+#import <Cordova/CDV.h>++@implementation CDVHandleOpenURL++- (void)pluginInitialize+{+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationLaunchedWithUrl:) name:CDVPluginHandleOpenURLNotification object:nil];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationPageDidLoad:) name:CDVPageDidLoadNotification object:nil];+}++- (void)applicationLaunchedWithUrl:(NSNotification*)notification+{+ NSURL* url = [notification object];++ self.url = url;++ // warm-start handler+ if (self.pageLoaded) {+ [self processOpenUrl:self.url pageLoaded:YES];+ self.url = nil;+ }+}++- (void)applicationPageDidLoad:(NSNotification*)notification+{+ // cold-start handler++ self.pageLoaded = YES;++ if (self.url) {+ [self processOpenUrl:self.url pageLoaded:YES];+ self.url = nil;+ }+}++- (void)processOpenUrl:(NSURL*)url pageLoaded:(BOOL)pageLoaded+{+ __weak __typeof(self) weakSelf = self;++ dispatch_block_t handleOpenUrl = ^(void) {+ // calls into javascript global function 'handleOpenURL'+ NSString* jsString = [NSString stringWithFormat:@"document.addEventListener('deviceready',function(){if (typeof handleOpenURL === 'function') { handleOpenURL(\"%@\");}});", url.absoluteString];++ [weakSelf.webViewEngine evaluateJavaScript:jsString completionHandler:nil];+ };++ if (!pageLoaded) {+ NSString* jsString = @"document.readystate";+ [self.webViewEngine evaluateJavaScript:jsString+ completionHandler:^(id object, NSError* error) {+ if ((error == nil) && [object isKindOfClass:[NSString class]]) {+ NSString* readyState = (NSString*)object;+ BOOL ready = [readyState isEqualToString:@"loaded"] || [readyState isEqualToString:@"complete"];+ if (ready) {+ handleOpenUrl();+ } else {+ self.url = url;+ }+ }+ }];+ } else {+ handleOpenUrl();+ }+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.hnew file mode 100644index 000000000..a038dbdee--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.h@@ -0,0 +1,40 @@+/*+ 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 <Cordova/CDVPlugin.h>+#import <Cordova/CDVWhitelist.h>++#if WK_WEB_VIEW_ONLY+#define CDVWebViewNavigationType int+#else+#define CDVWebViewNavigationType UIWebViewNavigationType+#endif++typedef NS_ENUM(NSInteger, CDVIntentAndNavigationFilterValue) {+ CDVIntentAndNavigationFilterValueIntentAllowed,+ CDVIntentAndNavigationFilterValueNavigationAllowed,+ CDVIntentAndNavigationFilterValueNoneAllowed+};++@interface CDVIntentAndNavigationFilter : CDVPlugin <NSXMLParserDelegate>+++ (CDVIntentAndNavigationFilterValue) filterUrl:(NSURL*)url intentsWhitelist:(CDVWhitelist*)intentsWhitelist navigationsWhitelist:(CDVWhitelist*)navigationsWhitelist;++ (BOOL)shouldOverrideLoadWithRequest:(NSURLRequest*)request navigationType:(CDVWebViewNavigationType)navigationType filterValue:(CDVIntentAndNavigationFilterValue)filterValue;++ (BOOL)shouldOpenURLRequest:(NSURLRequest*)request navigationType:(CDVWebViewNavigationType)navigationType;+@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.mnew file mode 100644index 000000000..b656cd9eb--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.m@@ -0,0 +1,150 @@+/*+ 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 "CDVIntentAndNavigationFilter.h"+#import <Cordova/CDV.h>++@interface CDVIntentAndNavigationFilter ()++@property (nonatomic, readwrite) NSMutableArray* allowIntents;+@property (nonatomic, readwrite) NSMutableArray* allowNavigations;+@property (nonatomic, readwrite) CDVWhitelist* allowIntentsWhitelist;+@property (nonatomic, readwrite) CDVWhitelist* allowNavigationsWhitelist;++@end++@implementation CDVIntentAndNavigationFilter++#pragma mark NSXMLParserDelegate++- (void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict+{+ if ([elementName isEqualToString:@"allow-navigation"]) {+ [self.allowNavigations addObject:attributeDict[@"href"]];+ }+ if ([elementName isEqualToString:@"allow-intent"]) {+ [self.allowIntents addObject:attributeDict[@"href"]];+ }+}++- (void)parserDidStartDocument:(NSXMLParser*)parser+{+ // file: url <allow-navigations> are added by default+ self.allowNavigations = [[NSMutableArray alloc] initWithArray:@[ @"file://" ]];+ // no intents are added by default+ self.allowIntents = [[NSMutableArray alloc] init];+}++- (void)parserDidEndDocument:(NSXMLParser*)parser+{+ self.allowIntentsWhitelist = [[CDVWhitelist alloc] initWithArray:self.allowIntents];+ self.allowNavigationsWhitelist = [[CDVWhitelist alloc] initWithArray:self.allowNavigations];+}++- (void)parser:(NSXMLParser*)parser parseErrorOccurred:(NSError*)parseError+{+ NSAssert(NO, @"config.xml parse error line %ld col %ld", (long)[parser lineNumber], (long)[parser columnNumber]);+}++#pragma mark CDVPlugin++- (void)pluginInitialize+{+ if ([self.viewController isKindOfClass:[CDVViewController class]]) {+ [(CDVViewController*)self.viewController parseSettingsWithParser:self];+ }+}+++ (CDVIntentAndNavigationFilterValue) filterUrl:(NSURL*)url intentsWhitelist:(CDVWhitelist*)intentsWhitelist navigationsWhitelist:(CDVWhitelist*)navigationsWhitelist+{+ // a URL can only allow-intent OR allow-navigation, if both are specified,+ // only allow-navigation is allowed++ BOOL allowNavigationsPass = [navigationsWhitelist URLIsAllowed:url logFailure:NO];+ BOOL allowIntentPass = [intentsWhitelist URLIsAllowed:url logFailure:NO];++ if (allowNavigationsPass && allowIntentPass) {+ return CDVIntentAndNavigationFilterValueNavigationAllowed;+ } else if (allowNavigationsPass) {+ return CDVIntentAndNavigationFilterValueNavigationAllowed;+ } else if (allowIntentPass) {+ return CDVIntentAndNavigationFilterValueIntentAllowed;+ }++ return CDVIntentAndNavigationFilterValueNoneAllowed;+}++- (CDVIntentAndNavigationFilterValue) filterUrl:(NSURL*)url+{+ return [[self class] filterUrl:url intentsWhitelist:self.allowIntentsWhitelist navigationsWhitelist:self.allowNavigationsWhitelist];+}++#if WK_WEB_VIEW_ONLY+#define CDVWebViewNavigationTypeLinkClicked 0+#define CDVWebViewNavigationTypeOther 5+#else+#define CDVWebViewNavigationTypeLinkClicked UIWebViewNavigationTypeLinkClicked+#define CDVWebViewNavigationTypeOther UIWebViewNavigationTypeOther+#endif+++ (BOOL)shouldOpenURLRequest:(NSURLRequest*)request navigationType:(CDVWebViewNavigationType)navigationType+{+ return (CDVWebViewNavigationTypeLinkClicked == navigationType ||+ (CDVWebViewNavigationTypeOther == navigationType &&+ [[request.mainDocumentURL absoluteString] isEqualToString:[request.URL absoluteString]]+ )+ );+}+++ (BOOL)shouldOverrideLoadWithRequest:(NSURLRequest*)request navigationType:(CDVWebViewNavigationType)navigationType filterValue:(CDVIntentAndNavigationFilterValue)filterValue+{+ NSString* allowIntents_whitelistRejectionFormatString = @"ERROR External navigation rejected - <allow-intent> not set for url='%@'";+ NSString* allowNavigations_whitelistRejectionFormatString = @"ERROR Internal navigation rejected - <allow-navigation> not set for url='%@'";++ NSURL* url = [request URL];++ switch (filterValue) {+ case CDVIntentAndNavigationFilterValueNavigationAllowed:+ return YES;+ case CDVIntentAndNavigationFilterValueIntentAllowed:+ // only allow-intent if it's a UIWebViewNavigationTypeLinkClicked (anchor tag) OR+ // it's a UIWebViewNavigationTypeOther, and it's an internal link+ if ([[self class] shouldOpenURLRequest:request navigationType:navigationType]){+ [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];+ }++ // consume the request (i.e. no error) if it wasn't handled above+ return NO;+ case CDVIntentAndNavigationFilterValueNoneAllowed:+ // allow-navigation attempt failed for sure+ NSLog(@"%@", [NSString stringWithFormat:allowNavigations_whitelistRejectionFormatString, [url absoluteString]]);+ // anchor tag link means it was an allow-intent attempt that failed as well+ if (CDVWebViewNavigationTypeLinkClicked == navigationType) {+ NSLog(@"%@", [NSString stringWithFormat:allowIntents_whitelistRejectionFormatString, [url absoluteString]]);+ }+ return NO;+ }+}++- (BOOL)shouldOverrideLoadWithRequest:(NSURLRequest*)request navigationType:(CDVWebViewNavigationType)navigationType+{+ return [[self class] shouldOverrideLoadWithRequest:request navigationType:navigationType filterValue:[self filterUrl:request.URL]];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.hnew file mode 100644index 000000000..e93675ec2--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.h@@ -0,0 +1,50 @@+/*+ 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 <Cordova/CDVPlugin.h>++#define kCDVLocalStorageErrorDomain @"kCDVLocalStorageErrorDomain"+#define kCDVLocalStorageFileOperationError 1++@interface CDVLocalStorage : CDVPlugin++@property (nonatomic, readonly, strong) NSMutableArray* backupInfo;++- (BOOL)shouldBackup;+- (BOOL)shouldRestore;+- (void)backup:(CDVInvokedUrlCommand*)command;+- (void)restore:(CDVInvokedUrlCommand*)command;+++ (void)__fixupDatabaseLocationsWithBackupType:(NSString*)backupType;+// Visible for testing.++ (BOOL)__verifyAndFixDatabaseLocationsWithAppPlistDict:(NSMutableDictionary*)appPlistDict+ bundlePath:(NSString*)bundlePath+ fileManager:(NSFileManager*)fileManager;+@end++@interface CDVBackupInfo : NSObject++@property (nonatomic, copy) NSString* original;+@property (nonatomic, copy) NSString* backup;+@property (nonatomic, copy) NSString* label;++- (BOOL)shouldBackup;+- (BOOL)shouldRestore;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.mnew file mode 100644index 000000000..25c48536d--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.m@@ -0,0 +1,493 @@+/*+ 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 "CDVLocalStorage.h"+#import <Cordova/CDV.h>++@interface CDVLocalStorage ()++@property (nonatomic, readwrite, strong) NSMutableArray* backupInfo; // array of CDVBackupInfo objects+#if !WK_WEB_VIEW_ONLY+@property (nonatomic, readwrite, weak) id <UIWebViewDelegate> webviewDelegate;+#endif++@end++@implementation CDVLocalStorage++#if WK_WEB_VIEW_ONLY+@synthesize backupInfo;+#else+@synthesize backupInfo, webviewDelegate;+#endif++- (void)pluginInitialize+{+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResignActive)+ name:UIApplicationWillResignActiveNotification object:nil];+ BOOL cloudBackup = [@"cloud" isEqualToString : self.commandDelegate.settings[[@"BackupWebStorage" lowercaseString]]];++ self.backupInfo = [[self class] createBackupInfoWithCloudBackup:cloudBackup];+}++#pragma mark -+#pragma mark Plugin interface methods+++ (NSMutableArray*)createBackupInfoWithTargetDir:(NSString*)targetDir backupDir:(NSString*)backupDir targetDirNests:(BOOL)targetDirNests backupDirNests:(BOOL)backupDirNests rename:(BOOL)rename+{+ /*+ This "helper" does so much work and has so many options it would probably be clearer to refactor the whole thing.+ Basically, there are three database locations:++ 1. "Normal" dir -- LIB/<nested dires WebKit/LocalStorage etc>/<normal filenames>+ 2. "Caches" dir -- LIB/Caches/<normal filenames>+ 3. "Backup" dir -- DOC/Backups/<renamed filenames>++ And between these three, there are various migration paths, most of which only consider 2 of the 3, which is why this helper is based on 2 locations and has a notion of "direction".+ */+ NSMutableArray* backupInfo = [NSMutableArray arrayWithCapacity:3];++ NSString* original;+ NSString* backup;+ CDVBackupInfo* backupItem;++ // ////////// LOCALSTORAGE++ original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/file__0.localstorage":@"file__0.localstorage"];+ backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];+ backup = [backup stringByAppendingPathComponent:(rename ? @"localstorage.appdata.db" : @"file__0.localstorage")];++ backupItem = [[CDVBackupInfo alloc] init];+ backupItem.backup = backup;+ backupItem.original = original;+ backupItem.label = @"localStorage database";++ [backupInfo addObject:backupItem];++ // ////////// WEBSQL MAIN DB++ original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/Databases.db":@"Databases.db"];+ backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];+ backup = [backup stringByAppendingPathComponent:(rename ? @"websqlmain.appdata.db" : @"Databases.db")];++ backupItem = [[CDVBackupInfo alloc] init];+ backupItem.backup = backup;+ backupItem.original = original;+ backupItem.label = @"websql main database";++ [backupInfo addObject:backupItem];++ // ////////// WEBSQL DATABASES++ original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/file__0":@"file__0"];+ backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];+ backup = [backup stringByAppendingPathComponent:(rename ? @"websqldbs.appdata.db" : @"file__0")];++ backupItem = [[CDVBackupInfo alloc] init];+ backupItem.backup = backup;+ backupItem.original = original;+ backupItem.label = @"websql databases";++ [backupInfo addObject:backupItem];++ return backupInfo;+}+++ (NSMutableArray*)createBackupInfoWithCloudBackup:(BOOL)cloudBackup+{+ // create backup info from backup folder to caches folder+ NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];+ NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];+ NSString* cacheFolder = [appLibraryFolder stringByAppendingPathComponent:@"Caches"];+ NSString* backupsFolder = [appDocumentsFolder stringByAppendingPathComponent:@"Backups"];++ // create the backups folder, if needed+ [[NSFileManager defaultManager] createDirectoryAtPath:backupsFolder withIntermediateDirectories:YES attributes:nil error:nil];++ [self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:backupsFolder] skip:!cloudBackup];++ return [self createBackupInfoWithTargetDir:cacheFolder backupDir:backupsFolder targetDirNests:NO backupDirNests:NO rename:YES];+}+++ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL*)URL skip:(BOOL)skip+{+ NSError* error = nil;+ BOOL success = [URL setResourceValue:[NSNumber numberWithBool:skip] forKey:NSURLIsExcludedFromBackupKey error:&error];++ if (!success) {+ NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);+ }+ return success;+}+++ (BOOL)copyFrom:(NSString*)src to:(NSString*)dest error:(NSError* __autoreleasing*)error+{+ NSFileManager* fileManager = [NSFileManager defaultManager];++ if (![fileManager fileExistsAtPath:src]) {+ NSString* errorString = [NSString stringWithFormat:@"%@ file does not exist.", src];+ if (error != NULL) {+ (*error) = [NSError errorWithDomain:kCDVLocalStorageErrorDomain+ code:kCDVLocalStorageFileOperationError+ userInfo:[NSDictionary dictionaryWithObject:errorString+ forKey:NSLocalizedDescriptionKey]];+ }+ return NO;+ }++ // generate unique filepath in temp directory+ CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);+ CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef);+ NSString* tempBackup = [[NSTemporaryDirectory() stringByAppendingPathComponent:(__bridge NSString*)uuidString] stringByAppendingPathExtension:@"bak"];+ CFRelease(uuidString);+ CFRelease(uuidRef);++ BOOL destExists = [fileManager fileExistsAtPath:dest];++ // backup the dest+ if (destExists && ![fileManager copyItemAtPath:dest toPath:tempBackup error:error]) {+ return NO;+ }++ // remove the dest+ if (destExists && ![fileManager removeItemAtPath:dest error:error]) {+ return NO;+ }++ // create path to dest+ if (!destExists && ![fileManager createDirectoryAtPath:[dest stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:error]) {+ return NO;+ }++ // copy src to dest+ if ([fileManager copyItemAtPath:src toPath:dest error:error]) {+ // success - cleanup - delete the backup to the dest+ if ([fileManager fileExistsAtPath:tempBackup]) {+ [fileManager removeItemAtPath:tempBackup error:error];+ }+ return YES;+ } else {+ // failure - we restore the temp backup file to dest+ [fileManager copyItemAtPath:tempBackup toPath:dest error:error];+ // cleanup - delete the backup to the dest+ if ([fileManager fileExistsAtPath:tempBackup]) {+ [fileManager removeItemAtPath:tempBackup error:error];+ }+ return NO;+ }+}++- (BOOL)shouldBackup+{+ for (CDVBackupInfo* info in self.backupInfo) {+ if ([info shouldBackup]) {+ return YES;+ }+ }++ return NO;+}++- (BOOL)shouldRestore+{+ for (CDVBackupInfo* info in self.backupInfo) {+ if ([info shouldRestore]) {+ return YES;+ }+ }++ return NO;+}++/* copy from webkitDbLocation to persistentDbLocation */+- (void)backup:(CDVInvokedUrlCommand*)command+{+ NSString* callbackId = command.callbackId;++ NSError* __autoreleasing error = nil;+ CDVPluginResult* result = nil;+ NSString* message = nil;++ for (CDVBackupInfo* info in self.backupInfo) {+ if ([info shouldBackup]) {+ [[self class] copyFrom:info.original to:info.backup error:&error];++ if (callbackId) {+ if (error == nil) {+ message = [NSString stringWithFormat:@"Backed up: %@", info.label];+ NSLog(@"%@", message);++ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];+ } else {+ message = [NSString stringWithFormat:@"Error in CDVLocalStorage (%@) backup: %@", info.label, [error localizedDescription]];+ NSLog(@"%@", message);++ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];+ }+ }+ }+ }+}++/* copy from persistentDbLocation to webkitDbLocation */+- (void)restore:(CDVInvokedUrlCommand*)command+{+ NSError* __autoreleasing error = nil;+ CDVPluginResult* result = nil;+ NSString* message = nil;++ for (CDVBackupInfo* info in self.backupInfo) {+ if ([info shouldRestore]) {+ [[self class] copyFrom:info.backup to:info.original error:&error];++ if (error == nil) {+ message = [NSString stringWithFormat:@"Restored: %@", info.label];+ NSLog(@"%@", message);++ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ } else {+ message = [NSString stringWithFormat:@"Error in CDVLocalStorage (%@) restore: %@", info.label, [error localizedDescription]];+ NSLog(@"%@", message);++ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }+ }+ }+}+++ (void)__fixupDatabaseLocationsWithBackupType:(NSString*)backupType+{+ [self __verifyAndFixDatabaseLocations];+ [self __restoreLegacyDatabaseLocationsWithBackupType:backupType];+}+++ (void)__verifyAndFixDatabaseLocations+{+ NSBundle* mainBundle = [NSBundle mainBundle];+ NSString* bundlePath = [[mainBundle bundlePath] stringByDeletingLastPathComponent];+ NSString* bundleIdentifier = [[mainBundle infoDictionary] objectForKey:@"CFBundleIdentifier"];+ NSString* appPlistPath = [bundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"Library/Preferences/%@.plist", bundleIdentifier]];++ NSMutableDictionary* appPlistDict = [NSMutableDictionary dictionaryWithContentsOfFile:appPlistPath];+ BOOL modified = [[self class] __verifyAndFixDatabaseLocationsWithAppPlistDict:appPlistDict+ bundlePath:bundlePath+ fileManager:[NSFileManager defaultManager]];++ if (modified) {+ BOOL ok = [appPlistDict writeToFile:appPlistPath atomically:YES];+ [[NSUserDefaults standardUserDefaults] synchronize];+ NSLog(@"Fix applied for database locations?: %@", ok ? @"YES" : @"NO");+ }+}+++ (BOOL)__verifyAndFixDatabaseLocationsWithAppPlistDict:(NSMutableDictionary*)appPlistDict+ bundlePath:(NSString*)bundlePath+ fileManager:(NSFileManager*)fileManager+{+ NSString* libraryCaches = @"Library/Caches";+ NSString* libraryWebKit = @"Library/WebKit";++ NSArray* keysToCheck = [NSArray arrayWithObjects:+ @"WebKitLocalStorageDatabasePathPreferenceKey",+ @"WebDatabaseDirectory",+ nil];++ BOOL dirty = NO;++ for (NSString* key in keysToCheck) {+ NSString* value = [appPlistDict objectForKey:key];+ // verify key exists, and path is in app bundle, if not - fix+ if ((value != nil) && ![value hasPrefix:bundlePath]) {+ // the pathSuffix to use may be wrong - OTA upgrades from < 5.1 to 5.1 do keep the old path Library/WebKit,+ // while Xcode synced ones do change the storage location to Library/Caches+ NSString* newBundlePath = [bundlePath stringByAppendingPathComponent:libraryCaches];+ if (![fileManager fileExistsAtPath:newBundlePath]) {+ newBundlePath = [bundlePath stringByAppendingPathComponent:libraryWebKit];+ }+ [appPlistDict setValue:newBundlePath forKey:key];+ dirty = YES;+ }+ }++ return dirty;+}+++ (void)__restoreLegacyDatabaseLocationsWithBackupType:(NSString*)backupType+{+ // on iOS 6, if you toggle between cloud/local backup, you must move database locations. Default upgrade from iOS5.1 to iOS6 is like a toggle from local to cloud.+ NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];+ NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];++ NSMutableArray* backupInfo = [NSMutableArray arrayWithCapacity:0];++ if ([backupType isEqualToString:@"cloud"]) {+#ifdef DEBUG+ NSLog(@"\n\nStarted backup to iCloud! Please be careful."+ "\nYour application might be rejected by Apple if you store too much data."+ "\nFor more information please read \"iOS Data Storage Guidelines\" at:"+ "\nhttps://developer.apple.com/icloud/documentation/data-storage/"+ "\nTo disable web storage backup to iCloud, set the BackupWebStorage preference to \"local\" in the Cordova config.xml file\n\n");+#endif+ // We would like to restore old backups/caches databases to the new destination (nested in lib folder)+ [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:appLibraryFolder backupDir:[appDocumentsFolder stringByAppendingPathComponent:@"Backups"] targetDirNests:YES backupDirNests:NO rename:YES]];+ [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:appLibraryFolder backupDir:[appLibraryFolder stringByAppendingPathComponent:@"Caches"] targetDirNests:YES backupDirNests:NO rename:NO]];+ } else {+ // For ios6 local backups we also want to restore from Backups dir -- but we don't need to do that here, since the plugin will do that itself.+ [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:[appLibraryFolder stringByAppendingPathComponent:@"Caches"] backupDir:appLibraryFolder targetDirNests:NO backupDirNests:YES rename:NO]];+ }++ NSFileManager* manager = [NSFileManager defaultManager];++ for (CDVBackupInfo* info in backupInfo) {+ if ([manager fileExistsAtPath:info.backup]) {+ if ([info shouldRestore]) {+ NSLog(@"Restoring old webstorage backup. From: '%@' To: '%@'.", info.backup, info.original);+ [self copyFrom:info.backup to:info.original error:nil];+ }+ NSLog(@"Removing old webstorage backup: '%@'.", info.backup);+ [manager removeItemAtPath:info.backup error:nil];+ }+ }++ [[NSUserDefaults standardUserDefaults] setBool:[backupType isEqualToString:@"cloud"] forKey:@"WebKitStoreWebDataForBackup"];+}++#pragma mark -+#pragma mark Notification handlers++- (void)onResignActive+{+ UIDevice* device = [UIDevice currentDevice];+ NSNumber* exitsOnSuspend = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIApplicationExitsOnSuspend"];++ BOOL isMultitaskingSupported = [device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported];++ if (exitsOnSuspend == nil) { // if it's missing, it should be NO (i.e. multi-tasking on by default)+ exitsOnSuspend = [NSNumber numberWithBool:NO];+ }++ if (exitsOnSuspend) {+ [self backup:nil];+ } else if (isMultitaskingSupported) {+ __block UIBackgroundTaskIdentifier backgroundTaskID = UIBackgroundTaskInvalid;++ backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{+ [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];+ backgroundTaskID = UIBackgroundTaskInvalid;+ NSLog(@"Background task to backup WebSQL/LocalStorage expired.");+ }];+ CDVLocalStorage __weak* weakSelf = self;+ [self.commandDelegate runInBackground:^{+ [weakSelf backup:nil];++ [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];+ backgroundTaskID = UIBackgroundTaskInvalid;+ }];+ }+}++- (void)onAppTerminate+{+ [self onResignActive];+}++- (void)onReset+{+ [self restore:nil];+}++@end++#pragma mark -+#pragma mark CDVBackupInfo implementation++@implementation CDVBackupInfo++@synthesize original, backup, label;++- (BOOL)file:(NSString*)aPath isNewerThanFile:(NSString*)bPath+{+ NSFileManager* fileManager = [NSFileManager defaultManager];+ NSError* __autoreleasing error = nil;++ NSDictionary* aPathAttribs = [fileManager attributesOfItemAtPath:aPath error:&error];+ NSDictionary* bPathAttribs = [fileManager attributesOfItemAtPath:bPath error:&error];++ NSDate* aPathModDate = [aPathAttribs objectForKey:NSFileModificationDate];+ NSDate* bPathModDate = [bPathAttribs objectForKey:NSFileModificationDate];++ if ((nil == aPathModDate) && (nil == bPathModDate)) {+ return NO;+ }++ return [aPathModDate compare:bPathModDate] == NSOrderedDescending || bPathModDate == nil;+}++- (BOOL)item:(NSString*)aPath isNewerThanItem:(NSString*)bPath+{+ NSFileManager* fileManager = [NSFileManager defaultManager];++ BOOL aPathIsDir = NO, bPathIsDir = NO;+ BOOL aPathExists = [fileManager fileExistsAtPath:aPath isDirectory:&aPathIsDir];++ [fileManager fileExistsAtPath:bPath isDirectory:&bPathIsDir];++ if (!aPathExists) {+ return NO;+ }++ if (!(aPathIsDir && bPathIsDir)) { // just a file+ return [self file:aPath isNewerThanFile:bPath];+ }++ // essentially we want rsync here, but have to settle for our poor man's implementation+ // we get the files in aPath, and see if it is newer than the file in bPath+ // (it is newer if it doesn't exist in bPath) if we encounter the FIRST file that is newer,+ // we return YES+ NSDirectoryEnumerator* directoryEnumerator = [fileManager enumeratorAtPath:aPath];+ NSString* path;++ while ((path = [directoryEnumerator nextObject])) {+ NSString* aPathFile = [aPath stringByAppendingPathComponent:path];+ NSString* bPathFile = [bPath stringByAppendingPathComponent:path];++ BOOL isNewer = [self file:aPathFile isNewerThanFile:bPathFile];+ if (isNewer) {+ return YES;+ }+ }++ return NO;+}++- (BOOL)shouldBackup+{+ return [self item:self.original isNewerThanItem:self.backup];+}++- (BOOL)shouldRestore+{+ return [self item:self.backup isNewerThanItem:self.original];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLogger/CDVLogger.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLogger/CDVLogger.hnew file mode 100644index 000000000..7cfb3063e--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLogger/CDVLogger.h@@ -0,0 +1,26 @@+/*+ 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 <Cordova/CDVPlugin.h>++@interface CDVLogger : CDVPlugin++- (void)logLevel:(CDVInvokedUrlCommand*)command;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLogger/CDVLogger.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLogger/CDVLogger.mnew file mode 100644index 000000000..810caa560--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLogger/CDVLogger.m@@ -0,0 +1,37 @@+/*+ 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 "CDVLogger.h"++@implementation CDVLogger++/* log a message */+- (void)logLevel:(CDVInvokedUrlCommand*)command+{+ id level = [command argumentAtIndex:0];+ id message = [command argumentAtIndex:1];++ if ([level isEqualToString:@"LOG"]) {+ NSLog(@"%@", message);+ } else {+ NSLog(@"%@: %@", level, message);+ }+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.hnew file mode 100644index 000000000..8118d5f04--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.h@@ -0,0 +1,45 @@+/*+ 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.+ */++#if !WK_WEB_VIEW_ONLY++#import <UIKit/UIKit.h>+#import <Cordova/CDVAvailability.h>++/**+ * Distinguishes top-level navigations from sub-frame navigations.+ * shouldStartLoadWithRequest is called for every request, but didStartLoad+ * and didFinishLoad is called only for top-level navigations.+ * Relevant bug: CB-2389+ */+@interface CDVUIWebViewDelegate : NSObject <UIWebViewDelegate>{+ __weak NSObject <UIWebViewDelegate>* _delegate;+ NSInteger _loadCount;+ NSInteger _state;+ NSInteger _curLoadToken;+ NSInteger _loadStartPollCount;+}++- (id)initWithDelegate:(NSObject <UIWebViewDelegate>*)delegate;++- (BOOL)request:(NSURLRequest*)newRequest isEqualToRequestAfterStrippingFragments:(NSURLRequest*)originalRequest;++@end++#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.mnew file mode 100644index 000000000..ddef8be13--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.m@@ -0,0 +1,408 @@+/*+ 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.+ */++//+// Testing shows:+//+// In all cases, webView.request.URL is the previous page's URL (or empty) during the didStartLoad callback.+// When loading a page with a redirect:+// 1. shouldStartLoading (requestURL is target page)+// 2. didStartLoading+// 3. shouldStartLoading (requestURL is redirect target)+// 4. didFinishLoad (request.URL is redirect target)+//+// Note the lack of a second didStartLoading **+//+// When loading a page with iframes:+// 1. shouldStartLoading (requestURL is main page)+// 2. didStartLoading+// 3. shouldStartLoading (requestURL is one of the iframes)+// 4. didStartLoading+// 5. didFinishLoad+// 6. didFinishLoad+//+// Note there is no way to distinguish which didFinishLoad maps to which didStartLoad **+//+// Loading a page by calling window.history.go(-1):+// 1. didStartLoading+// 2. didFinishLoad+//+// Note the lack of a shouldStartLoading call **+// Actually - this is fixed on iOS6. iOS6 has a shouldStart. **+//+// Loading a page by calling location.reload()+// 1. shouldStartLoading+// 2. didStartLoading+// 3. didFinishLoad+//+// Loading a page with an iframe that fails to load:+// 1. shouldStart (main page)+// 2. didStart+// 3. shouldStart (iframe)+// 4. didStart+// 5. didFailWithError+// 6. didFinish+//+// Loading a page with an iframe that fails to load due to an invalid URL:+// 1. shouldStart (main page)+// 2. didStart+// 3. shouldStart (iframe)+// 5. didFailWithError+// 6. didFinish+//+// This case breaks our logic since there is a missing didStart. To prevent this,+// we check URLs in shouldStart and return NO if they are invalid.+//+// Loading a page with an invalid URL+// 1. shouldStart (main page)+// 2. didFailWithError+//+// TODO: Record order when page is re-navigated before the first navigation finishes.+//++#if !WK_WEB_VIEW_ONLY++#import "CDVUIWebViewDelegate.h"++// #define VerboseLog NSLog+#define VerboseLog(...) do { \+} while (0)++typedef enum {+ STATE_IDLE = 0,+ STATE_WAITING_FOR_LOAD_START = 1,+ STATE_WAITING_FOR_LOAD_FINISH = 2,+ STATE_IOS5_POLLING_FOR_LOAD_START = 3,+ STATE_IOS5_POLLING_FOR_LOAD_FINISH = 4,+ STATE_CANCELLED = 5+} State;++static NSString *stripFragment(NSString* url)+{+ NSRange r = [url rangeOfString:@"#"];++ if (r.location == NSNotFound) {+ return url;+ }+ return [url substringToIndex:r.location];+}++@implementation CDVUIWebViewDelegate++- (id)initWithDelegate:(NSObject <UIWebViewDelegate>*)delegate+{+ self = [super init];+ if (self != nil) {+ _delegate = delegate;+ _loadCount = -1;+ _state = STATE_IDLE;+ }+ return self;+}++- (BOOL)request:(NSURLRequest*)newRequest isEqualToRequestAfterStrippingFragments:(NSURLRequest*)originalRequest+{+ if (originalRequest.URL && newRequest.URL) {+ NSString* originalRequestUrl = [originalRequest.URL absoluteString];+ NSString* newRequestUrl = [newRequest.URL absoluteString];++ NSString* baseOriginalRequestUrl = stripFragment(originalRequestUrl);+ NSString* baseNewRequestUrl = stripFragment(newRequestUrl);+ return [baseOriginalRequestUrl isEqualToString:baseNewRequestUrl];+ }++ return NO;+}++- (BOOL)isPageLoaded:(UIWebView*)webView+{+ NSString* readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];++ return [readyState isEqualToString:@"loaded"] || [readyState isEqualToString:@"complete"];+}++- (BOOL)isJsLoadTokenSet:(UIWebView*)webView+{+ NSString* loadToken = [webView stringByEvaluatingJavaScriptFromString:@"window.__cordovaLoadToken"];++ return [[NSString stringWithFormat:@"%ld", (long)_curLoadToken] isEqualToString:loadToken];+}++- (void)setLoadToken:(UIWebView*)webView+{+ _curLoadToken += 1;+ [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.__cordovaLoadToken=%ld", (long)_curLoadToken]];+}++- (NSString*)evalForCurrentURL:(UIWebView*)webView+{+ return [webView stringByEvaluatingJavaScriptFromString:@"location.href"];+}++- (void)pollForPageLoadStart:(UIWebView*)webView+{+ if (_state != STATE_IOS5_POLLING_FOR_LOAD_START) {+ return;+ }+ if (![self isJsLoadTokenSet:webView]) {+ VerboseLog(@"Polled for page load start. result = YES!");+ _state = STATE_IOS5_POLLING_FOR_LOAD_FINISH;+ [self setLoadToken:webView];+ if ([_delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {+ [_delegate webViewDidStartLoad:webView];+ }+ [self pollForPageLoadFinish:webView];+ } else {+ VerboseLog(@"Polled for page load start. result = NO");+ // Poll only for 1 second, and then fall back on checking only when delegate methods are called.+ ++_loadStartPollCount;+ if (_loadStartPollCount < (1000 * .05)) {+ [self performSelector:@selector(pollForPageLoadStart:) withObject:webView afterDelay:.05];+ }+ }+}++- (void)pollForPageLoadFinish:(UIWebView*)webView+{+ if (_state != STATE_IOS5_POLLING_FOR_LOAD_FINISH) {+ return;+ }+ if ([self isPageLoaded:webView]) {+ VerboseLog(@"Polled for page load finish. result = YES!");+ _state = STATE_IDLE;+ if ([_delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {+ [_delegate webViewDidFinishLoad:webView];+ }+ } else {+ VerboseLog(@"Polled for page load finish. result = NO");+ [self performSelector:@selector(pollForPageLoadFinish:) withObject:webView afterDelay:.05];+ }+}++- (BOOL)shouldLoadRequest:(NSURLRequest*)request+{+ NSString* scheme = [[request URL] scheme];+ NSArray* allowedSchemes = [NSArray arrayWithObjects:@"mailto",@"tel",@"blob",@"sms",@"data", nil];+ if([allowedSchemes containsObject:scheme]) {+ return YES;+ }+ else {+ return [NSURLConnection canHandleRequest:request];+ }+}++- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType+{+ BOOL shouldLoad = YES;++ if ([_delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {+ shouldLoad = [_delegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];+ }++ VerboseLog(@"webView shouldLoad=%d (before) state=%d loadCount=%d URL=%@", shouldLoad, _state, _loadCount, request.URL);++ if (shouldLoad) {+ // When devtools refresh occurs, it blindly uses the same request object. If a history.replaceState() has occured, then+ // mainDocumentURL != URL even though it's a top-level navigation.+ BOOL isDevToolsRefresh = (request == webView.request);+ BOOL isTopLevelNavigation = isDevToolsRefresh || [request.URL isEqual:[request mainDocumentURL]];+ if (isTopLevelNavigation) {+ // Ignore hash changes that don't navigate to a different page.+ // webView.request does actually update when history.replaceState() gets called.+ if ([self request:request isEqualToRequestAfterStrippingFragments:webView.request]) {+ NSString* prevURL = [self evalForCurrentURL:webView];+ if ([prevURL isEqualToString:[request.URL absoluteString]]) {+ VerboseLog(@"Page reload detected.");+ } else {+ VerboseLog(@"Detected hash change shouldLoad");+ return shouldLoad;+ }+ }++ switch (_state) {+ case STATE_WAITING_FOR_LOAD_FINISH:+ // Redirect case.+ // We expect loadCount == 1.+ if (_loadCount != 1) {+ NSLog(@"CDVWebViewDelegate: Detected redirect when loadCount=%ld", (long)_loadCount);+ }+ break;++ case STATE_IDLE:+ case STATE_IOS5_POLLING_FOR_LOAD_START:+ case STATE_CANCELLED:+ // Page navigation start.+ _loadCount = 0;+ _state = STATE_WAITING_FOR_LOAD_START;+ break;++ default:+ {+ NSString* description = [NSString stringWithFormat:@"CDVWebViewDelegate: Navigation started when state=%ld", (long)_state];+ NSLog(@"%@", description);+ _loadCount = 0;+ _state = STATE_WAITING_FOR_LOAD_START;++ NSDictionary* errorDictionary = @{NSLocalizedDescriptionKey : description};+ NSError* error = [[NSError alloc] initWithDomain:@"CDVUIWebViewDelegate" code:1 userInfo:errorDictionary];+ [self webView:webView didFailLoadWithError:error];+ }+ }+ } else {+ // Deny invalid URLs so that we don't get the case where we go straight from+ // webViewShouldLoad -> webViewDidFailLoad (messes up _loadCount).+ shouldLoad = shouldLoad && [self shouldLoadRequest:request];+ }+ VerboseLog(@"webView shouldLoad=%d (after) isTopLevelNavigation=%d state=%d loadCount=%d", shouldLoad, isTopLevelNavigation, _state, _loadCount);+ }+ return shouldLoad;+}++- (void)webViewDidStartLoad:(UIWebView*)webView+{+ VerboseLog(@"webView didStartLoad (before). state=%d loadCount=%d", _state, _loadCount);+ BOOL fireCallback = NO;+ switch (_state) {+ case STATE_IDLE:+ break;++ case STATE_CANCELLED:+ fireCallback = YES;+ _state = STATE_WAITING_FOR_LOAD_FINISH;+ _loadCount += 1;+ break;++ case STATE_WAITING_FOR_LOAD_START:+ if (_loadCount != 0) {+ NSLog(@"CDVWebViewDelegate: Unexpected loadCount in didStart. count=%ld", (long)_loadCount);+ }+ fireCallback = YES;+ _state = STATE_WAITING_FOR_LOAD_FINISH;+ _loadCount = 1;+ break;++ case STATE_WAITING_FOR_LOAD_FINISH:+ _loadCount += 1;+ break;++ case STATE_IOS5_POLLING_FOR_LOAD_START:+ [self pollForPageLoadStart:webView];+ break;++ case STATE_IOS5_POLLING_FOR_LOAD_FINISH:+ [self pollForPageLoadFinish:webView];+ break;++ default:+ NSLog(@"CDVWebViewDelegate: Unexpected didStart with state=%ld loadCount=%ld", (long)_state, (long)_loadCount);+ }+ VerboseLog(@"webView didStartLoad (after). state=%d loadCount=%d fireCallback=%d", _state, _loadCount, fireCallback);+ if (fireCallback && [_delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {+ [_delegate webViewDidStartLoad:webView];+ }+}++- (void)webViewDidFinishLoad:(UIWebView*)webView+{+ VerboseLog(@"webView didFinishLoad (before). state=%d loadCount=%d", _state, _loadCount);+ BOOL fireCallback = NO;+ switch (_state) {+ case STATE_IDLE:+ break;++ case STATE_WAITING_FOR_LOAD_START:+ NSLog(@"CDVWebViewDelegate: Unexpected didFinish while waiting for load start.");+ break;++ case STATE_WAITING_FOR_LOAD_FINISH:+ // fix call loadRequest multiple times just callback webViewDidFinishLoad once time in iOS 12+ if (@available(iOS 12.0, *)) {+ fireCallback = YES;+ } else {+ if (_loadCount == 1) {+ fireCallback = YES;+ _state = STATE_IDLE;+ }+ }+ _loadCount -= 1;+ break;++ case STATE_IOS5_POLLING_FOR_LOAD_START:+ [self pollForPageLoadStart:webView];+ break;++ case STATE_IOS5_POLLING_FOR_LOAD_FINISH:+ [self pollForPageLoadFinish:webView];+ break;+ }+ VerboseLog(@"webView didFinishLoad (after). state=%d loadCount=%d fireCallback=%d", _state, _loadCount, fireCallback);+ if (fireCallback && [_delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {+ [_delegate webViewDidFinishLoad:webView];+ }+}++- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error+{+ VerboseLog(@"webView didFailLoad (before). state=%d loadCount=%d", _state, _loadCount);+ BOOL fireCallback = NO;++ switch (_state) {+ case STATE_IDLE:+ break;++ case STATE_WAITING_FOR_LOAD_START:+ if ([error code] == NSURLErrorCancelled) {+ _state = STATE_CANCELLED;+ } else {+ _state = STATE_IDLE;+ }+ fireCallback = YES;+ break;++ case STATE_WAITING_FOR_LOAD_FINISH:+ if ([error code] != NSURLErrorCancelled) {+ if (_loadCount == 1) {+ _state = STATE_IDLE;+ fireCallback = YES;+ }+ _loadCount = -1;+ } else {+ fireCallback = YES;+ _state = STATE_CANCELLED;+ _loadCount -= 1;+ }+ break;++ case STATE_IOS5_POLLING_FOR_LOAD_START:+ [self pollForPageLoadStart:webView];+ break;++ case STATE_IOS5_POLLING_FOR_LOAD_FINISH:+ [self pollForPageLoadFinish:webView];+ break;+ }+ VerboseLog(@"webView didFailLoad (after). state=%d loadCount=%d, fireCallback=%d", _state, _loadCount, fireCallback);+ if (fireCallback && [_delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {+ [_delegate webView:webView didFailLoadWithError:error];+ }+}++@end++#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.hnew file mode 100644index 000000000..9b4bf187a--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.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 <Cordova/CDVPlugin.h>+#import <Cordova/CDVWebViewEngineProtocol.h>++@interface CDVUIWebViewEngine : CDVPlugin <CDVWebViewEngineProtocol>++#if !WK_WEB_VIEW_ONLY+@property (nonatomic, strong, readonly) id <UIWebViewDelegate> uiWebViewDelegate;+#endif++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.mnew file mode 100644index 000000000..e5767b5be--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.m@@ -0,0 +1,206 @@+/*+ 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.+ */++#if !WK_WEB_VIEW_ONLY++#import "CDVUIWebViewEngine.h"+#import "CDVUIWebViewDelegate.h"+#import "CDVUIWebViewNavigationDelegate.h"+#import "NSDictionary+CordovaPreferences.h"++#import <objc/message.h>++@interface CDVUIWebViewEngine ()++@property (nonatomic, strong, readwrite) UIView* engineWebView;+@property (nonatomic, strong, readwrite) id <UIWebViewDelegate> uiWebViewDelegate;+@property (nonatomic, strong, readwrite) CDVUIWebViewNavigationDelegate* navWebViewDelegate;++@end++@implementation CDVUIWebViewEngine++@synthesize engineWebView = _engineWebView;++- (instancetype)initWithFrame:(CGRect)frame+{+ self = [super init];+ if (self) {+ self.engineWebView = [[UIWebView alloc] initWithFrame:frame];+ NSLog(@"Using UIWebView");+ }++ return self;+}++- (void)pluginInitialize+{+ // viewController would be available now. we attempt to set all possible delegates to it, by default++ UIWebView* uiWebView = (UIWebView*)_engineWebView;++ if ([self.viewController conformsToProtocol:@protocol(UIWebViewDelegate)]) {+ self.uiWebViewDelegate = [[CDVUIWebViewDelegate alloc] initWithDelegate:(id <UIWebViewDelegate>)self.viewController];+ uiWebView.delegate = self.uiWebViewDelegate;+ } else {+ self.navWebViewDelegate = [[CDVUIWebViewNavigationDelegate alloc] initWithEnginePlugin:self];+ self.uiWebViewDelegate = [[CDVUIWebViewDelegate alloc] initWithDelegate:self.navWebViewDelegate];+ uiWebView.delegate = self.uiWebViewDelegate;+ }++ [self updateSettings:self.commandDelegate.settings];+}++- (void)evaluateJavaScript:(NSString*)javaScriptString completionHandler:(void (^)(id, NSError*))completionHandler+{+ NSString* ret = [(UIWebView*)_engineWebView stringByEvaluatingJavaScriptFromString:javaScriptString];++ if (completionHandler) {+ completionHandler(ret, nil);+ }+}++- (id)loadRequest:(NSURLRequest*)request+{+ [(UIWebView*)_engineWebView loadRequest:request];+ return nil;+}++- (id)loadHTMLString:(NSString*)string baseURL:(NSURL*)baseURL+{+ [(UIWebView*)_engineWebView loadHTMLString:string baseURL:baseURL];+ return nil;+}++- (NSURL*)URL+{+ return [[(UIWebView*)_engineWebView request] URL];+}++- (BOOL) canLoadRequest:(NSURLRequest*)request+{+ return (request != nil);+}++- (void)updateSettings:(NSDictionary*)settings+{+ UIWebView* uiWebView = (UIWebView*)_engineWebView;++ uiWebView.scalesPageToFit = [settings cordovaBoolSettingForKey:@"EnableViewportScale" defaultValue:NO];+ uiWebView.allowsInlineMediaPlayback = [settings cordovaBoolSettingForKey:@"AllowInlineMediaPlayback" defaultValue:NO];+ uiWebView.mediaPlaybackRequiresUserAction = [settings cordovaBoolSettingForKey:@"MediaPlaybackRequiresUserAction" defaultValue:YES];+ uiWebView.mediaPlaybackAllowsAirPlay = [settings cordovaBoolSettingForKey:@"MediaPlaybackAllowsAirPlay" defaultValue:YES];+ uiWebView.keyboardDisplayRequiresUserAction = [settings cordovaBoolSettingForKey:@"KeyboardDisplayRequiresUserAction" defaultValue:YES];+ uiWebView.suppressesIncrementalRendering = [settings cordovaBoolSettingForKey:@"SuppressesIncrementalRendering" defaultValue:NO];+ uiWebView.gapBetweenPages = [settings cordovaFloatSettingForKey:@"GapBetweenPages" defaultValue:0.0];+ uiWebView.pageLength = [settings cordovaFloatSettingForKey:@"PageLength" defaultValue:0.0];++ id prefObj = nil;++ // By default, DisallowOverscroll is false (thus bounce is allowed)+ BOOL bounceAllowed = !([settings cordovaBoolSettingForKey:@"DisallowOverscroll" defaultValue:NO]);++ // prevent webView from bouncing+ if (!bounceAllowed) {+ if ([uiWebView respondsToSelector:@selector(scrollView)]) {+ ((UIScrollView*)[uiWebView scrollView]).bounces = NO;+ } else {+ for (id subview in self.webView.subviews) {+ if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {+ ((UIScrollView*)subview).bounces = NO;+ }+ }+ }+ }++ NSString* decelerationSetting = [settings cordovaSettingForKey:@"UIWebViewDecelerationSpeed"];+ if (![@"fast" isEqualToString:decelerationSetting]) {+ [uiWebView.scrollView setDecelerationRate:UIScrollViewDecelerationRateNormal];+ }++ NSInteger paginationBreakingMode = 0; // default - UIWebPaginationBreakingModePage+ prefObj = [settings cordovaSettingForKey:@"PaginationBreakingMode"];+ if (prefObj != nil) {+ NSArray* validValues = @[@"page", @"column"];+ NSString* prefValue = [validValues objectAtIndex:0];++ if ([prefObj isKindOfClass:[NSString class]]) {+ prefValue = prefObj;+ }++ paginationBreakingMode = [validValues indexOfObject:[prefValue lowercaseString]];+ if (paginationBreakingMode == NSNotFound) {+ paginationBreakingMode = 0;+ }+ }+ uiWebView.paginationBreakingMode = paginationBreakingMode;++ NSInteger paginationMode = 0; // default - UIWebPaginationModeUnpaginated+ prefObj = [settings cordovaSettingForKey:@"PaginationMode"];+ if (prefObj != nil) {+ NSArray* validValues = @[@"unpaginated", @"lefttoright", @"toptobottom", @"bottomtotop", @"righttoleft"];+ NSString* prefValue = [validValues objectAtIndex:0];++ if ([prefObj isKindOfClass:[NSString class]]) {+ prefValue = prefObj;+ }++ paginationMode = [validValues indexOfObject:[prefValue lowercaseString]];+ if (paginationMode == NSNotFound) {+ paginationMode = 0;+ }+ }+ uiWebView.paginationMode = paginationMode;+}++- (void)updateWithInfo:(NSDictionary*)info+{+ UIWebView* uiWebView = (UIWebView*)_engineWebView;++ id <UIWebViewDelegate> uiWebViewDelegate = [info objectForKey:kCDVWebViewEngineUIWebViewDelegate];+ NSDictionary* settings = [info objectForKey:kCDVWebViewEngineWebViewPreferences];++ if (uiWebViewDelegate &&+ [uiWebViewDelegate conformsToProtocol:@protocol(UIWebViewDelegate)]) {+ self.uiWebViewDelegate = [[CDVUIWebViewDelegate alloc] initWithDelegate:(id <UIWebViewDelegate>)uiWebViewDelegate];+ uiWebView.delegate = self.uiWebViewDelegate;+ }++ if (settings && [settings isKindOfClass:[NSDictionary class]]) {+ [self updateSettings:settings];+ }+}++// This forwards the methods that are in the header that are not implemented here.+// Both WKWebView and UIWebView implement the below:+// loadHTMLString:baseURL:+// loadRequest:+- (id)forwardingTargetForSelector:(SEL)aSelector+{+ return _engineWebView;+}++- (UIView*)webView+{+ return self.engineWebView;+}++@end++#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.hnew file mode 100644index 000000000..9b9b31f1f--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.h@@ -0,0 +1,33 @@+/*+ 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.+ */++#if !WK_WEB_VIEW_ONLY++#import <UIKit/UIKit.h>+#import "CDVUIWebViewEngine.h"++@interface CDVUIWebViewNavigationDelegate : NSObject <UIWebViewDelegate>++@property (nonatomic, weak) CDVPlugin* enginePlugin;++- (instancetype)initWithEnginePlugin:(CDVPlugin*)enginePlugin;++@end++#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.mnew file mode 100644index 000000000..a918e2d7b--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.m@@ -0,0 +1,157 @@+/*+ 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.+ */++#if !WK_WEB_VIEW_ONLY++#import "CDVUIWebViewNavigationDelegate.h"+#import <Cordova/CDVViewController.h>+#import <Cordova/CDVCommandDelegateImpl.h>+#import <Cordova/CDVUserAgentUtil.h>+#import <objc/message.h>++@implementation CDVUIWebViewNavigationDelegate++- (instancetype)initWithEnginePlugin:(CDVPlugin*)theEnginePlugin+{+ self = [super init];+ if (self) {+ self.enginePlugin = theEnginePlugin;+ }++ return self;+}++/**+ When web application loads Add stuff to the DOM, mainly the user-defined settings from the Settings.plist file, and+ the device's data such as device ID, platform version, etc.+ */+- (void)webViewDidStartLoad:(UIWebView*)theWebView+{+ NSLog(@"Resetting plugins due to page load.");+ CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;++ [vc.commandQueue resetRequestId];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginResetNotification object:self.enginePlugin.webView]];+}++/**+ Called when the webview finishes loading. This stops the activity view.+ */+- (void)webViewDidFinishLoad:(UIWebView*)theWebView+{+ NSLog(@"Finished load of: %@", theWebView.request.URL);+ CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;++ // It's safe to release the lock even if this is just a sub-frame that's finished loading.+ [CDVUserAgentUtil releaseLock:vc.userAgentLockToken];++ /*+ * Hide the Top Activity THROBBER in the Battery Bar+ */+ [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];++ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPageDidLoadNotification object:self.enginePlugin.webView]];+}++- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error+{+ CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;++ [CDVUserAgentUtil releaseLock:vc.userAgentLockToken];++ NSString* message = [NSString stringWithFormat:@"Failed to load webpage with error: %@", [error localizedDescription]];+ NSLog(@"%@", message);++ NSURL* errorUrl = vc.errorURL;+ if (errorUrl) {+ errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [message stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]] relativeToURL:errorUrl];+ NSLog(@"%@", [errorUrl absoluteString]);+ if(error.code != NSURLErrorCancelled) {+ [theWebView loadRequest:[NSURLRequest requestWithURL:errorUrl]];+ }+ }+}++- (BOOL)defaultResourcePolicyForURL:(NSURL*)url+{+ /*+ * If a URL is being loaded that's a file url, just load it internally+ */+ if ([url isFileURL]) {+ return YES;+ }++ return NO;+}++- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType+{+ NSURL* url = [request URL];+ CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;++ /*+ * Execute any commands queued with cordova.exec() on the JS side.+ * The part of the URL after gap:// is irrelevant.+ */+ if ([[url scheme] isEqualToString:@"gap"]) {+ [vc.commandQueue fetchCommandsFromJs];+ // The delegate is called asynchronously in this case, so we don't have to use+ // flushCommandQueueWithDelayedJs (setTimeout(0)) as we do with hash changes.+ [vc.commandQueue executePending];+ return NO;+ }++ /*+ * Give plugins the chance to handle the url+ */+ BOOL anyPluginsResponded = NO;+ BOOL shouldAllowRequest = NO;++ for (NSString* pluginName in vc.pluginObjects) {+ CDVPlugin* plugin = [vc.pluginObjects objectForKey:pluginName];+ SEL selector = NSSelectorFromString(@"shouldOverrideLoadWithRequest:navigationType:");+ if ([plugin respondsToSelector:selector]) {+ anyPluginsResponded = YES;+ shouldAllowRequest = (((BOOL (*)(id, SEL, id, int))objc_msgSend)(plugin, selector, request, navigationType));+ if (!shouldAllowRequest) {+ break;+ }+ }+ }++ if (anyPluginsResponded) {+ return shouldAllowRequest;+ }++ /*+ * Handle all other types of urls (tel:, sms:), and requests to load a url in the main webview.+ */+ BOOL shouldAllowNavigation = [self defaultResourcePolicyForURL:url];+ if (shouldAllowNavigation) {+ return YES;+ } else {+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];+ }++ return NO;+}++@end++#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDV.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDV.hnew file mode 100644index 000000000..96d6efc8f--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDV.h@@ -0,0 +1,32 @@+/*+ 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 "CDVAvailability.h"+#import "CDVAvailabilityDeprecated.h"+#import "CDVAppDelegate.h"+#import "CDVPlugin.h"+#import "CDVPluginResult.h"+#import "CDVViewController.h"+#import "CDVCommandDelegate.h"+#import "CDVURLProtocol.h"+#import "CDVInvokedUrlCommand.h"+#import "CDVWhitelist.h"+#import "CDVScreenOrientationDelegate.h"+#import "CDVTimer.h"+#import "CDVUserAgentUtil.h"diff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.hnew file mode 100644index 000000000..de5b518f8--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.h@@ -0,0 +1,28 @@+/*+ 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 "CDVViewController.h"++@interface CDVAppDelegate : NSObject <UIApplicationDelegate>{}++@property (nonatomic, strong) IBOutlet UIWindow* window;+@property (nonatomic, strong) IBOutlet CDVViewController* viewController;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.mnew file mode 100644index 000000000..6a339f43f--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.m@@ -0,0 +1,118 @@+/*+ 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 "CDVAppDelegate.h"++@implementation CDVAppDelegate++@synthesize window, viewController;++- (id)init+{+ /** If you need to do any extra app-specific initialization, you can do it here+ * -jm+ **/+ NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];++ [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];++ int cacheSizeMemory = 8 * 1024 * 1024; // 8MB+ int cacheSizeDisk = 32 * 1024 * 1024; // 32MB+ NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];+ [NSURLCache setSharedURLCache:sharedCache];++ self = [super init];+ return self;+}++#pragma mark UIApplicationDelegate implementation++/**+ * This is main kick off after the app inits, the views and Settings are setup here. (preferred - iOS4 and up)+ */+- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions+{+ CGRect screenBounds = [[UIScreen mainScreen] bounds];++ self.window = [[UIWindow alloc] initWithFrame:screenBounds];+ self.window.autoresizesSubviews = YES;++ // only set if not already set in subclass+ if (self.viewController == nil) {+ self.viewController = [[CDVViewController alloc] init];+ }++ // Set your app's start page by setting the <content src='foo.html' /> tag in config.xml.+ // If necessary, uncomment the line below to override it.+ // self.viewController.startPage = @"index.html";++ // NOTE: To customize the view's frame size (which defaults to full screen), override+ // [self.viewController viewWillAppear:] in your view controller.++ self.window.rootViewController = self.viewController;+ [self.window makeKeyAndVisible];++ return YES;+}++// this happens while we are running ( in the background, or from within our own app )+// only valid if 40x-Info.plist specifies a protocol to handle+- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options+{+ if (!url) {+ return NO;+ }++ NSMutableDictionary * openURLData = [[NSMutableDictionary alloc] init];++ [openURLData setValue:url forKey:@"url"];++ if (options[UIApplicationOpenURLOptionsSourceApplicationKey]) {+ [openURLData setValue:options[UIApplicationOpenURLOptionsSourceApplicationKey] forKey:@"sourceApplication"];+ }++ if (options[UIApplicationOpenURLOptionsAnnotationKey]) {+ [openURLData setValue:options[UIApplicationOpenURLOptionsAnnotationKey] forKey:@"annotation"];+ }++ // all plugins will get the notification, and their handlers will be called+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification object:openURLData]];++ return YES;+}++#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000+- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window+#else //CB-12098. Defaults to UIInterfaceOrientationMask for iOS 9++- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window+#endif+{+ // iPhone doesn't support upside down by default, while the iPad does. Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).+ NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);++ return supportedInterfaceOrientations;+}++- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application+{+ [[NSURLCache sharedURLCache] removeAllCachedResponses];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailability.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailability.hnew file mode 100644index 000000000..00498ab5b--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailability.h@@ -0,0 +1,115 @@+/*+ 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 "CDVAvailabilityDeprecated.h"++#define __CORDOVA_IOS__++#define __CORDOVA_0_9_6 906+#define __CORDOVA_1_0_0 10000+#define __CORDOVA_1_1_0 10100+#define __CORDOVA_1_2_0 10200+#define __CORDOVA_1_3_0 10300+#define __CORDOVA_1_4_0 10400+#define __CORDOVA_1_4_1 10401+#define __CORDOVA_1_5_0 10500+#define __CORDOVA_1_6_0 10600+#define __CORDOVA_1_6_1 10601+#define __CORDOVA_1_7_0 10700+#define __CORDOVA_1_8_0 10800+#define __CORDOVA_1_8_1 10801+#define __CORDOVA_1_9_0 10900+#define __CORDOVA_2_0_0 20000+#define __CORDOVA_2_1_0 20100+#define __CORDOVA_2_2_0 20200+#define __CORDOVA_2_3_0 20300+#define __CORDOVA_2_4_0 20400+#define __CORDOVA_2_5_0 20500+#define __CORDOVA_2_6_0 20600+#define __CORDOVA_2_7_0 20700+#define __CORDOVA_2_8_0 20800+#define __CORDOVA_2_9_0 20900+#define __CORDOVA_3_0_0 30000+#define __CORDOVA_3_1_0 30100+#define __CORDOVA_3_2_0 30200+#define __CORDOVA_3_3_0 30300+#define __CORDOVA_3_4_0 30400+#define __CORDOVA_3_4_1 30401+#define __CORDOVA_3_5_0 30500+#define __CORDOVA_3_6_0 30600+#define __CORDOVA_3_7_0 30700+#define __CORDOVA_3_8_0 30800+#define __CORDOVA_3_9_0 30900+#define __CORDOVA_3_9_1 30901+#define __CORDOVA_3_9_2 30902+#define __CORDOVA_4_0_0 40000+#define __CORDOVA_4_0_1 40001+#define __CORDOVA_4_1_0 40100+#define __CORDOVA_4_1_1 40101+#define __CORDOVA_4_2_0 40200+#define __CORDOVA_4_2_1 40201+#define __CORDOVA_4_3_0 40300+#define __CORDOVA_4_3_1 40301+#define __CORDOVA_4_4_0 40400+#define __CORDOVA_4_5_0 40500+#define __CORDOVA_4_5_1 40501+#define __CORDOVA_4_5_2 40502+#define __CORDOVA_4_5_4 40504+#define __CORDOVA_5_0_0 50000+#define __CORDOVA_5_0_1 50001+#define __CORDOVA_5_1_0 50100+#define __CORDOVA_5_1_1 50101+/* coho:next-version,insert-before */+#define __CORDOVA_NA 99999 /* not available */++/*+ #if CORDOVA_VERSION_MIN_REQUIRED >= __CORDOVA_4_0_0+ // do something when its at least 4.0.0+ #else+ // do something else (non 4.0.0)+ #endif+ */+#ifndef CORDOVA_VERSION_MIN_REQUIRED+ /* coho:next-version-min-required,replace-after */+ #define CORDOVA_VERSION_MIN_REQUIRED __CORDOVA_5_1_1+#endif++/*+ Returns YES if it is at least version specified as NSString(X)+ Usage:+ if (IsAtLeastiOSVersion(@"5.1")) {+ // do something for iOS 5.1 or greater+ }+ */+#define IsAtLeastiOSVersion(X) ([[[UIDevice currentDevice] systemVersion] compare:X options:NSNumericSearch] != NSOrderedAscending)++/* Return the string version of the decimal version */+#define CDV_VERSION [NSString stringWithFormat:@"%d.%d.%d", \+ (CORDOVA_VERSION_MIN_REQUIRED / 10000), \+ (CORDOVA_VERSION_MIN_REQUIRED % 10000) / 100, \+ (CORDOVA_VERSION_MIN_REQUIRED % 10000) % 100]++// Enable this to log all exec() calls.+#define CDV_ENABLE_EXEC_LOGGING 0+#if CDV_ENABLE_EXEC_LOGGING+ #define CDV_EXEC_LOG NSLog+#else+ #define CDV_EXEC_LOG(...) do { \+} while (NO)+#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailabilityDeprecated.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailabilityDeprecated.hnew file mode 100644index 000000000..abf7a16ad--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailabilityDeprecated.h@@ -0,0 +1,26 @@+/*+ 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 <UIKit/UIKit.h>++#ifdef __clang__+ #define CDV_DEPRECATED(version, msg) __attribute__((deprecated("Deprecated in Cordova " #version ". " msg)))+#else+ #define CDV_DEPRECATED(version, msg) __attribute__((deprecated()))+#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegate.hnew file mode 100644index 000000000..efc9ad3f3--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegate.h@@ -0,0 +1,51 @@+/*+ 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 "CDVAvailability.h"+#import "CDVInvokedUrlCommand.h"++@class CDVPlugin;+@class CDVPluginResult;+@class CDVWhitelist;++typedef NSURL* (^ UrlTransformerBlock)(NSURL*);++@protocol CDVCommandDelegate <NSObject>++@property (nonatomic, readonly) NSDictionary* settings;+@property (nonatomic, copy) UrlTransformerBlock urlTransformer;++- (NSString*)pathForResource:(NSString*)resourcepath;+- (id)getCommandInstance:(NSString*)pluginName;++// Sends a plugin result to the JS. This is thread-safe.+- (void)sendPluginResult:(CDVPluginResult*)result callbackId:(NSString*)callbackId;+// Evaluates the given JS. This is thread-safe.+- (void)evalJs:(NSString*)js;+// Can be used to evaluate JS right away instead of scheduling it on the run-loop.+// This is required for dispatch resign and pause events, but should not be used+// without reason. Without the run-loop delay, alerts used in JS callbacks may result+// in dead-lock. This method must be called from the UI thread.+- (void)evalJs:(NSString*)js scheduledOnRunLoop:(BOOL)scheduledOnRunLoop;+// Runs the given block on a background thread using a shared thread-pool.+- (void)runInBackground:(void (^)(void))block;+// Returns the User-Agent of the associated UIWebView.+- (NSString*)userAgent;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.hnew file mode 100644index 000000000..053113431--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.h@@ -0,0 +1,36 @@+/*+ 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 <UIKit/UIKit.h>+#import "CDVCommandDelegate.h"++@class CDVViewController;+@class CDVCommandQueue;++@interface CDVCommandDelegateImpl : NSObject <CDVCommandDelegate>{+ @private+ __weak CDVViewController* _viewController;+ NSRegularExpression* _callbackIdPattern;+ @protected+ __weak CDVCommandQueue* _commandQueue;+ BOOL _delayResponses;+}+- (id)initWithViewController:(CDVViewController*)viewController;+- (void)flushCommandQueueWithDelayedJs;+@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.mnew file mode 100644index 000000000..effca6fd4--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.m@@ -0,0 +1,186 @@+/*+ 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 "CDVCommandDelegateImpl.h"+#import "CDVJSON_private.h"+#import "CDVCommandQueue.h"+#import "CDVPluginResult.h"+#import "CDVViewController.h"++@implementation CDVCommandDelegateImpl++@synthesize urlTransformer;++- (id)initWithViewController:(CDVViewController*)viewController+{+ self = [super init];+ if (self != nil) {+ _viewController = viewController;+ _commandQueue = _viewController.commandQueue;++ NSError* err = nil;+ _callbackIdPattern = [NSRegularExpression regularExpressionWithPattern:@"[^A-Za-z0-9._-]" options:0 error:&err];+ if (err != nil) {+ // Couldn't initialize Regex+ NSLog(@"Error: Couldn't initialize regex");+ _callbackIdPattern = nil;+ }+ }+ return self;+}++- (NSString*)pathForResource:(NSString*)resourcepath+{+ NSBundle* mainBundle = [NSBundle mainBundle];+ NSMutableArray* directoryParts = [NSMutableArray arrayWithArray:[resourcepath componentsSeparatedByString:@"/"]];+ NSString* filename = [directoryParts lastObject];++ [directoryParts removeLastObject];++ NSString* directoryPartsJoined = [directoryParts componentsJoinedByString:@"/"];+ NSString* directoryStr = _viewController.wwwFolderName;++ if ([directoryPartsJoined length] > 0) {+ directoryStr = [NSString stringWithFormat:@"%@/%@", _viewController.wwwFolderName, [directoryParts componentsJoinedByString:@"/"]];+ }++ return [mainBundle pathForResource:filename ofType:@"" inDirectory:directoryStr];+}++- (void)flushCommandQueueWithDelayedJs+{+ _delayResponses = YES;+ [_commandQueue executePending];+ _delayResponses = NO;+}++- (void)evalJsHelper2:(NSString*)js+{+ CDV_EXEC_LOG(@"Exec: evalling: %@", [js substringToIndex:MIN([js length], 160)]);+ [_viewController.webViewEngine evaluateJavaScript:js completionHandler:^(id obj, NSError* error) {+ // TODO: obj can be something other than string+ if ([obj isKindOfClass:[NSString class]]) {+ NSString* commandsJSON = (NSString*)obj;+ if ([commandsJSON length] > 0) {+ CDV_EXEC_LOG(@"Exec: Retrieved new exec messages by chaining.");+ }++ [self->_commandQueue enqueueCommandBatch:commandsJSON];+ [self->_commandQueue executePending];+ }+ }];+}++- (void)evalJsHelper:(NSString*)js+{+ // Cycle the run-loop before executing the JS.+ // For _delayResponses -+ // This ensures that we don't eval JS during the middle of an existing JS+ // function (possible since UIWebViewDelegate callbacks can be synchronous).+ // For !isMainThread -+ // It's a hard error to eval on the non-UI thread.+ // For !_commandQueue.currentlyExecuting -+ // This works around a bug where sometimes alerts() within callbacks can cause+ // dead-lock.+ // If the commandQueue is currently executing, then we know that it is safe to+ // execute the callback immediately.+ // Using (dispatch_get_main_queue()) does *not* fix deadlocks for some reason,+ // but performSelectorOnMainThread: does.+ if (_delayResponses || ![NSThread isMainThread] || !_commandQueue.currentlyExecuting) {+ [self performSelectorOnMainThread:@selector(evalJsHelper2:) withObject:js waitUntilDone:NO];+ } else {+ [self evalJsHelper2:js];+ }+}++- (BOOL)isValidCallbackId:(NSString*)callbackId+{+ if ((callbackId == nil) || (_callbackIdPattern == nil)) {+ return NO;+ }++ // Disallow if too long or if any invalid characters were found.+ if (([callbackId length] > 100) || [_callbackIdPattern firstMatchInString:callbackId options:0 range:NSMakeRange(0, [callbackId length])]) {+ return NO;+ }+ return YES;+}++- (void)sendPluginResult:(CDVPluginResult*)result callbackId:(NSString*)callbackId+{+ CDV_EXEC_LOG(@"Exec(%@): Sending result. Status=%@", callbackId, result.status);+ // This occurs when there is are no win/fail callbacks for the call.+ if ([@"INVALID" isEqualToString:callbackId]) {+ return;+ }+ // This occurs when the callback id is malformed.+ if (![self isValidCallbackId:callbackId]) {+ NSLog(@"Invalid callback id received by sendPluginResult");+ return;+ }+ int status = [result.status intValue];+ BOOL keepCallback = [result.keepCallback boolValue];+ NSString* argumentsAsJSON = [result argumentsAsJSON];+ BOOL debug = NO;++#ifdef DEBUG+ debug = YES;+#endif++ NSString* js = [NSString stringWithFormat:@"cordova.require('cordova/exec').nativeCallback('%@',%d,%@,%d, %d)", callbackId, status, argumentsAsJSON, keepCallback, debug];++ [self evalJsHelper:js];+}++- (void)evalJs:(NSString*)js+{+ [self evalJs:js scheduledOnRunLoop:YES];+}++- (void)evalJs:(NSString*)js scheduledOnRunLoop:(BOOL)scheduledOnRunLoop+{+ js = [NSString stringWithFormat:@"try{cordova.require('cordova/exec').nativeEvalAndFetch(function(){%@})}catch(e){console.log('exception nativeEvalAndFetch : '+e);};", js];+ if (scheduledOnRunLoop) {+ [self evalJsHelper:js];+ } else {+ [self evalJsHelper2:js];+ }+}++- (id)getCommandInstance:(NSString*)pluginName+{+ return [_viewController getCommandInstance:pluginName];+}++- (void)runInBackground:(void (^)(void))block+{+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);+}++- (NSString*)userAgent+{+ return [_viewController userAgent];+}++- (NSDictionary*)settings+{+ return _viewController.settings;+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandQueue.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandQueue.hnew file mode 100644index 000000000..cb7bd6e4b--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandQueue.h@@ -0,0 +1,39 @@+/*+ 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>++@class CDVInvokedUrlCommand;+@class CDVViewController;++@interface CDVCommandQueue : NSObject++@property (nonatomic, readonly) BOOL currentlyExecuting;++- (id)initWithViewController:(CDVViewController*)viewController;+- (void)dispose;++- (void)resetRequestId;+- (void)enqueueCommandBatch:(NSString*)batchJSON;++- (void)fetchCommandsFromJs;+- (void)executePending;+- (BOOL)execute:(CDVInvokedUrlCommand*)command;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandQueue.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandQueue.mnew file mode 100644index 000000000..b78ed833e--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandQueue.m@@ -0,0 +1,194 @@+/*+ 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 <objc/message.h>+#import "CDVCommandQueue.h"+#import "CDVViewController.h"+#import "CDVCommandDelegateImpl.h"+#import "CDVJSON_private.h"+#import "CDVDebug.h"++// Parse JS on the main thread if it's shorter than this.+static const NSInteger JSON_SIZE_FOR_MAIN_THREAD = 4 * 1024; // Chosen arbitrarily.+// Execute multiple commands in one go until this many seconds have passed.+static const double MAX_EXECUTION_TIME = .008; // Half of a 60fps frame.++@interface CDVCommandQueue () {+ NSInteger _lastCommandQueueFlushRequestId;+ __weak CDVViewController* _viewController;+ NSMutableArray* _queue;+ NSTimeInterval _startExecutionTime;+}+@end++@implementation CDVCommandQueue++- (BOOL)currentlyExecuting+{+ return _startExecutionTime > 0;+}++- (id)initWithViewController:(CDVViewController*)viewController+{+ self = [super init];+ if (self != nil) {+ _viewController = viewController;+ _queue = [[NSMutableArray alloc] init];+ }+ return self;+}++- (void)dispose+{+ // TODO(agrieve): Make this a zeroing weak ref once we drop support for 4.3.+ _viewController = nil;+}++- (void)resetRequestId+{+ _lastCommandQueueFlushRequestId = 0;+}++- (void)enqueueCommandBatch:(NSString*)batchJSON+{+ if ([batchJSON length] > 0) {+ NSMutableArray* commandBatchHolder = [[NSMutableArray alloc] init];+ [_queue addObject:commandBatchHolder];+ if ([batchJSON length] < JSON_SIZE_FOR_MAIN_THREAD) {+ [commandBatchHolder addObject:[batchJSON cdv_JSONObject]];+ } else {+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^() {+ NSMutableArray* result = [batchJSON cdv_JSONObject];+ @synchronized(commandBatchHolder) {+ [commandBatchHolder addObject:result];+ }+ [self performSelectorOnMainThread:@selector(executePending) withObject:nil waitUntilDone:NO];+ });+ }+ }+}++- (void)fetchCommandsFromJs+{+ __weak CDVCommandQueue* weakSelf = self;+ NSString* js = @"cordova.require('cordova/exec').nativeFetchMessages()";++ [_viewController.webViewEngine evaluateJavaScript:js+ completionHandler:^(id obj, NSError* error) {+ if ((error == nil) && [obj isKindOfClass:[NSString class]]) {+ NSString* queuedCommandsJSON = (NSString*)obj;+ CDV_EXEC_LOG(@"Exec: Flushed JS->native queue (hadCommands=%d).", [queuedCommandsJSON length] > 0);+ [weakSelf enqueueCommandBatch:queuedCommandsJSON];+ // this has to be called here now, because fetchCommandsFromJs is now async (previously: synchronous)+ [self executePending];+ }+ }];+}++- (void)executePending+{+ // Make us re-entrant-safe.+ if (_startExecutionTime > 0) {+ return;+ }+ @try {+ _startExecutionTime = [NSDate timeIntervalSinceReferenceDate];++ while ([_queue count] > 0) {+ NSMutableArray* commandBatchHolder = _queue[0];+ NSMutableArray* commandBatch = nil;+ @synchronized(commandBatchHolder) {+ // If the next-up command is still being decoded, wait for it.+ if ([commandBatchHolder count] == 0) {+ break;+ }+ commandBatch = commandBatchHolder[0];+ }++ while ([commandBatch count] > 0) {+ @autoreleasepool {+ // Execute the commands one-at-a-time.+ NSArray* jsonEntry = [commandBatch cdv_dequeue];+ if ([commandBatch count] == 0) {+ [_queue removeObjectAtIndex:0];+ }+ CDVInvokedUrlCommand* command = [CDVInvokedUrlCommand commandFromJson:jsonEntry];+ CDV_EXEC_LOG(@"Exec(%@): Calling %@.%@", command.callbackId, command.className, command.methodName);++ if (![self execute:command]) {+#ifdef DEBUG+ NSString* commandJson = [jsonEntry cdv_JSONString];+ static NSUInteger maxLogLength = 1024;+ NSString* commandString = ([commandJson length] > maxLogLength) ?+ [NSString stringWithFormat : @"%@[...]", [commandJson substringToIndex:maxLogLength]] :+ commandJson;++ DLog(@"FAILED pluginJSON = %@", commandString);+#endif+ }+ }++ // Yield if we're taking too long.+ if (([_queue count] > 0) && ([NSDate timeIntervalSinceReferenceDate] - _startExecutionTime > MAX_EXECUTION_TIME)) {+ [self performSelector:@selector(executePending) withObject:nil afterDelay:0];+ return;+ }+ }+ }+ } @finally+ {+ _startExecutionTime = 0;+ }+}++- (BOOL)execute:(CDVInvokedUrlCommand*)command+{+ if ((command.className == nil) || (command.methodName == nil)) {+ NSLog(@"ERROR: Classname and/or methodName not found for command.");+ return NO;+ }++ // Fetch an instance of this class+ CDVPlugin* obj = [_viewController.commandDelegate getCommandInstance:command.className];++ if (!([obj isKindOfClass:[CDVPlugin class]])) {+ NSLog(@"ERROR: Plugin '%@' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.", command.className);+ return NO;+ }+ BOOL retVal = YES;+ double started = [[NSDate date] timeIntervalSince1970] * 1000.0;+ // Find the proper selector to call.+ NSString* methodName = [NSString stringWithFormat:@"%@:", command.methodName];+ SEL normalSelector = NSSelectorFromString(methodName);+ if ([obj respondsToSelector:normalSelector]) {+ // [obj performSelector:normalSelector withObject:command];+ ((void (*)(id, SEL, id))objc_msgSend)(obj, normalSelector, command);+ } else {+ // There's no method to call, so throw an error.+ NSLog(@"ERROR: Method '%@' not defined in Plugin '%@'", methodName, command.className);+ retVal = NO;+ }+ double elapsed = [[NSDate date] timeIntervalSince1970] * 1000.0 - started;+ if (elapsed > 10) {+ NSLog(@"THREAD WARNING: ['%@'] took '%f' ms. Plugin should use a background thread.", command.className, elapsed);+ }+ return retVal;+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVConfigParser.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVConfigParser.hnew file mode 100644index 000000000..bae3d0f8b--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVConfigParser.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 CDVConfigParser : NSObject <NSXMLParserDelegate>+{+ NSString* featureName;+}++@property (nonatomic, readonly, strong) NSMutableDictionary* pluginsDict;+@property (nonatomic, readonly, strong) NSMutableDictionary* settings;+@property (nonatomic, readonly, strong) NSMutableArray* startupPluginNames;+@property (nonatomic, readonly, strong) NSString* startPage;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVConfigParser.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVConfigParser.mnew file mode 100644index 000000000..ab32b4a76--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVConfigParser.m@@ -0,0 +1,81 @@+/*+ 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"++@interface CDVConfigParser ()++@property (nonatomic, readwrite, strong) NSMutableDictionary* pluginsDict;+@property (nonatomic, readwrite, strong) NSMutableDictionary* settings;+@property (nonatomic, readwrite, strong) NSMutableArray* startupPluginNames;+@property (nonatomic, readwrite, strong) NSString* startPage;++@end++@implementation CDVConfigParser++@synthesize pluginsDict, settings, startPage, startupPluginNames;++- (id)init+{+ self = [super init];+ if (self != nil) {+ self.pluginsDict = [[NSMutableDictionary alloc] initWithCapacity:30];+ self.settings = [[NSMutableDictionary 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"] lowercaseString]] = 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:@"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 %ld col %ld", (long)[parser lineNumber], (long)[parser columnNumber]);+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVInvokedUrlCommand.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVInvokedUrlCommand.hnew file mode 100644index 000000000..993e0a285--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/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 <Foundation/Foundation.h>++@interface CDVInvokedUrlCommand : NSObject {+ NSString* _callbackId;+ NSString* _className;+ NSString* _methodName;+ NSArray* _arguments;+}++@property (nonatomic, readonly) NSArray* arguments;+@property (nonatomic, readonly) NSString* callbackId;+@property (nonatomic, readonly) NSString* className;+@property (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;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVInvokedUrlCommand.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVInvokedUrlCommand.mnew file mode 100644index 000000000..5b4281dfc--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVInvokedUrlCommand.m@@ -0,0 +1,116 @@+/*+ 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_private.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 alloc] initWithBase64EncodedString:data options:0]];+ }+}++- (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;+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin+Resources.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin+Resources.hnew file mode 100644index 000000000..cc43b16b7--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin+Resources.h@@ -0,0 +1,39 @@+/*+ 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 <UIKit/UIKit.h>+#import "CDVPlugin.h"++@interface CDVPlugin (CDVPluginResources)++/*+ This will return the localized string for a key in a .bundle that is named the same as your class+ For example, if your plugin class was called Foo, and you have a Spanish localized strings file, it will+ try to load the desired key from Foo.bundle/es.lproj/Localizable.strings+ */+- (NSString*)pluginLocalizedString:(NSString*)key;++/*+ This will return the image for a name in a .bundle that is named the same as your class+ For example, if your plugin class was called Foo, and you have an image called "bar",+ it will try to load the image from Foo.bundle/bar.png (and appropriately named retina versions)+ */+- (UIImage*)pluginImageResource:(NSString*)name;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin+Resources.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin+Resources.mnew file mode 100644index 000000000..56907385f--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin+Resources.m@@ -0,0 +1,38 @@+/*+ 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+Resources.h"++@implementation CDVPlugin (CDVPluginResources)++- (NSString*)pluginLocalizedString:(NSString*)key+{+ NSBundle* bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:NSStringFromClass([self class]) ofType:@"bundle"]];++ return [bundle localizedStringForKey:(key) value:nil table:nil];+}++- (UIImage*)pluginImageResource:(NSString*)name+{+ NSString* resourceIdentifier = [NSString stringWithFormat:@"%@.bundle/%@", NSStringFromClass([self class]), name];++ return [UIImage imageNamed:resourceIdentifier];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin.hnew file mode 100644index 000000000..0bdbbabbb--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin.h@@ -0,0 +1,74 @@+/*+ 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 <UIKit/UIKit.h>+#import "CDVPluginResult.h"+#import "NSMutableArray+QueueAdditions.h"+#import "CDVCommandDelegate.h"+#import "CDVWebViewEngineProtocol.h"++@interface UIView (org_apache_cordova_UIView_Extension)++@property (nonatomic, weak) UIScrollView* scrollView;++@end++extern NSString* const CDVPageDidLoadNotification;+extern NSString* const CDVPluginHandleOpenURLNotification;+extern NSString* const CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification;+extern NSString* const CDVPluginResetNotification;+extern NSString* const CDVViewWillAppearNotification;+extern NSString* const CDVViewDidAppearNotification;+extern NSString* const CDVViewWillDisappearNotification;+extern NSString* const CDVViewDidDisappearNotification;+extern NSString* const CDVViewWillLayoutSubviewsNotification;+extern NSString* const CDVViewDidLayoutSubviewsNotification;+extern NSString* const CDVViewWillTransitionToSizeNotification;++@interface CDVPlugin : NSObject {}++@property (nonatomic, readonly, weak) UIView* webView;+@property (nonatomic, readonly, weak) id <CDVWebViewEngineProtocol> webViewEngine;++@property (nonatomic, weak) UIViewController* viewController;+@property (nonatomic, weak) id <CDVCommandDelegate> commandDelegate;++@property (readonly, assign) BOOL hasPendingOperation;++- (void)pluginInitialize;++- (void)handleOpenURL:(NSNotification*)notification;+- (void)handleOpenURLWithApplicationSourceAndAnnotation:(NSNotification*)notification;+- (void)onAppTerminate;+- (void)onMemoryWarning;+- (void)onReset;+- (void)dispose;++/*+ // see initWithWebView implementation+ - (void) onPause {}+ - (void) onResume {}+ - (void) onOrientationWillChange {}+ - (void) onOrientationDidChange {}+ */++- (id)appDelegate;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin.mnew file mode 100644index 000000000..6af03e9cc--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPlugin.m@@ -0,0 +1,199 @@+/*+ 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"+#import "CDVPlugin+Private.h"+#import "CDVPlugin+Resources.h"+#import "CDVViewController.h"+#include <objc/message.h>++@implementation UIView (org_apache_cordova_UIView_Extension)++@dynamic scrollView;++- (UIScrollView*)scrollView+{+ SEL scrollViewSelector = NSSelectorFromString(@"scrollView");++ if ([self respondsToSelector:scrollViewSelector]) {+ return ((id (*)(id, SEL))objc_msgSend)(self, scrollViewSelector);+ }++ return nil;+}++@end++NSString* const CDVPageDidLoadNotification = @"CDVPageDidLoadNotification";+NSString* const CDVPluginHandleOpenURLNotification = @"CDVPluginHandleOpenURLNotification";+NSString* const CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification = @"CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification";+NSString* const CDVPluginResetNotification = @"CDVPluginResetNotification";+NSString* const CDVViewWillAppearNotification = @"CDVViewWillAppearNotification";+NSString* const CDVViewDidAppearNotification = @"CDVViewDidAppearNotification";+NSString* const CDVViewWillDisappearNotification = @"CDVViewWillDisappearNotification";+NSString* const CDVViewDidDisappearNotification = @"CDVViewDidDisappearNotification";+NSString* const CDVViewWillLayoutSubviewsNotification = @"CDVViewWillLayoutSubviewsNotification";+NSString* const CDVViewDidLayoutSubviewsNotification = @"CDVViewDidLayoutSubviewsNotification";+NSString* const CDVViewWillTransitionToSizeNotification = @"CDVViewWillTransitionToSizeNotification";++@interface CDVPlugin ()++@property (readwrite, assign) BOOL hasPendingOperation;+@property (nonatomic, readwrite, weak) id <CDVWebViewEngineProtocol> webViewEngine;++@end++@implementation CDVPlugin+@synthesize webViewEngine, viewController, commandDelegate, hasPendingOperation;+@dynamic webView;++// Do not override these methods. Use pluginInitialize instead.+- (instancetype)initWithWebViewEngine:(id <CDVWebViewEngineProtocol>)theWebViewEngine+{+ 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(handleOpenURLWithApplicationSourceAndAnnotation:) name:CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification object:nil];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReset) name:CDVPluginResetNotification object:theWebViewEngine.engineWebView];++ self.webViewEngine = theWebViewEngine;+ }+ 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.5.0+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageDidLoad:) name:CDVPageDidLoadNotification object:self.webView];+ //Added in 4.3.0+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillAppear:) name:CDVViewWillAppearNotification object:nil];+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidAppear:) name:CDVViewDidAppearNotification object:nil];+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillDisappear:) name:CDVViewWillDisappearNotification object:nil];+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidDisappear:) name:CDVViewDidDisappearNotification object:nil];+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillLayoutSubviews:) name:CDVViewWillLayoutSubviewsNotification object:nil];+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidLayoutSubviews:) name:CDVViewDidLayoutSubviewsNotification object:nil];+ // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillTransitionToSize:) name:CDVViewWillTransitionToSizeNotification object:nil];+}++- (void)dispose+{+ viewController = nil;+ commandDelegate = nil;+}++- (UIView*)webView+{+ if (self.webViewEngine != nil) {+ return self.webViewEngine.engineWebView;+ }++ return 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)handleOpenURLWithApplicationSourceAndAnnotation: (NSNotification*)notification+{++ // override to handle urls sent to your app+ // register your url schemes in your App-Info.plist++ // The notification object is an NSDictionary which contains+ // - url which is a type of NSURL+ // - sourceApplication which is a type of NSString and represents the package+ // id of the app that calls our app+ // - annotation which a type of Property list which can be several different types+ // please see https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/PropertyList.html++ NSDictionary* notificationData = [notification object];++ if ([notificationData isKindOfClass: NSDictionary.class]){++ NSURL* url = notificationData[@"url"];+ NSString* sourceApplication = notificationData[@"sourceApplication"];+ id annotation = notificationData[@"annotation"];++ if ([url isKindOfClass:NSURL.class] && [sourceApplication isKindOfClass:NSString.class] && annotation) {+ /* 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 notifications unless added using addObserverForName:object:queue:usingBlock:+}++- (id)appDelegate+{+ return [[UIApplication sharedApplication] delegate];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.hnew file mode 100644index 000000000..2f62d77b4--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.h@@ -0,0 +1,83 @@+/*+ 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 "CDVAvailability.h"++typedef NS_ENUM(NSUInteger, CDVCommandStatus) {+ CDVCommandStatus_NO_RESULT NS_SWIFT_NAME(noResult) = 0,+ CDVCommandStatus_OK NS_SWIFT_NAME(ok),+ CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION NS_SWIFT_NAME(classNotFoundException),+ CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION NS_SWIFT_NAME(illegalAccessException),+ CDVCommandStatus_INSTANTIATION_EXCEPTION NS_SWIFT_NAME(instantiationException),+ CDVCommandStatus_MALFORMED_URL_EXCEPTION NS_SWIFT_NAME(malformedUrlException),+ CDVCommandStatus_IO_EXCEPTION NS_SWIFT_NAME(ioException),+ CDVCommandStatus_INVALID_ACTION NS_SWIFT_NAME(invalidAction),+ CDVCommandStatus_JSON_EXCEPTION NS_SWIFT_NAME(jsonException),+ CDVCommandStatus_ERROR NS_SWIFT_NAME(error)+};++// This exists to preserve compatibility with early Swift plugins, who are+// using CDVCommandStatus as ObjC-style constants rather than as Swift enum+// values.+// This declares extern'ed constants (implemented in CDVPluginResult.m)+#define SWIFT_ENUM_COMPAT_HACK(enumVal) extern const CDVCommandStatus SWIFT_##enumVal NS_SWIFT_NAME(enumVal)+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_NO_RESULT);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_OK);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INSTANTIATION_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_MALFORMED_URL_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_IO_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INVALID_ACTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_JSON_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ERROR);+#undef SWIFT_ENUM_COMPAT_HACK++@interface CDVPluginResult : NSObject {}++@property (nonatomic, strong, readonly) NSNumber* status;+@property (nonatomic, strong, readonly) id message;+@property (nonatomic, strong) NSNumber* keepCallback;+// This property can be used to scope the lifetime of another object. For example,+// Use it to store the associated NSData when `message` is created using initWithBytesNoCopy.+@property (nonatomic, strong) id associatedObject;++- (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 messageAsNSInteger:(NSInteger)theMessage;++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsNSUInteger:(NSUInteger)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;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.mnew file mode 100644index 000000000..2f6f3a6cb--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.m@@ -0,0 +1,203 @@+/*+ 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_private.h"+#import "CDVDebug.h"++// This exists to preserve compatibility with early Swift plugins, who are+// using CDVCommandStatus as ObjC-style constants rather than as Swift enum+// values.+// These constants alias the enum values back to their previous names.+#define SWIFT_ENUM_COMPAT_HACK(enumVal) const CDVCommandStatus SWIFT_##enumVal NS_SWIFT_NAME(enumVal) = enumVal+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_NO_RESULT);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_OK);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INSTANTIATION_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_MALFORMED_URL_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_IO_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INVALID_ACTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_JSON_EXCEPTION);+SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ERROR);+#undef SWIFT_ENUM_COMPAT_HACK++@interface CDVPluginResult ()++- (CDVPluginResult*)initWithStatus:(CDVCommandStatus)statusOrdinal message:(id)theMessage;++@end++@implementation CDVPluginResult+@synthesize status, message, keepCallback, associatedObject;++static NSArray* org_apache_cordova_CommandStatusMsgs;++id messageFromArrayBuffer(NSData* data)+{+ return @{+ @"CDVType" : @"ArrayBuffer",+ @"data" :[data base64EncodedStringWithOptions:0]+ };+}++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:nil];+}+++ (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 messageAsNSInteger:(NSInteger)theMessage+{+ return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithInteger:theMessage]];+}+++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsNSUInteger:(NSUInteger)theMessage+{+ return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithUnsignedInteger: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 cdv_JSONString];++ argumentsJSON = [argumentsJSON substringWithRange:NSMakeRange(1, [argumentsJSON length] - 2)];++ return argumentsJSON;+}++static BOOL gIsVerbose = NO;++ (void)setVerbose:(BOOL)verbose+{+ gIsVerbose = verbose;+}+++ (BOOL)isVerbose+{+ return gIsVerbose;+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVScreenOrientationDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVScreenOrientationDelegate.hnew file mode 100644index 000000000..519dd490c--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVScreenOrientationDelegate.h@@ -0,0 +1,33 @@+/*+ 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>++@protocol CDVScreenOrientationDelegate <NSObject>++#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000+- (NSUInteger)supportedInterfaceOrientations;+#else+- (UIInterfaceOrientationMask)supportedInterfaceOrientations;+#endif++- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;+- (BOOL)shouldAutorotate;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVTimer.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVTimer.hnew file mode 100644index 000000000..6d31593f2--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVTimer.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 <Foundation/Foundation.h>++@interface CDVTimer : NSObject+++ (void)start:(NSString*)name;++ (void)stop:(NSString*)name;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVTimer.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVTimer.mnew file mode 100644index 000000000..784e94d38--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVTimer.m@@ -0,0 +1,123 @@+/*+ 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 "CDVTimer.h"++#pragma mark CDVTimerItem++@interface CDVTimerItem : NSObject++@property (nonatomic, strong) NSString* name;+@property (nonatomic, strong) NSDate* started;+@property (nonatomic, strong) NSDate* ended;++- (void)log;++@end++@implementation CDVTimerItem++- (void)log+{+ NSLog(@"[CDVTimer][%@] %fms", self.name, [self.ended timeIntervalSinceDate:self.started] * 1000.0);+}++@end++#pragma mark CDVTimer++@interface CDVTimer ()++@property (nonatomic, strong) NSMutableDictionary* items;++@end++@implementation CDVTimer++#pragma mark object methods++- (id)init+{+ if (self = [super init]) {+ self.items = [NSMutableDictionary dictionaryWithCapacity:6];+ }++ return self;+}++- (void)add:(NSString*)name+{+ if ([self.items objectForKey:[name lowercaseString]] == nil) {+ CDVTimerItem* item = [CDVTimerItem new];+ item.name = name;+ item.started = [NSDate new];+ [self.items setObject:item forKey:[name lowercaseString]];+ } else {+ NSLog(@"Timer called '%@' already exists.", name);+ }+}++- (void)remove:(NSString*)name+{+ CDVTimerItem* item = [self.items objectForKey:[name lowercaseString]];++ if (item != nil) {+ item.ended = [NSDate new];+ [item log];+ [self.items removeObjectForKey:[name lowercaseString]];+ } else {+ NSLog(@"Timer called '%@' does not exist.", name);+ }+}++- (void)removeAll+{+ [self.items removeAllObjects];+}++#pragma mark class methods+++ (void)start:(NSString*)name+{+ [[CDVTimer sharedInstance] add:name];+}+++ (void)stop:(NSString*)name+{+ [[CDVTimer sharedInstance] remove:name];+}+++ (void)clearAll+{+ [[CDVTimer sharedInstance] removeAll];+}+++ (CDVTimer*)sharedInstance+{+ static dispatch_once_t pred = 0;+ __strong static CDVTimer* _sharedObject = nil;++ dispatch_once(&pred, ^{+ _sharedObject = [[self alloc] init];+ });++ return _sharedObject;+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.hnew file mode 100644index 000000000..0561e04d9--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.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 <Foundation/Foundation.h>+#import "CDVAvailability.h"++@class CDVViewController;++@interface CDVURLProtocol : NSURLProtocol {}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.mnew file mode 100644index 000000000..7b2c5ce5b--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.m@@ -0,0 +1,113 @@+/*+ 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 <AssetsLibrary/ALAsset.h>+#import <AssetsLibrary/ALAssetRepresentation.h>+#import <AssetsLibrary/ALAssetsLibrary.h>+#import <MobileCoreServices/MobileCoreServices.h>+#import "CDVURLProtocol.h"+#import "CDVCommandQueue.h"+#import "CDVViewController.h"++// Contains a set of NSNumbers of addresses of controllers. It doesn't store+// the actual pointer to avoid retaining.+static NSMutableSet* gRegisteredControllers = nil;++NSString* const kCDVAssetsLibraryPrefixes = @"assets-library://";++@implementation CDVURLProtocol++++ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest+{+ NSURL* theUrl = [theRequest URL];++ if ([[theUrl absoluteString] hasPrefix:kCDVAssetsLibraryPrefixes]) {+ return YES;+ }++ return NO;+}+++ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request+{+ // NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd));+ return request;+}++- (void)startLoading+{+ // NSLog(@"%@ received %@ - start", self, NSStringFromSelector(_cmd));+ NSURL* url = [[self request] URL];++ if ([[url absoluteString] hasPrefix:kCDVAssetsLibraryPrefixes]) {+ ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {+ if (asset) {+ // We have the asset! Get the data and send it along.+ ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];+ NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType);+ Byte* buffer = (Byte*)malloc((unsigned long)[assetRepresentation size]);+ NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:0.0 length:(NSUInteger)[assetRepresentation size] error:nil];+ NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];+ [self sendResponseWithResponseCode:200 data:data mimeType:MIMEType];+ } else {+ // Retrieving the asset failed for some reason. Send an error.+ [self sendResponseWithResponseCode:404 data:nil mimeType:nil];+ }+ };+ ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {+ // Retrieving the asset failed for some reason. Send an error.+ [self sendResponseWithResponseCode:401 data:nil mimeType:nil];+ };++ ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];+ [assetsLibrary assetForURL:url resultBlock:resultBlock failureBlock:failureBlock];+ return;+ }++ NSString* body = [NSString stringWithFormat:@"Access not allowed to URL: %@", url];+ [self sendResponseWithResponseCode:401 data:[body dataUsingEncoding:NSASCIIStringEncoding] mimeType:nil];+}++- (void)stopLoading+{+ // do any cleanup here+}+++ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB+{+ return NO;+}++- (void)sendResponseWithResponseCode:(NSInteger)statusCode data:(NSData*)data mimeType:(NSString*)mimeType+{+ if (mimeType == nil) {+ mimeType = @"text/plain";+ }++ NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL] statusCode:statusCode HTTPVersion:@"HTTP/1.1" headerFields:@{@"Content-Type" : mimeType}];++ [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];+ if (data != nil) {+ [[self client] URLProtocol:self didLoadData:data];+ }+ [[self client] URLProtocolDidFinishLoading:self];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.hnew file mode 100644index 000000000..4de382f0b--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.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 <Foundation/Foundation.h>++@interface CDVUserAgentUtil : NSObject++ (NSString*)originalUserAgent;++ (void)acquireLock:(void (^)(NSInteger lockToken))block;++ (void)releaseLock:(NSInteger*)lockToken;++ (void)setUserAgent:(NSString*)value lockToken:(NSInteger)lockToken;+@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.mnew file mode 100644index 000000000..c5e9e2bcd--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.m@@ -0,0 +1,162 @@+/*+ 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 "CDVUserAgentUtil.h"++#import <UIKit/UIKit.h>++// #define VerboseLog NSLog+#define VerboseLog(...) do {} while (0)++static NSString* const kCdvUserAgentKey = @"Cordova-User-Agent";+static NSString* const kCdvUserAgentVersionKey = @"Cordova-User-Agent-Version";++static NSString* gOriginalUserAgent = nil;+static NSInteger gNextLockToken = 0;+static NSInteger gCurrentLockToken = 0;+static NSMutableArray* gPendingSetUserAgentBlocks = nil;++#if WK_WEB_VIEW_ONLY+#import <WebKit/WebKit.h>++@interface WKWebView(SynchronousEvaluateJavaScript)+- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;+@end++@implementation WKWebView(SynchronousEvaluateJavaScript)++- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script+{+ __block NSString *resultString = nil;+ __block BOOL finished = NO;++ [self evaluateJavaScript:script completionHandler:^(id result, NSError *error) {+ if (error == nil) {+ if (result != nil) {+ resultString = [NSString stringWithFormat:@"%@", result];+ }+ } else {+ NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);+ }+ finished = YES;+ }];++ while (!finished) {+ [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];+ }++ return resultString;+}+@end+#endif++@implementation CDVUserAgentUtil+++ (NSString*)originalUserAgent+{+ if (gOriginalUserAgent == nil) {+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppLocaleDidChange:)+ name:NSCurrentLocaleDidChangeNotification object:nil];++ NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];+ NSString* systemVersion = [[UIDevice currentDevice] systemVersion];+ NSString* localeStr = [[NSLocale currentLocale] localeIdentifier];+ // Record the model since simulator can change it without re-install (CB-5420).+ NSString* model = [UIDevice currentDevice].model;+ // Record the version of the app so that we can bust the cache when it changes (CB-10078)+ NSString* appVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"];+ NSString* systemAndLocale = [NSString stringWithFormat:@"%@ %@ %@ %@", appVersion, model, systemVersion, localeStr];++ NSString* cordovaUserAgentVersion = [userDefaults stringForKey:kCdvUserAgentVersionKey];+ gOriginalUserAgent = [userDefaults stringForKey:kCdvUserAgentKey];+ BOOL cachedValueIsOld = ![systemAndLocale isEqualToString:cordovaUserAgentVersion];++ if ((gOriginalUserAgent == nil) || cachedValueIsOld) {+ #if WK_WEB_VIEW_ONLY+ WKWebView* sampleWebView = [[WKWebView alloc] initWithFrame:CGRectZero];+ #else+ UIWebView* sampleWebView = [[UIWebView alloc] initWithFrame:CGRectZero];+#endif+ gOriginalUserAgent = [sampleWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];++ [userDefaults setObject:gOriginalUserAgent forKey:kCdvUserAgentKey];+ [userDefaults setObject:systemAndLocale forKey:kCdvUserAgentVersionKey];++ [userDefaults synchronize];+ }+ }+ return gOriginalUserAgent;+}+++ (void)onAppLocaleDidChange:(NSNotification*)notification+{+ // TODO: We should figure out how to update the user-agent of existing UIWebViews when this happens.+ // Maybe use the PDF bug (noted in setUserAgent:).+ gOriginalUserAgent = nil;+}+++ (void)acquireLock:(void (^)(NSInteger lockToken))block+{+ if (gCurrentLockToken == 0) {+ gCurrentLockToken = ++gNextLockToken;+ VerboseLog(@"Gave lock %d", gCurrentLockToken);+ block(gCurrentLockToken);+ } else {+ if (gPendingSetUserAgentBlocks == nil) {+ gPendingSetUserAgentBlocks = [[NSMutableArray alloc] initWithCapacity:4];+ }+ VerboseLog(@"Waiting for lock");+ [gPendingSetUserAgentBlocks addObject:block];+ }+}+++ (void)releaseLock:(NSInteger*)lockToken+{+ if (lockToken == nil || *lockToken == 0) {+ return;+ }+ NSAssert(gCurrentLockToken == *lockToken, @"Got token %ld, expected %ld", (long)*lockToken, (long)gCurrentLockToken);++ VerboseLog(@"Released lock %d", *lockToken);+ if ([gPendingSetUserAgentBlocks count] > 0) {+ void (^block)(NSInteger lockToken) = [gPendingSetUserAgentBlocks objectAtIndex:0];+ [gPendingSetUserAgentBlocks removeObjectAtIndex:0];+ gCurrentLockToken = ++gNextLockToken;+ NSLog(@"Gave lock %ld", (long)gCurrentLockToken);+ block(gCurrentLockToken);+ } else {+ gCurrentLockToken = 0;+ }+ *lockToken = 0;+}+++ (void)setUserAgent:(NSString*)value lockToken:(NSInteger)lockToken+{+ NSAssert(gCurrentLockToken == lockToken, @"Got token %ld, expected %ld", (long)lockToken, (long)gCurrentLockToken);+ VerboseLog(@"User-Agent set to: %@", value);++ // Setting the UserAgent must occur before a UIWebView is instantiated.+ // It is read per instantiation, so it does not affect previously created views.+ // Except! When a PDF is loaded, all currently active UIWebViews reload their+ // User-Agent from the NSUserDefaults some time after the DidFinishLoad of the PDF bah!+ NSDictionary* dict = [[NSDictionary alloc] initWithObjectsAndKeys:value, @"UserAgent", nil];+ [[NSUserDefaults standardUserDefaults] registerDefaults:dict];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.hnew file mode 100644index 000000000..605dbbbfb--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.h@@ -0,0 +1,92 @@+/*+ 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 <UIKit/UIKit.h>+#import <Foundation/NSJSONSerialization.h>+#import "CDVAvailability.h"+#import "CDVInvokedUrlCommand.h"+#import "CDVCommandDelegate.h"+#import "CDVCommandQueue.h"+#import "CDVScreenOrientationDelegate.h"+#import "CDVPlugin.h"+#import "CDVWebViewEngineProtocol.h"++@interface CDVViewController : UIViewController <CDVScreenOrientationDelegate>{+ @protected+ id <CDVWebViewEngineProtocol> _webViewEngine;+ @protected+ id <CDVCommandDelegate> _commandDelegate;+ @protected+ CDVCommandQueue* _commandQueue;+ NSString* _userAgent;+}++@property (nonatomic, readonly, weak) IBOutlet UIView* webView;++@property (nonatomic, readonly, strong) NSMutableDictionary* pluginObjects;+@property (nonatomic, readonly, strong) NSDictionary* pluginsMap;+@property (nonatomic, readonly, strong) NSMutableDictionary* settings;+@property (nonatomic, readonly, strong) NSXMLParser* configParser;++@property (nonatomic, readwrite, copy) NSString* configFile;+@property (nonatomic, readwrite, copy) NSString* wwwFolderName;+@property (nonatomic, readwrite, copy) NSString* startPage;+@property (nonatomic, readonly, strong) CDVCommandQueue* commandQueue;+@property (nonatomic, readonly, strong) id <CDVWebViewEngineProtocol> webViewEngine;+@property (nonatomic, readonly, strong) id <CDVCommandDelegate> commandDelegate;++/**+ The complete user agent that Cordova will use when sending web requests.+ */+@property (nonatomic, readonly) NSString* userAgent;++/**+ The base user agent data that Cordova will use to build its user agent. If this+ property isn't set, Cordova will use the standard web view user agent as its+ base.+ */+@property (nonatomic, readwrite, copy) NSString* baseUserAgent;++/**+ Takes/Gives an array of UIInterfaceOrientation (int) objects+ ex. UIInterfaceOrientationPortrait+*/+@property (nonatomic, readwrite, strong) NSArray* supportedOrientations;++/**+ The address of the lock token used for controlling access to setting the user-agent+ */+@property (nonatomic, readonly) NSInteger* userAgentLockToken;++- (UIView*)newCordovaViewWithFrame:(CGRect)bounds;++- (NSString*)appURLScheme;+- (NSURL*)errorURL;++- (UIColor*)colorFromColorString:(NSString*)colorString;+- (NSArray*)parseInterfaceOrientations:(NSArray*)orientations;+- (BOOL)supportsOrientation:(UIInterfaceOrientation)orientation;++- (id)getCommandInstance:(NSString*)pluginName;+- (void)registerPlugin:(CDVPlugin*)plugin withClassName:(NSString*)className;+- (void)registerPlugin:(CDVPlugin*)plugin withPluginName:(NSString*)pluginName;++- (void)parseSettingsWithParser:(NSObject <NSXMLParserDelegate>*)delegate;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.mnew file mode 100644index 000000000..75e74add0--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.m@@ -0,0 +1,810 @@+/*+ 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 <objc/message.h>+#import "CDV.h"+#import "CDVPlugin+Private.h"+#import "CDVConfigParser.h"+#import "CDVUserAgentUtil.h"+#import <AVFoundation/AVFoundation.h>+#import "NSDictionary+CordovaPreferences.h"+#import "CDVLocalStorage.h"+#import "CDVCommandDelegateImpl.h"+#import <Foundation/NSCharacterSet.h>++@interface CDVViewController () {+ NSInteger _userAgentLockToken;+}++@property (nonatomic, readwrite, strong) NSXMLParser* configParser;+@property (nonatomic, readwrite, strong) NSMutableDictionary* settings;+@property (nonatomic, readwrite, strong) NSMutableDictionary* pluginObjects;+@property (nonatomic, readwrite, strong) NSMutableArray* startupPluginNames;+@property (nonatomic, readwrite, strong) NSDictionary* pluginsMap;+@property (nonatomic, readwrite, strong) id <CDVWebViewEngineProtocol> webViewEngine;++@property (readwrite, assign) BOOL initialized;++@property (atomic, strong) NSURL* openURL;++@end++@implementation CDVViewController++@synthesize supportedOrientations;+@synthesize pluginObjects, pluginsMap, startupPluginNames;+@synthesize configParser, settings;+@synthesize wwwFolderName, startPage, initialized, openURL, baseUserAgent;+@synthesize commandDelegate = _commandDelegate;+@synthesize commandQueue = _commandQueue;+@synthesize webViewEngine = _webViewEngine;+@dynamic webView;++- (void)__init+{+ if ((self != nil) && !self.initialized) {+ _commandQueue = [[CDVCommandQueue alloc] initWithViewController:self];+ _commandDelegate = [[CDVCommandDelegateImpl alloc] initWithViewController:self];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillTerminate:)+ name:UIApplicationWillTerminateNotification object:nil];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillResignActive:)+ name:UIApplicationWillResignActiveNotification object:nil];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidBecomeActive:)+ name:UIApplicationDidBecomeActiveNotification object:nil];++ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:)+ name:UIApplicationWillEnterForegroundNotification object:nil];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackground:)+ name:UIApplicationDidEnterBackgroundNotification object:nil];++ // read from UISupportedInterfaceOrientations (or UISupportedInterfaceOrientations~iPad, if its iPad) from -Info.plist+ self.supportedOrientations = [self parseInterfaceOrientations:+ [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]];++ [self printVersion];+ [self printMultitaskingInfo];+ [self printPlatformVersionWarning];+ self.initialized = YES;+ }+}++- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil+{+ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];+ [self __init];+ return self;+}++- (id)initWithCoder:(NSCoder*)aDecoder+{+ self = [super initWithCoder:aDecoder];+ [self __init];+ return self;+}++- (id)init+{+ self = [super init];+ [self __init];+ return self;+}++- (void)printVersion+{+ NSLog(@"Apache Cordova native platform version %@ is starting.", CDV_VERSION);+}++- (void)printPlatformVersionWarning+{+ if (!IsAtLeastiOSVersion(@"8.0")) {+ NSLog(@"CRITICAL: For Cordova 4.0.0 and above, you will need to upgrade to at least iOS 8.0 or greater. Your current version of iOS is %@.",+ [[UIDevice currentDevice] systemVersion]+ );+ }+}++- (void)printMultitaskingInfo+{+ UIDevice* device = [UIDevice currentDevice];+ BOOL backgroundSupported = NO;++ if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {+ backgroundSupported = device.multitaskingSupported;+ }++ NSNumber* exitsOnSuspend = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIApplicationExitsOnSuspend"];+ if (exitsOnSuspend == nil) { // if it's missing, it should be NO (i.e. multi-tasking on by default)+ exitsOnSuspend = [NSNumber numberWithBool:NO];+ }++ NSLog(@"Multi-tasking -> Device: %@, App: %@", (backgroundSupported ? @"YES" : @"NO"), (![exitsOnSuspend intValue]) ? @"YES" : @"NO");+}++-(NSString*)configFilePath{+ NSString* path = self.configFile ?: @"config.xml";++ // if path is relative, resolve it against the main bundle+ if(![path isAbsolutePath]){+ NSString* absolutePath = [[NSBundle mainBundle] pathForResource:path ofType:nil];+ if(!absolutePath){+ NSAssert(NO, @"ERROR: %@ not found in the main bundle!", path);+ }+ path = absolutePath;+ }++ // Assert file exists+ if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {+ NSAssert(NO, @"ERROR: %@ does not exist. Please run cordova-ios/bin/cordova_plist_to_config_xml path/to/project.", path);+ return nil;+ }++ return path;+}++- (void)parseSettingsWithParser:(NSObject <NSXMLParserDelegate>*)delegate+{+ // read from config.xml in the app bundle+ NSString* path = [self configFilePath];++ NSURL* url = [NSURL fileURLWithPath:path];++ self.configParser = [[NSXMLParser alloc] initWithContentsOfURL:url];+ if (self.configParser == nil) {+ NSLog(@"Failed to initialize XML parser.");+ return;+ }+ [self.configParser setDelegate:((id < NSXMLParserDelegate >)delegate)];+ [self.configParser parse];+}++- (void)loadSettings+{+ CDVConfigParser* delegate = [[CDVConfigParser alloc] init];++ [self parseSettingsWithParser:delegate];++ // Get the plugin dictionary, whitelist and settings from the delegate.+ self.pluginsMap = delegate.pluginsDict;+ self.startupPluginNames = delegate.startupPluginNames;+ self.settings = delegate.settings;++ // And the start folder/page.+ if(self.wwwFolderName == nil){+ self.wwwFolderName = @"www";+ }+ if(delegate.startPage && self.startPage == nil){+ self.startPage = delegate.startPage;+ }+ if (self.startPage == nil) {+ self.startPage = @"index.html";+ }++ // Initialize the plugin objects dict.+ self.pluginObjects = [[NSMutableDictionary alloc] initWithCapacity:20];+}++- (NSURL*)appUrl+{+ NSURL* appURL = nil;++ if ([self.startPage rangeOfString:@"://"].location != NSNotFound) {+ appURL = [NSURL URLWithString:self.startPage];+ } else if ([self.wwwFolderName rangeOfString:@"://"].location != NSNotFound) {+ appURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", self.wwwFolderName, self.startPage]];+ } else if([self.wwwFolderName rangeOfString:@".bundle"].location != NSNotFound){+ // www folder is actually a bundle+ NSBundle* bundle = [NSBundle bundleWithPath:self.wwwFolderName];+ appURL = [bundle URLForResource:self.startPage withExtension:nil];+ } else if([self.wwwFolderName rangeOfString:@".framework"].location != NSNotFound){+ // www folder is actually a framework+ NSBundle* bundle = [NSBundle bundleWithPath:self.wwwFolderName];+ appURL = [bundle URLForResource:self.startPage withExtension:nil];+ } else {+ // CB-3005 strip parameters from start page to check if page exists in resources+ NSURL* startURL = [NSURL URLWithString:self.startPage];+ NSString* startFilePath = [self.commandDelegate pathForResource:[startURL path]];++ if (startFilePath == nil) {+ appURL = nil;+ } else {+ appURL = [NSURL fileURLWithPath:startFilePath];+ // CB-3005 Add on the query params or fragment.+ NSString* startPageNoParentDirs = self.startPage;+ NSRange r = [startPageNoParentDirs rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"?#"] options:0];+ if (r.location != NSNotFound) {+ NSString* queryAndOrFragment = [self.startPage substringFromIndex:r.location];+ appURL = [NSURL URLWithString:queryAndOrFragment relativeToURL:appURL];+ }+ }+ }++ return appURL;+}++- (NSURL*)errorURL+{+ NSURL* errorUrl = nil;++ id setting = [self.settings cordovaSettingForKey:@"ErrorUrl"];++ if (setting) {+ NSString* errorUrlString = (NSString*)setting;+ if ([errorUrlString rangeOfString:@"://"].location != NSNotFound) {+ errorUrl = [NSURL URLWithString:errorUrlString];+ } else {+ NSURL* url = [NSURL URLWithString:(NSString*)setting];+ NSString* errorFilePath = [self.commandDelegate pathForResource:[url path]];+ if (errorFilePath) {+ errorUrl = [NSURL fileURLWithPath:errorFilePath];+ }+ }+ }++ return errorUrl;+}++- (UIView*)webView+{+ if (self.webViewEngine != nil) {+ return self.webViewEngine.engineWebView;+ }++ return nil;+}++// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.+- (void)viewDidLoad+{+ [super viewDidLoad];++ // Load settings+ [self loadSettings];++ NSString* backupWebStorageType = @"cloud"; // default value++ id backupWebStorage = [self.settings cordovaSettingForKey:@"BackupWebStorage"];+ if ([backupWebStorage isKindOfClass:[NSString class]]) {+ backupWebStorageType = backupWebStorage;+ }+ [self.settings setCordovaSetting:backupWebStorageType forKey:@"BackupWebStorage"];++ [CDVLocalStorage __fixupDatabaseLocationsWithBackupType:backupWebStorageType];++ // // Instantiate the WebView ///////////////++ if (!self.webView) {+ [self createGapView];+ }++ // /////////////////++ /*+ * Fire up CDVLocalStorage to work-around WebKit storage limitations: on all iOS 5.1+ versions for local-only backups, but only needed on iOS 5.1 for cloud backup.+ With minimum iOS 7/8 supported, only first clause applies.+ */+ if ([backupWebStorageType isEqualToString:@"local"]) {+ NSString* localStorageFeatureName = @"localstorage";+ if ([self.pluginsMap objectForKey:localStorageFeatureName]) { // plugin specified in config+ [self.startupPluginNames addObject:localStorageFeatureName];+ }+ }++ if ([self.startupPluginNames count] > 0) {+ [CDVTimer start:@"TotalPluginStartup"];++ for (NSString* pluginName in self.startupPluginNames) {+ [CDVTimer start:pluginName];+ [self getCommandInstance:pluginName];+ [CDVTimer stop:pluginName];+ }++ [CDVTimer stop:@"TotalPluginStartup"];+ }++ // /////////////////+ NSURL* appURL = [self appUrl];+ __weak __typeof__(self) weakSelf = self;++ [CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {+ // Fix the memory leak caused by the strong reference.+ [weakSelf setLockToken:lockToken];+ if (appURL) {+ NSURLRequest* appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];+ [self.webViewEngine loadRequest:appReq];+ } else {+ NSString* loadErr = [NSString stringWithFormat:@"ERROR: Start Page at '%@/%@' was not found.", self.wwwFolderName, self.startPage];+ NSLog(@"%@", loadErr);++ NSURL* errorUrl = [self errorURL];+ if (errorUrl) {+ errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [loadErr stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]] relativeToURL:errorUrl];+ NSLog(@"%@", [errorUrl absoluteString]);+ [self.webViewEngine loadRequest:[NSURLRequest requestWithURL:errorUrl]];+ } else {+ NSString* html = [NSString stringWithFormat:@"<html><body> %@ </body></html>", loadErr];+ [self.webViewEngine loadHTMLString:html baseURL:nil];+ }+ }+ }];++ // /////////////////++ NSString* bgColorString = [self.settings cordovaSettingForKey:@"BackgroundColor"];+ UIColor* bgColor = [self colorFromColorString:bgColorString];+ [self.webView setBackgroundColor:bgColor];+}++- (void)setLockToken:(NSInteger)lockToken+{+ _userAgentLockToken = lockToken;+ [CDVUserAgentUtil setUserAgent:self.userAgent lockToken:lockToken];+}++-(void)viewWillAppear:(BOOL)animated+{+ [super viewWillAppear:animated];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVViewWillAppearNotification object:nil]];+}++-(void)viewDidAppear:(BOOL)animated+{+ [super viewDidAppear:animated];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVViewDidAppearNotification object:nil]];+}++-(void)viewWillDisappear:(BOOL)animated+{+ [super viewWillDisappear:animated];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVViewWillDisappearNotification object:nil]];+}++-(void)viewDidDisappear:(BOOL)animated+{+ [super viewDidDisappear:animated];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVViewDidDisappearNotification object:nil]];+}++-(void)viewWillLayoutSubviews+{+ [super viewWillLayoutSubviews];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVViewWillLayoutSubviewsNotification object:nil]];+}++-(void)viewDidLayoutSubviews+{+ [super viewDidLayoutSubviews];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVViewDidLayoutSubviewsNotification object:nil]];+}++-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator+{+ [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];+ [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVViewWillTransitionToSizeNotification object:[NSValue valueWithCGSize:size]]];+}++- (UIColor*)colorFromColorString:(NSString*)colorString+{+ // No value, nothing to do+ if (!colorString) {+ return nil;+ }++ // Validate format+ NSError* error = NULL;+ NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"^(#[0-9A-F]{3}|(0x|#)([0-9A-F]{2})?[0-9A-F]{6})$" options:NSRegularExpressionCaseInsensitive error:&error];+ NSUInteger countMatches = [regex numberOfMatchesInString:colorString options:0 range:NSMakeRange(0, [colorString length])];++ if (!countMatches) {+ return nil;+ }++ // #FAB to #FFAABB+ if ([colorString hasPrefix:@"#"] && [colorString length] == 4) {+ NSString* r = [colorString substringWithRange:NSMakeRange(1, 1)];+ NSString* g = [colorString substringWithRange:NSMakeRange(2, 1)];+ NSString* b = [colorString substringWithRange:NSMakeRange(3, 1)];+ colorString = [NSString stringWithFormat:@"#%@%@%@%@%@%@", r, r, g, g, b, b];+ }++ // #RRGGBB to 0xRRGGBB+ colorString = [colorString stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];++ // 0xRRGGBB to 0xAARRGGBB+ if ([colorString hasPrefix:@"0x"] && [colorString length] == 8) {+ colorString = [@"0xFF" stringByAppendingString:[colorString substringFromIndex:2]];+ }++ // 0xAARRGGBB to int+ unsigned colorValue = 0;+ NSScanner *scanner = [NSScanner scannerWithString:colorString];+ if (![scanner scanHexInt:&colorValue]) {+ return nil;+ }++ // int to UIColor+ return [UIColor colorWithRed:((float)((colorValue & 0x00FF0000) >> 16))/255.0+ green:((float)((colorValue & 0x0000FF00) >> 8))/255.0+ blue:((float)((colorValue & 0x000000FF) >> 0))/255.0+ alpha:((float)((colorValue & 0xFF000000) >> 24))/255.0];+}++- (NSArray*)parseInterfaceOrientations:(NSArray*)orientations+{+ NSMutableArray* result = [[NSMutableArray alloc] init];++ if (orientations != nil) {+ NSEnumerator* enumerator = [orientations objectEnumerator];+ NSString* orientationString;++ while (orientationString = [enumerator nextObject]) {+ if ([orientationString isEqualToString:@"UIInterfaceOrientationPortrait"]) {+ [result addObject:[NSNumber numberWithInt:UIInterfaceOrientationPortrait]];+ } else if ([orientationString isEqualToString:@"UIInterfaceOrientationPortraitUpsideDown"]) {+ [result addObject:[NSNumber numberWithInt:UIInterfaceOrientationPortraitUpsideDown]];+ } else if ([orientationString isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]) {+ [result addObject:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft]];+ } else if ([orientationString isEqualToString:@"UIInterfaceOrientationLandscapeRight"]) {+ [result addObject:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight]];+ }+ }+ }++ // default+ if ([result count] == 0) {+ [result addObject:[NSNumber numberWithInt:UIInterfaceOrientationPortrait]];+ }++ return result;+}++- (BOOL)shouldAutorotate+{+ return YES;+}++// CB-12098+#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000+- (NSUInteger)supportedInterfaceOrientations+#else+- (UIInterfaceOrientationMask)supportedInterfaceOrientations+#endif+{+ NSUInteger ret = 0;++ if ([self supportsOrientation:UIInterfaceOrientationPortrait]) {+ ret = ret | (1 << UIInterfaceOrientationPortrait);+ }+ if ([self supportsOrientation:UIInterfaceOrientationPortraitUpsideDown]) {+ ret = ret | (1 << UIInterfaceOrientationPortraitUpsideDown);+ }+ if ([self supportsOrientation:UIInterfaceOrientationLandscapeRight]) {+ ret = ret | (1 << UIInterfaceOrientationLandscapeRight);+ }+ if ([self supportsOrientation:UIInterfaceOrientationLandscapeLeft]) {+ ret = ret | (1 << UIInterfaceOrientationLandscapeLeft);+ }++ return ret;+}++- (BOOL)supportsOrientation:(UIInterfaceOrientation)orientation+{+ return [self.supportedOrientations containsObject:[NSNumber numberWithInt:orientation]];+}++- (UIView*)newCordovaViewWithFrame:(CGRect)bounds+{+ NSString* defaultWebViewEngineClass = [self.settings cordovaSettingForKey:@"CordovaDefaultWebViewEngine"];+ NSString* webViewEngineClass = [self.settings cordovaSettingForKey:@"CordovaWebViewEngine"];++ if (!defaultWebViewEngineClass) {+ defaultWebViewEngineClass = @"CDVUIWebViewEngine";+ }+ if (!webViewEngineClass) {+ webViewEngineClass = defaultWebViewEngineClass;+ }++ // Find webViewEngine+ if (NSClassFromString(webViewEngineClass)) {+ self.webViewEngine = [[NSClassFromString(webViewEngineClass) alloc] initWithFrame:bounds];+ // if a webView engine returns nil (not supported by the current iOS version) or doesn't conform to the protocol, or can't load the request, we use UIWebView+ if (!self.webViewEngine || ![self.webViewEngine conformsToProtocol:@protocol(CDVWebViewEngineProtocol)] || ![self.webViewEngine canLoadRequest:[NSURLRequest requestWithURL:self.appUrl]]) {+ self.webViewEngine = [[NSClassFromString(defaultWebViewEngineClass) alloc] initWithFrame:bounds];+ }+ } else {+ self.webViewEngine = [[NSClassFromString(defaultWebViewEngineClass) alloc] initWithFrame:bounds];+ }++ if ([self.webViewEngine isKindOfClass:[CDVPlugin class]]) {+ [self registerPlugin:(CDVPlugin*)self.webViewEngine withClassName:webViewEngineClass];+ }++ return self.webViewEngine.engineWebView;+}++- (NSString*)userAgent+{+ if (_userAgent != nil) {+ return _userAgent;+ }++ NSString* localBaseUserAgent;+ if (self.baseUserAgent != nil) {+ localBaseUserAgent = self.baseUserAgent;+ } else if ([self.settings cordovaSettingForKey:@"OverrideUserAgent"] != nil) {+ localBaseUserAgent = [self.settings cordovaSettingForKey:@"OverrideUserAgent"];+ } else {+ localBaseUserAgent = [CDVUserAgentUtil originalUserAgent];+ }+ NSString* appendUserAgent = [self.settings cordovaSettingForKey:@"AppendUserAgent"];+ if (appendUserAgent) {+ _userAgent = [NSString stringWithFormat:@"%@ %@", localBaseUserAgent, appendUserAgent];+ } else {+ // Use our address as a unique number to append to the User-Agent.+ _userAgent = localBaseUserAgent;+ }+ return _userAgent;+}++- (void)createGapView+{+ CGRect webViewBounds = self.view.bounds;++ webViewBounds.origin = self.view.bounds.origin;++ UIView* view = [self newCordovaViewWithFrame:webViewBounds];++ view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);+ [self.view addSubview:view];+ [self.view sendSubviewToBack:view];+}++- (void)didReceiveMemoryWarning+{+ // iterate through all the plugin objects, and call hasPendingOperation+ // if at least one has a pending operation, we don't call [super didReceiveMemoryWarning]++ NSEnumerator* enumerator = [self.pluginObjects objectEnumerator];+ CDVPlugin* plugin;++ BOOL doPurge = YES;++ while ((plugin = [enumerator nextObject])) {+ if (plugin.hasPendingOperation) {+ NSLog(@"Plugin '%@' has a pending operation, memory purge is delayed for didReceiveMemoryWarning.", NSStringFromClass([plugin class]));+ doPurge = NO;+ }+ }++ if (doPurge) {+ // Releases the view if it doesn't have a superview.+ [super didReceiveMemoryWarning];+ }++ // Release any cached data, images, etc. that aren't in use.+}++#pragma mark CordovaCommands++- (void)registerPlugin:(CDVPlugin*)plugin withClassName:(NSString*)className+{+ if ([plugin respondsToSelector:@selector(setViewController:)]) {+ [plugin setViewController:self];+ }++ if ([plugin respondsToSelector:@selector(setCommandDelegate:)]) {+ [plugin setCommandDelegate:_commandDelegate];+ }++ [self.pluginObjects setObject:plugin forKey:className];+ [plugin pluginInitialize];+}++- (void)registerPlugin:(CDVPlugin*)plugin withPluginName:(NSString*)pluginName+{+ if ([plugin respondsToSelector:@selector(setViewController:)]) {+ [plugin setViewController:self];+ }++ if ([plugin respondsToSelector:@selector(setCommandDelegate:)]) {+ [plugin setCommandDelegate:_commandDelegate];+ }++ NSString* className = NSStringFromClass([plugin class]);+ [self.pluginObjects setObject:plugin forKey:className];+ [self.pluginsMap setValue:className forKey:[pluginName lowercaseString]];+ [plugin pluginInitialize];+}++/**+ Returns an instance of a CordovaCommand object, based on its name. If one exists already, it is returned.+ */+- (id)getCommandInstance:(NSString*)pluginName+{+ // first, we try to find the pluginName in the pluginsMap+ // (acts as a whitelist as well) if it does not exist, we return nil+ // NOTE: plugin names are matched as lowercase to avoid problems - however, a+ // possible issue is there can be duplicates possible if you had:+ // "org.apache.cordova.Foo" and "org.apache.cordova.foo" - only the lower-cased entry will match+ NSString* className = [self.pluginsMap objectForKey:[pluginName lowercaseString]];++ if (className == nil) {+ return nil;+ }++ id obj = [self.pluginObjects objectForKey:className];+ if (!obj) {+ obj = [[NSClassFromString(className)alloc] initWithWebViewEngine:_webViewEngine];+ if (!obj) {+ NSString* fullClassName = [NSString stringWithFormat:@"%@.%@",+ NSBundle.mainBundle.infoDictionary[@"CFBundleExecutable"],+ className];+ obj = [[NSClassFromString(fullClassName)alloc] initWithWebViewEngine:_webViewEngine];+ }++ if (obj != nil) {+ [self registerPlugin:obj withClassName:className];+ } else {+ NSLog(@"CDVPlugin class %@ (pluginName: %@) does not exist.", className, pluginName);+ }+ }+ return obj;+}++#pragma mark -++- (NSString*)appURLScheme+{+ NSString* URLScheme = nil;++ NSArray* URLTypes = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleURLTypes"];++ if (URLTypes != nil) {+ NSDictionary* dict = [URLTypes objectAtIndex:0];+ if (dict != nil) {+ NSArray* URLSchemes = [dict objectForKey:@"CFBundleURLSchemes"];+ if (URLSchemes != nil) {+ URLScheme = [URLSchemes objectAtIndex:0];+ }+ }+ }++ return URLScheme;+}++#pragma mark -+#pragma mark UIApplicationDelegate impl++/*+ This method lets your application know that it is about to be terminated and purged from memory entirely+ */+- (void)onAppWillTerminate:(NSNotification*)notification+{+ // empty the tmp directory+ NSFileManager* fileMgr = [[NSFileManager alloc] init];+ NSError* __autoreleasing err = nil;++ // clear contents of NSTemporaryDirectory+ NSString* tempDirectoryPath = NSTemporaryDirectory();+ NSDirectoryEnumerator* directoryEnumerator = [fileMgr enumeratorAtPath:tempDirectoryPath];+ NSString* fileName = nil;+ BOOL result;++ while ((fileName = [directoryEnumerator nextObject])) {+ NSString* filePath = [tempDirectoryPath stringByAppendingPathComponent:fileName];+ result = [fileMgr removeItemAtPath:filePath error:&err];+ if (!result && err) {+ NSLog(@"Failed to delete: %@ (error: %@)", filePath, err);+ }+ }+}++- (bool)isUrlEmpty:(NSURL *)url+{+ if (!url || (url == (id) [NSNull null])) {+ return true;+ }+ NSString *urlAsString = [url absoluteString];+ return (urlAsString == (id) [NSNull null] || [urlAsString length]==0 || [urlAsString isEqualToString:@"about:blank"]);+}++- (bool)checkAndReinitViewUrl+{+ NSURL* appURL = [self appUrl];+ if ([self isUrlEmpty: [self.webViewEngine URL]] && ![self isUrlEmpty: appURL]) {+ NSURLRequest* appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];+ [self.webViewEngine loadRequest:appReq];+ return true;+ }+ return false;+}++/*+ This method is called to let your application know that it is about to move from the active to inactive state.+ You should use this method to pause ongoing tasks, disable timer, ...+ */+- (void)onAppWillResignActive:(NSNotification*)notification+{+ [self checkAndReinitViewUrl];+ // NSLog(@"%@",@"applicationWillResignActive");+ [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('resign');" scheduledOnRunLoop:NO];+}++/*+ In iOS 4.0 and later, this method is called as part of the transition from the background to the inactive state.+ You can use this method to undo many of the changes you made to your application upon entering the background.+ invariably followed by applicationDidBecomeActive+ */+- (void)onAppWillEnterForeground:(NSNotification*)notification+{+ [self checkAndReinitViewUrl];+ // NSLog(@"%@",@"applicationWillEnterForeground");+ [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('resume');"];++ if (!IsAtLeastiOSVersion(@"11.0")) {+ /** Clipboard fix **/+ UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];+ NSString* string = pasteboard.string;+ if (string) {+ [pasteboard setValue:string forPasteboardType:@"public.text"];+ }+ }+}++// This method is called to let your application know that it moved from the inactive to active state.+- (void)onAppDidBecomeActive:(NSNotification*)notification+{+ [self checkAndReinitViewUrl];+ // NSLog(@"%@",@"applicationDidBecomeActive");+ [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('active');"];+}++/*+ In iOS 4.0 and later, this method is called instead of the applicationWillTerminate: method+ when the user quits an application that supports background execution.+ */+- (void)onAppDidEnterBackground:(NSNotification*)notification+{+ [self checkAndReinitViewUrl];+ // NSLog(@"%@",@"applicationDidEnterBackground");+ [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('pause', null, true);" scheduledOnRunLoop:NO];+}++// ///////////////////////++- (void)dealloc+{+ [[NSNotificationCenter defaultCenter] removeObserver:self];++ [CDVUserAgentUtil releaseLock:&_userAgentLockToken];+ [_commandQueue dispose];+ [[self.pluginObjects allValues] makeObjectsPerformSelector:@selector(dispose)];++ [self.webViewEngine loadHTMLString:@"about:blank" baseURL:nil];+ [self.pluginObjects removeAllObjects];+ [self.webView removeFromSuperview];+ self.webViewEngine = nil;+}++- (NSInteger*)userAgentLockToken+{+ return &_userAgentLockToken;+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWebViewEngineProtocol.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWebViewEngineProtocol.hnew file mode 100644index 000000000..34d07f3d0--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWebViewEngineProtocol.h@@ -0,0 +1,42 @@+/*+ 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 <UIKit/UIKit.h>++#define kCDVWebViewEngineScriptMessageHandlers @"kCDVWebViewEngineScriptMessageHandlers"+#define kCDVWebViewEngineUIWebViewDelegate @"kCDVWebViewEngineUIWebViewDelegate"+#define kCDVWebViewEngineWKNavigationDelegate @"kCDVWebViewEngineWKNavigationDelegate"+#define kCDVWebViewEngineWKUIDelegate @"kCDVWebViewEngineWKUIDelegate"+#define kCDVWebViewEngineWebViewPreferences @"kCDVWebViewEngineWebViewPreferences"++@protocol CDVWebViewEngineProtocol <NSObject>++@property (nonatomic, strong, readonly) UIView* engineWebView;++- (id)loadRequest:(NSURLRequest*)request;+- (id)loadHTMLString:(NSString*)string baseURL:(NSURL*)baseURL;+- (void)evaluateJavaScript:(NSString*)javaScriptString completionHandler:(void (^)(id, NSError*))completionHandler;++- (NSURL*)URL;+- (BOOL)canLoadRequest:(NSURLRequest*)request;++- (instancetype)initWithFrame:(CGRect)frame;+- (void)updateWithInfo:(NSDictionary*)info;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWhitelist.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWhitelist.hnew file mode 100644index 000000000..91650970b--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWhitelist.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 <Foundation/Foundation.h>++extern NSString* const kCDVDefaultWhitelistRejectionString;++@interface CDVWhitelist : NSObject++@property (nonatomic, copy) NSString* whitelistRejectionFormatString;++- (id)initWithArray:(NSArray*)array;+- (BOOL)schemeIsAllowed:(NSString*)scheme;+- (BOOL)URLIsAllowed:(NSURL*)url;+- (BOOL)URLIsAllowed:(NSURL*)url logFailure:(BOOL)logFailure;+- (NSString*)errorStringForURL:(NSURL*)url;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWhitelist.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWhitelist.mnew file mode 100644index 000000000..758f4d1ef--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWhitelist.m@@ -0,0 +1,285 @@+/*+ 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 "CDVWhitelist.h"++NSString* const kCDVDefaultWhitelistRejectionString = @"ERROR whitelist rejection: url='%@'";+NSString* const kCDVDefaultSchemeName = @"cdv-default-scheme";++@interface CDVWhitelistPattern : NSObject {+ @private+ NSRegularExpression* _scheme;+ NSRegularExpression* _host;+ NSNumber* _port;+ NSRegularExpression* _path;+}+++ (NSString*)regexFromPattern:(NSString*)pattern allowWildcards:(bool)allowWildcards;+- (id)initWithScheme:(NSString*)scheme host:(NSString*)host port:(NSString*)port path:(NSString*)path;+- (bool)matches:(NSURL*)url;++@end++@implementation CDVWhitelistPattern+++ (NSString*)regexFromPattern:(NSString*)pattern allowWildcards:(bool)allowWildcards+{+ NSString* regex = [NSRegularExpression escapedPatternForString:pattern];++ if (allowWildcards) {+ regex = [regex stringByReplacingOccurrencesOfString:@"\\*" withString:@".*"];++ /* [NSURL path] has the peculiarity that a trailing slash at the end of a path+ * will be omitted. This regex tweak compensates for that.+ */+ if ([regex hasSuffix:@"\\/.*"]) {+ regex = [NSString stringWithFormat:@"%@(\\/.*)?", [regex substringToIndex:([regex length] - 4)]];+ }+ }+ return [NSString stringWithFormat:@"%@$", regex];+}++- (id)initWithScheme:(NSString*)scheme host:(NSString*)host port:(NSString*)port path:(NSString*)path+{+ self = [super init]; // Potentially change "self"+ if (self) {+ if ((scheme == nil) || [scheme isEqualToString:@"*"]) {+ _scheme = nil;+ } else {+ _scheme = [NSRegularExpression regularExpressionWithPattern:[CDVWhitelistPattern regexFromPattern:scheme allowWildcards:NO] options:NSRegularExpressionCaseInsensitive error:nil];+ }+ if ([host isEqualToString:@"*"] || host == nil) {+ _host = nil;+ } else if ([host hasPrefix:@"*."]) {+ _host = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"([a-z0-9.-]*\\.)?%@", [CDVWhitelistPattern regexFromPattern:[host substringFromIndex:2] allowWildcards:false]] options:NSRegularExpressionCaseInsensitive error:nil];+ } else {+ _host = [NSRegularExpression regularExpressionWithPattern:[CDVWhitelistPattern regexFromPattern:host allowWildcards:NO] options:NSRegularExpressionCaseInsensitive error:nil];+ }+ if ((port == nil) || [port isEqualToString:@"*"]) {+ _port = nil;+ } else {+ _port = [[NSNumber alloc] initWithInteger:[port integerValue]];+ }+ if ((path == nil) || [path isEqualToString:@"/*"]) {+ _path = nil;+ } else {+ _path = [NSRegularExpression regularExpressionWithPattern:[CDVWhitelistPattern regexFromPattern:path allowWildcards:YES] options:0 error:nil];+ }+ }+ return self;+}++- (bool)matches:(NSURL*)url+{+ return (_scheme == nil || [_scheme numberOfMatchesInString:[url scheme] options:NSMatchingAnchored range:NSMakeRange(0, [[url scheme] length])]) &&+ (_host == nil || ([url host] != nil && [_host numberOfMatchesInString:[url host] options:NSMatchingAnchored range:NSMakeRange(0, [[url host] length])])) &&+ (_port == nil || [[url port] isEqualToNumber:_port]) &&+ (_path == nil || [_path numberOfMatchesInString:[url path] options:NSMatchingAnchored range:NSMakeRange(0, [[url path] length])])+ ;+}++@end++@interface CDVWhitelist ()++@property (nonatomic, readwrite, strong) NSMutableArray* whitelist;+@property (nonatomic, readwrite, strong) NSMutableSet* permittedSchemes;++- (void)addWhiteListEntry:(NSString*)pattern;++@end++@implementation CDVWhitelist++@synthesize whitelist, permittedSchemes, whitelistRejectionFormatString;++- (id)initWithArray:(NSArray*)array+{+ self = [super init];+ if (self) {+ self.whitelist = [[NSMutableArray alloc] init];+ self.permittedSchemes = [[NSMutableSet alloc] init];+ self.whitelistRejectionFormatString = kCDVDefaultWhitelistRejectionString;++ for (NSString* pattern in array) {+ [self addWhiteListEntry:pattern];+ }+ }+ return self;+}++- (BOOL)isIPv4Address:(NSString*)externalHost+{+ // an IPv4 address has 4 octets b.b.b.b where b is a number between 0 and 255.+ // for our purposes, b can also be the wildcard character '*'++ // we could use a regex to solve this problem but then I would have two problems+ // anyways, this is much clearer and maintainable+ NSArray* octets = [externalHost componentsSeparatedByString:@"."];+ NSUInteger num_octets = [octets count];++ // quick check+ if (num_octets != 4) {+ return NO;+ }++ // restrict number parsing to 0-255+ NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];+ [numberFormatter setMinimum:[NSNumber numberWithUnsignedInteger:0]];+ [numberFormatter setMaximum:[NSNumber numberWithUnsignedInteger:255]];++ // iterate through each octet, and test for a number between 0-255 or if it equals '*'+ for (NSUInteger i = 0; i < num_octets; ++i) {+ NSString* octet = [octets objectAtIndex:i];++ if ([octet isEqualToString:@"*"]) { // passes - check next octet+ continue;+ } else if ([numberFormatter numberFromString:octet] == nil) { // fails - not a number and not within our range, return+ return NO;+ }+ }++ return YES;+}++- (void)addWhiteListEntry:(NSString*)origin+{+ if (self.whitelist == nil) {+ return;+ }++ if ([origin isEqualToString:@"*"]) {+ NSLog(@"Unlimited access to network resources");+ self.whitelist = nil;+ self.permittedSchemes = nil;+ } else { // specific access+ NSRegularExpression* parts = [NSRegularExpression regularExpressionWithPattern:@"^((\\*|[A-Za-z-]+):/?/?)?(((\\*\\.)?[^*/:]+)|\\*)?(:(\\d+))?(/.*)?" options:0 error:nil];+ NSTextCheckingResult* m = [parts firstMatchInString:origin options:NSMatchingAnchored range:NSMakeRange(0, [origin length])];+ if (m != nil) {+ NSRange r;+ NSString* scheme = nil;+ r = [m rangeAtIndex:2];+ if (r.location != NSNotFound) {+ scheme = [origin substringWithRange:r];+ }++ NSString* host = nil;+ r = [m rangeAtIndex:3];+ if (r.location != NSNotFound) {+ host = [origin substringWithRange:r];+ }++ // Special case for two urls which are allowed to have empty hosts+ if (([scheme isEqualToString:@"file"] || [scheme isEqualToString:@"content"]) && (host == nil)) {+ host = @"*";+ }++ NSString* port = nil;+ r = [m rangeAtIndex:7];+ if (r.location != NSNotFound) {+ port = [origin substringWithRange:r];+ }++ NSString* path = nil;+ r = [m rangeAtIndex:8];+ if (r.location != NSNotFound) {+ path = [origin substringWithRange:r];+ }++ if (scheme == nil) {+ // XXX making it stupid friendly for people who forget to include protocol/SSL+ [self.whitelist addObject:[[CDVWhitelistPattern alloc] initWithScheme:@"http" host:host port:port path:path]];+ [self.whitelist addObject:[[CDVWhitelistPattern alloc] initWithScheme:@"https" host:host port:port path:path]];+ } else {+ [self.whitelist addObject:[[CDVWhitelistPattern alloc] initWithScheme:scheme host:host port:port path:path]];+ }++ if (self.permittedSchemes != nil) {+ if ([scheme isEqualToString:@"*"]) {+ self.permittedSchemes = nil;+ } else if (scheme != nil) {+ [self.permittedSchemes addObject:scheme];+ }+ }+ }+ }+}++- (BOOL)schemeIsAllowed:(NSString*)scheme+{+ if ([scheme isEqualToString:@"http"] ||+ [scheme isEqualToString:@"https"] ||+ [scheme isEqualToString:@"ftp"] ||+ [scheme isEqualToString:@"ftps"]) {+ return YES;+ }++ return (self.permittedSchemes == nil) || [self.permittedSchemes containsObject:scheme];+}++- (BOOL)URLIsAllowed:(NSURL*)url+{+ return [self URLIsAllowed:url logFailure:YES];+}++- (BOOL)URLIsAllowed:(NSURL*)url logFailure:(BOOL)logFailure+{+ // Shortcut acceptance: Are all urls whitelisted ("*" in whitelist)?+ if (whitelist == nil) {+ return YES;+ }++ // Shortcut rejection: Check that the scheme is supported+ NSString* scheme = [[url scheme] lowercaseString];+ if (![self schemeIsAllowed:scheme]) {+ if (logFailure) {+ NSLog(@"%@", [self errorStringForURL:url]);+ }+ return NO;+ }++ // http[s] and ftp[s] should also validate against the common set in the kCDVDefaultSchemeName list+ if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"] || [scheme isEqualToString:@"ftps"]) {+ NSURL* newUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@%@", kCDVDefaultSchemeName, [url host], [[url path] stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]]];+ // If it is allowed, we are done. If not, continue to check for the actual scheme-specific list+ if ([self URLIsAllowed:newUrl logFailure:NO]) {+ return YES;+ }+ }++ // Check the url against patterns in the whitelist+ for (CDVWhitelistPattern* p in self.whitelist) {+ if ([p matches:url]) {+ return YES;+ }+ }++ if (logFailure) {+ NSLog(@"%@", [self errorStringForURL:url]);+ }+ // if we got here, the url host is not in the white-list, do nothing+ return NO;+}++- (NSString*)errorStringForURL:(NSURL*)url+{+ return [NSString stringWithFormat:self.whitelistRejectionFormatString, [url absoluteString]];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.h b/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.hnew file mode 100644index 000000000..9be2be2dc--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.h@@ -0,0 +1,35 @@+/*+ 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 <UIKit/UIKit.h>++@interface NSDictionary (CordovaPreferences)++- (id)cordovaSettingForKey:(NSString*)key;+- (BOOL)cordovaBoolSettingForKey:(NSString*)key defaultValue:(BOOL)defaultValue;+- (CGFloat)cordovaFloatSettingForKey:(NSString*)key defaultValue:(CGFloat)defaultValue;++@end++@interface NSMutableDictionary (CordovaPreferences)++- (void)setCordovaSetting:(id)value forKey:(NSString*)key;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.m b/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.mnew file mode 100644index 000000000..dcac40f12--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.m@@ -0,0 +1,63 @@+/*+ 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 "NSDictionary+CordovaPreferences.h"+#import <Foundation/Foundation.h>++@implementation NSDictionary (CordovaPreferences)++- (id)cordovaSettingForKey:(NSString*)key+{+ return [self objectForKey:[key lowercaseString]];+}++- (BOOL)cordovaBoolSettingForKey:(NSString*)key defaultValue:(BOOL)defaultValue+{+ BOOL value = defaultValue;+ id prefObj = [self cordovaSettingForKey:key];++ if (prefObj != nil) {+ value = [(NSNumber*)prefObj boolValue];+ }++ return value;+}++- (CGFloat)cordovaFloatSettingForKey:(NSString*)key defaultValue:(CGFloat)defaultValue+{+ CGFloat value = defaultValue;+ id prefObj = [self cordovaSettingForKey:key];++ if (prefObj != nil) {+ value = [prefObj floatValue];+ }++ return value;+}++@end++@implementation NSMutableDictionary (CordovaPreferences)++- (void)setCordovaSetting:(id)value forKey:(NSString*)key+{+ [self setObject:value forKey:[key lowercaseString]];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/NSMutableArray+QueueAdditions.h b/cordova/platforms/ios/CordovaLib/Classes/Public/NSMutableArray+QueueAdditions.hnew file mode 100644index 000000000..79e65164e--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/NSMutableArray+QueueAdditions.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 <Foundation/Foundation.h>++@interface NSMutableArray (QueueAdditions)++- (id)cdv_pop;+- (id)cdv_queueHead;+- (id)cdv_dequeue;+- (void)cdv_enqueue:(id)obj;++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/NSMutableArray+QueueAdditions.m b/cordova/platforms/ios/CordovaLib/Classes/Public/NSMutableArray+QueueAdditions.mnew file mode 100644index 000000000..2b3acdc0f--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/NSMutableArray+QueueAdditions.m@@ -0,0 +1,58 @@+/*+ 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 "NSMutableArray+QueueAdditions.h"++@implementation NSMutableArray (QueueAdditions)++- (id)cdv_queueHead+{+ if ([self count] == 0) {+ return nil;+ }++ return [self objectAtIndex:0];+}++- (__autoreleasing id)cdv_dequeue+{+ if ([self count] == 0) {+ return nil;+ }++ id head = [self objectAtIndex:0];+ if (head != nil) {+ // [[head retain] autorelease]; ARC - the __autoreleasing on the return value should so the same thing+ [self removeObjectAtIndex:0];+ }++ return head;+}++- (id)cdv_pop+{+ return [self cdv_dequeue];+}++- (void)cdv_enqueue:(id)object+{+ [self addObject:object];+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxprojnew file mode 100644index 000000000..cb6716388--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj@@ -0,0 +1,793 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 48;+ objects = {++/* Begin PBXBuildFile section */+ 28BFF9141F355A4E00DDF01A /* CDVLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 28BFF9121F355A4E00DDF01A /* CDVLogger.h */; };+ 28BFF9151F355A4E00DDF01A /* CDVLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 28BFF9131F355A4E00DDF01A /* CDVLogger.m */; };+ 30193A501AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */; };+ 30193A511AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */; };+ 3093E2231B16D6A3003F381A /* CDVIntentAndNavigationFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */; };+ 3093E2241B16D6A3003F381A /* CDVIntentAndNavigationFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */; };+ 7E7F69B61ABA35D8007546F4 /* CDVLocalStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */; };+ 7E7F69B81ABA368F007546F4 /* CDVUIWebViewEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */; };+ 7E7F69B91ABA3692007546F4 /* CDVHandleOpenURL.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF81AB9028C008C4574 /* CDVHandleOpenURL.h */; };+ 7ED95D021AB9028C008C4574 /* CDVDebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF21AB9028C008C4574 /* CDVDebug.h */; };+ 7ED95D031AB9028C008C4574 /* CDVJSON_private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF31AB9028C008C4574 /* CDVJSON_private.h */; };+ 7ED95D041AB9028C008C4574 /* CDVJSON_private.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CF41AB9028C008C4574 /* CDVJSON_private.m */; };+ 7ED95D051AB9028C008C4574 /* CDVPlugin+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF51AB9028C008C4574 /* CDVPlugin+Private.h */; };+ 7ED95D071AB9028C008C4574 /* CDVHandleOpenURL.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CF91AB9028C008C4574 /* CDVHandleOpenURL.m */; };+ 7ED95D091AB9028C008C4574 /* CDVLocalStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */; };+ 7ED95D0A1AB9028C008C4574 /* CDVUIWebViewDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D0B1AB9028C008C4574 /* CDVUIWebViewDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */; };+ 7ED95D0D1AB9028C008C4574 /* CDVUIWebViewEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */; };+ 7ED95D351AB9029B008C4574 /* CDV.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D0F1AB9029B008C4574 /* CDV.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D361AB9029B008C4574 /* CDVAppDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D101AB9029B008C4574 /* CDVAppDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D371AB9029B008C4574 /* CDVAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D111AB9029B008C4574 /* CDVAppDelegate.m */; };+ 7ED95D381AB9029B008C4574 /* CDVAvailability.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D121AB9029B008C4574 /* CDVAvailability.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D391AB9029B008C4574 /* CDVAvailabilityDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D131AB9029B008C4574 /* CDVAvailabilityDeprecated.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D3A1AB9029B008C4574 /* CDVCommandDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D141AB9029B008C4574 /* CDVCommandDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D3B1AB9029B008C4574 /* CDVCommandDelegateImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D151AB9029B008C4574 /* CDVCommandDelegateImpl.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D3C1AB9029B008C4574 /* CDVCommandDelegateImpl.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D161AB9029B008C4574 /* CDVCommandDelegateImpl.m */; };+ 7ED95D3D1AB9029B008C4574 /* CDVCommandQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D171AB9029B008C4574 /* CDVCommandQueue.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D3E1AB9029B008C4574 /* CDVCommandQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D181AB9029B008C4574 /* CDVCommandQueue.m */; };+ 7ED95D3F1AB9029B008C4574 /* CDVConfigParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D191AB9029B008C4574 /* CDVConfigParser.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D401AB9029B008C4574 /* CDVConfigParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D1A1AB9029B008C4574 /* CDVConfigParser.m */; };+ 7ED95D411AB9029B008C4574 /* CDVInvokedUrlCommand.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D1B1AB9029B008C4574 /* CDVInvokedUrlCommand.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D421AB9029B008C4574 /* CDVInvokedUrlCommand.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D1C1AB9029B008C4574 /* CDVInvokedUrlCommand.m */; };+ 7ED95D431AB9029B008C4574 /* CDVPlugin+Resources.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D1D1AB9029B008C4574 /* CDVPlugin+Resources.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D441AB9029B008C4574 /* CDVPlugin+Resources.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D1E1AB9029B008C4574 /* CDVPlugin+Resources.m */; };+ 7ED95D451AB9029B008C4574 /* CDVPlugin.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D1F1AB9029B008C4574 /* CDVPlugin.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D461AB9029B008C4574 /* CDVPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D201AB9029B008C4574 /* CDVPlugin.m */; };+ 7ED95D471AB9029B008C4574 /* CDVPluginResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D211AB9029B008C4574 /* CDVPluginResult.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D481AB9029B008C4574 /* CDVPluginResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D221AB9029B008C4574 /* CDVPluginResult.m */; };+ 7ED95D491AB9029B008C4574 /* CDVScreenOrientationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D4A1AB9029B008C4574 /* CDVTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D241AB9029B008C4574 /* CDVTimer.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D4B1AB9029B008C4574 /* CDVTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D251AB9029B008C4574 /* CDVTimer.m */; };+ 7ED95D4C1AB9029B008C4574 /* CDVURLProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D4D1AB9029B008C4574 /* CDVURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */; };+ 7ED95D4E1AB9029B008C4574 /* CDVUserAgentUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D4F1AB9029B008C4574 /* CDVUserAgentUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */; };+ 7ED95D501AB9029B008C4574 /* CDVViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2A1AB9029B008C4574 /* CDVViewController.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D511AB9029B008C4574 /* CDVViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D2B1AB9029B008C4574 /* CDVViewController.m */; };+ 7ED95D521AB9029B008C4574 /* CDVWebViewEngineProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D531AB9029B008C4574 /* CDVWhitelist.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2D1AB9029B008C4574 /* CDVWhitelist.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D541AB9029B008C4574 /* CDVWhitelist.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D2E1AB9029B008C4574 /* CDVWhitelist.m */; };+ 7ED95D571AB9029B008C4574 /* NSDictionary+CordovaPreferences.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D311AB9029B008C4574 /* NSDictionary+CordovaPreferences.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D581AB9029B008C4574 /* NSDictionary+CordovaPreferences.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D321AB9029B008C4574 /* NSDictionary+CordovaPreferences.m */; };+ 7ED95D591AB9029B008C4574 /* NSMutableArray+QueueAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D331AB9029B008C4574 /* NSMutableArray+QueueAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 7ED95D5A1AB9029B008C4574 /* NSMutableArray+QueueAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D341AB9029B008C4574 /* NSMutableArray+QueueAdditions.m */; };+ 9052DE712150D040008E83D4 /* CDVAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D111AB9029B008C4574 /* CDVAppDelegate.m */; };+ 9052DE722150D040008E83D4 /* CDVCommandDelegateImpl.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D161AB9029B008C4574 /* CDVCommandDelegateImpl.m */; };+ 9052DE732150D040008E83D4 /* CDVCommandQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D181AB9029B008C4574 /* CDVCommandQueue.m */; };+ 9052DE742150D040008E83D4 /* CDVConfigParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D1A1AB9029B008C4574 /* CDVConfigParser.m */; };+ 9052DE752150D040008E83D4 /* CDVInvokedUrlCommand.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D1C1AB9029B008C4574 /* CDVInvokedUrlCommand.m */; };+ 9052DE762150D040008E83D4 /* CDVPlugin+Resources.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D1E1AB9029B008C4574 /* CDVPlugin+Resources.m */; };+ 9052DE772150D040008E83D4 /* CDVPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D201AB9029B008C4574 /* CDVPlugin.m */; };+ 9052DE782150D040008E83D4 /* CDVPluginResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D221AB9029B008C4574 /* CDVPluginResult.m */; };+ 9052DE792150D040008E83D4 /* CDVTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D251AB9029B008C4574 /* CDVTimer.m */; };+ 9052DE7A2150D040008E83D4 /* CDVURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */; };+ 9052DE7B2150D040008E83D4 /* CDVUserAgentUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */; };+ 9052DE7C2150D040008E83D4 /* CDVViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D2B1AB9029B008C4574 /* CDVViewController.m */; };+ 9052DE7D2150D040008E83D4 /* CDVWhitelist.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D2E1AB9029B008C4574 /* CDVWhitelist.m */; };+ 9052DE7E2150D040008E83D4 /* NSDictionary+CordovaPreferences.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D321AB9029B008C4574 /* NSDictionary+CordovaPreferences.m */; };+ 9052DE7F2150D040008E83D4 /* NSMutableArray+QueueAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D341AB9029B008C4574 /* NSMutableArray+QueueAdditions.m */; };+ 9052DE802150D040008E83D4 /* CDVJSON_private.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CF41AB9028C008C4574 /* CDVJSON_private.m */; };+ 9052DE812150D040008E83D4 /* CDVLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 28BFF9131F355A4E00DDF01A /* CDVLogger.m */; };+ 9052DE822150D040008E83D4 /* CDVGestureHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = A3B082D31BB15CEA00D8DC35 /* CDVGestureHandler.m */; };+ 9052DE832150D040008E83D4 /* CDVIntentAndNavigationFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */; };+ 9052DE842150D040008E83D4 /* CDVHandleOpenURL.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CF91AB9028C008C4574 /* CDVHandleOpenURL.m */; };+ 9052DE852150D040008E83D4 /* CDVLocalStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */; };+ 9052DE862150D040008E83D4 /* CDVUIWebViewNavigationDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */; };+ 9052DE872150D040008E83D4 /* CDVUIWebViewDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */; };+ 9052DE882150D040008E83D4 /* CDVUIWebViewEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */; };+ 9052DE892150D06B008E83D4 /* CDVDebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF21AB9028C008C4574 /* CDVDebug.h */; };+ 9052DE8A2150D06B008E83D4 /* CDVJSON_private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF31AB9028C008C4574 /* CDVJSON_private.h */; };+ 9052DE8B2150D06B008E83D4 /* CDVPlugin+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF51AB9028C008C4574 /* CDVPlugin+Private.h */; };+ 9052DE8C2150D06B008E83D4 /* CDVLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 28BFF9121F355A4E00DDF01A /* CDVLogger.h */; };+ 9052DE8D2150D06B008E83D4 /* CDVGestureHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = A3B082D21BB15CEA00D8DC35 /* CDVGestureHandler.h */; };+ 9052DE8E2150D06B008E83D4 /* CDVIntentAndNavigationFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */; };+ 9052DE8F2150D06B008E83D4 /* CDVHandleOpenURL.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF81AB9028C008C4574 /* CDVHandleOpenURL.h */; };+ 9052DE902150D06B008E83D4 /* CDVLocalStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */; };+ 9052DE912150D06B008E83D4 /* CDVUIWebViewNavigationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */; };+ 9052DE922150D06B008E83D4 /* CDVUIWebViewEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */; };+ A3B082D41BB15CEA00D8DC35 /* CDVGestureHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = A3B082D21BB15CEA00D8DC35 /* CDVGestureHandler.h */; };+ A3B082D51BB15CEA00D8DC35 /* CDVGestureHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = A3B082D31BB15CEA00D8DC35 /* CDVGestureHandler.m */; };+ C0C01EB61E3911D50056E6CB /* Cordova.h in Headers */ = {isa = PBXBuildFile; fileRef = C0C01EB41E3911D50056E6CB /* Cordova.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EBB1E39131A0056E6CB /* CDV.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D0F1AB9029B008C4574 /* CDV.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EBC1E39131A0056E6CB /* CDVAppDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D101AB9029B008C4574 /* CDVAppDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EBD1E39131A0056E6CB /* CDVAvailability.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D121AB9029B008C4574 /* CDVAvailability.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EBE1E39131A0056E6CB /* CDVAvailabilityDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D131AB9029B008C4574 /* CDVAvailabilityDeprecated.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EBF1E39131A0056E6CB /* CDVCommandDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D141AB9029B008C4574 /* CDVCommandDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC01E39131A0056E6CB /* CDVCommandDelegateImpl.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D151AB9029B008C4574 /* CDVCommandDelegateImpl.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC11E39131A0056E6CB /* CDVCommandQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D171AB9029B008C4574 /* CDVCommandQueue.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC21E39131A0056E6CB /* CDVConfigParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D191AB9029B008C4574 /* CDVConfigParser.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC31E39131A0056E6CB /* CDVInvokedUrlCommand.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D1B1AB9029B008C4574 /* CDVInvokedUrlCommand.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC41E39131A0056E6CB /* CDVPlugin+Resources.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D1D1AB9029B008C4574 /* CDVPlugin+Resources.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC51E39131A0056E6CB /* CDVPlugin.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D1F1AB9029B008C4574 /* CDVPlugin.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC61E39131A0056E6CB /* CDVPluginResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D211AB9029B008C4574 /* CDVPluginResult.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC71E39131A0056E6CB /* CDVScreenOrientationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC81E39131A0056E6CB /* CDVTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D241AB9029B008C4574 /* CDVTimer.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01EC91E39131A0056E6CB /* CDVURLProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01ECA1E39131A0056E6CB /* CDVUserAgentUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01ECB1E39131A0056E6CB /* CDVViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2A1AB9029B008C4574 /* CDVViewController.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01ECC1E39131A0056E6CB /* CDVWebViewEngineProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01ECD1E39131A0056E6CB /* CDVWhitelist.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2D1AB9029B008C4574 /* CDVWhitelist.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01ECE1E39131A0056E6CB /* NSDictionary+CordovaPreferences.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D311AB9029B008C4574 /* NSDictionary+CordovaPreferences.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01ECF1E39131A0056E6CB /* NSMutableArray+QueueAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D331AB9029B008C4574 /* NSMutableArray+QueueAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; };+ C0C01ED01E3913610056E6CB /* CDVUIWebViewDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+/* End PBXBuildFile section */++/* Begin PBXFileReference section */+ 28BFF9121F355A4E00DDF01A /* CDVLogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVLogger.h; sourceTree = "<group>"; };+ 28BFF9131F355A4E00DDF01A /* CDVLogger.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVLogger.m; sourceTree = "<group>"; };+ 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUIWebViewNavigationDelegate.m; sourceTree = "<group>"; };+ 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUIWebViewNavigationDelegate.h; sourceTree = "<group>"; };+ 3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVIntentAndNavigationFilter.h; sourceTree = "<group>"; };+ 3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVIntentAndNavigationFilter.m; sourceTree = "<group>"; };+ 68A32D7114102E1C006B237C /* libCordova.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libCordova.a; sourceTree = BUILT_PRODUCTS_DIR; };+ 7ED95CF21AB9028C008C4574 /* CDVDebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVDebug.h; sourceTree = "<group>"; };+ 7ED95CF31AB9028C008C4574 /* CDVJSON_private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVJSON_private.h; sourceTree = "<group>"; };+ 7ED95CF41AB9028C008C4574 /* CDVJSON_private.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVJSON_private.m; sourceTree = "<group>"; };+ 7ED95CF51AB9028C008C4574 /* CDVPlugin+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CDVPlugin+Private.h"; sourceTree = "<group>"; };+ 7ED95CF81AB9028C008C4574 /* CDVHandleOpenURL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVHandleOpenURL.h; sourceTree = "<group>"; };+ 7ED95CF91AB9028C008C4574 /* CDVHandleOpenURL.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVHandleOpenURL.m; sourceTree = "<group>"; };+ 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVLocalStorage.h; sourceTree = "<group>"; };+ 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVLocalStorage.m; sourceTree = "<group>"; };+ 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUIWebViewDelegate.h; sourceTree = "<group>"; };+ 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUIWebViewDelegate.m; sourceTree = "<group>"; };+ 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUIWebViewEngine.h; sourceTree = "<group>"; };+ 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUIWebViewEngine.m; sourceTree = "<group>"; };+ 7ED95D0F1AB9029B008C4574 /* CDV.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDV.h; sourceTree = "<group>"; };+ 7ED95D101AB9029B008C4574 /* CDVAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVAppDelegate.h; sourceTree = "<group>"; };+ 7ED95D111AB9029B008C4574 /* CDVAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVAppDelegate.m; sourceTree = "<group>"; };+ 7ED95D121AB9029B008C4574 /* CDVAvailability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVAvailability.h; sourceTree = "<group>"; };+ 7ED95D131AB9029B008C4574 /* CDVAvailabilityDeprecated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVAvailabilityDeprecated.h; sourceTree = "<group>"; };+ 7ED95D141AB9029B008C4574 /* CDVCommandDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVCommandDelegate.h; sourceTree = "<group>"; };+ 7ED95D151AB9029B008C4574 /* CDVCommandDelegateImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVCommandDelegateImpl.h; sourceTree = "<group>"; };+ 7ED95D161AB9029B008C4574 /* CDVCommandDelegateImpl.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVCommandDelegateImpl.m; sourceTree = "<group>"; };+ 7ED95D171AB9029B008C4574 /* CDVCommandQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVCommandQueue.h; sourceTree = "<group>"; };+ 7ED95D181AB9029B008C4574 /* CDVCommandQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVCommandQueue.m; sourceTree = "<group>"; };+ 7ED95D191AB9029B008C4574 /* CDVConfigParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVConfigParser.h; sourceTree = "<group>"; };+ 7ED95D1A1AB9029B008C4574 /* CDVConfigParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVConfigParser.m; sourceTree = "<group>"; };+ 7ED95D1B1AB9029B008C4574 /* CDVInvokedUrlCommand.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVInvokedUrlCommand.h; sourceTree = "<group>"; };+ 7ED95D1C1AB9029B008C4574 /* CDVInvokedUrlCommand.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVInvokedUrlCommand.m; sourceTree = "<group>"; };+ 7ED95D1D1AB9029B008C4574 /* CDVPlugin+Resources.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CDVPlugin+Resources.h"; sourceTree = "<group>"; };+ 7ED95D1E1AB9029B008C4574 /* CDVPlugin+Resources.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "CDVPlugin+Resources.m"; sourceTree = "<group>"; };+ 7ED95D1F1AB9029B008C4574 /* CDVPlugin.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVPlugin.h; sourceTree = "<group>"; };+ 7ED95D201AB9029B008C4574 /* CDVPlugin.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVPlugin.m; sourceTree = "<group>"; };+ 7ED95D211AB9029B008C4574 /* CDVPluginResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVPluginResult.h; sourceTree = "<group>"; };+ 7ED95D221AB9029B008C4574 /* CDVPluginResult.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVPluginResult.m; sourceTree = "<group>"; };+ 7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVScreenOrientationDelegate.h; sourceTree = "<group>"; };+ 7ED95D241AB9029B008C4574 /* CDVTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVTimer.h; sourceTree = "<group>"; };+ 7ED95D251AB9029B008C4574 /* CDVTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVTimer.m; sourceTree = "<group>"; };+ 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVURLProtocol.h; sourceTree = "<group>"; };+ 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVURLProtocol.m; sourceTree = "<group>"; };+ 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUserAgentUtil.h; sourceTree = "<group>"; };+ 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUserAgentUtil.m; sourceTree = "<group>"; };+ 7ED95D2A1AB9029B008C4574 /* CDVViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVViewController.h; sourceTree = "<group>"; };+ 7ED95D2B1AB9029B008C4574 /* CDVViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVViewController.m; sourceTree = "<group>"; };+ 7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVWebViewEngineProtocol.h; sourceTree = "<group>"; };+ 7ED95D2D1AB9029B008C4574 /* CDVWhitelist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVWhitelist.h; sourceTree = "<group>"; };+ 7ED95D2E1AB9029B008C4574 /* CDVWhitelist.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVWhitelist.m; sourceTree = "<group>"; };+ 7ED95D311AB9029B008C4574 /* NSDictionary+CordovaPreferences.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSDictionary+CordovaPreferences.h"; sourceTree = "<group>"; };+ 7ED95D321AB9029B008C4574 /* NSDictionary+CordovaPreferences.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSDictionary+CordovaPreferences.m"; sourceTree = "<group>"; };+ 7ED95D331AB9029B008C4574 /* NSMutableArray+QueueAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSMutableArray+QueueAdditions.h"; sourceTree = "<group>"; };+ 7ED95D341AB9029B008C4574 /* NSMutableArray+QueueAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSMutableArray+QueueAdditions.m"; sourceTree = "<group>"; };+ A3B082D21BB15CEA00D8DC35 /* CDVGestureHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVGestureHandler.h; sourceTree = "<group>"; };+ A3B082D31BB15CEA00D8DC35 /* CDVGestureHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVGestureHandler.m; sourceTree = "<group>"; };+ AA747D9E0F9514B9006C5449 /* CordovaLib_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CordovaLib_Prefix.pch; sourceTree = SOURCE_ROOT; };+ C0C01EB21E3911D50056E6CB /* Cordova.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Cordova.framework; sourceTree = BUILT_PRODUCTS_DIR; };+ C0C01EB41E3911D50056E6CB /* Cordova.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Cordova.h; sourceTree = "<group>"; };+ C0C01EB51E3911D50056E6CB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };+/* End PBXFileReference section */++/* Begin PBXFrameworksBuildPhase section */+ C0C01EAE1E3911D50056E6CB /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ D2AAC07C0554694100DB518D /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ 034768DFFF38A50411DB9C8B /* Products */ = {+ isa = PBXGroup;+ children = (+ 68A32D7114102E1C006B237C /* libCordova.a */,+ C0C01EB21E3911D50056E6CB /* Cordova.framework */,+ );+ name = Products;+ sourceTree = "<group>";+ };+ 0867D691FE84028FC02AAC07 = {+ isa = PBXGroup;+ children = (+ 7ED95D0E1AB9029B008C4574 /* Public */,+ 7ED95CF11AB9028C008C4574 /* Private */,+ C0C01EB31E3911D50056E6CB /* Cordova */,+ 034768DFFF38A50411DB9C8B /* Products */,+ );+ sourceTree = "<group>";+ };+ 28BFF9111F355A1D00DDF01A /* CDVLogger */ = {+ isa = PBXGroup;+ children = (+ 28BFF9121F355A4E00DDF01A /* CDVLogger.h */,+ 28BFF9131F355A4E00DDF01A /* CDVLogger.m */,+ );+ path = CDVLogger;+ sourceTree = "<group>";+ };+ 3093E2201B16D6A3003F381A /* CDVIntentAndNavigationFilter */ = {+ isa = PBXGroup;+ children = (+ 3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */,+ 3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */,+ );+ path = CDVIntentAndNavigationFilter;+ sourceTree = "<group>";+ };+ 7ED95CF11AB9028C008C4574 /* Private */ = {+ isa = PBXGroup;+ children = (+ AA747D9E0F9514B9006C5449 /* CordovaLib_Prefix.pch */,+ 7ED95CF21AB9028C008C4574 /* CDVDebug.h */,+ 7ED95CF31AB9028C008C4574 /* CDVJSON_private.h */,+ 7ED95CF41AB9028C008C4574 /* CDVJSON_private.m */,+ 7ED95CF51AB9028C008C4574 /* CDVPlugin+Private.h */,+ 7ED95CF61AB9028C008C4574 /* Plugins */,+ );+ name = Private;+ path = Classes/Private;+ sourceTree = "<group>";+ };+ 7ED95CF61AB9028C008C4574 /* Plugins */ = {+ isa = PBXGroup;+ children = (+ 28BFF9111F355A1D00DDF01A /* CDVLogger */,+ A3B082D11BB15CEA00D8DC35 /* CDVGestureHandler */,+ 3093E2201B16D6A3003F381A /* CDVIntentAndNavigationFilter */,+ 7ED95CF71AB9028C008C4574 /* CDVHandleOpenURL */,+ 7ED95CFA1AB9028C008C4574 /* CDVLocalStorage */,+ 7ED95CFD1AB9028C008C4574 /* CDVUIWebViewEngine */,+ );+ path = Plugins;+ sourceTree = "<group>";+ };+ 7ED95CF71AB9028C008C4574 /* CDVHandleOpenURL */ = {+ isa = PBXGroup;+ children = (+ 7ED95CF81AB9028C008C4574 /* CDVHandleOpenURL.h */,+ 7ED95CF91AB9028C008C4574 /* CDVHandleOpenURL.m */,+ );+ path = CDVHandleOpenURL;+ sourceTree = "<group>";+ };+ 7ED95CFA1AB9028C008C4574 /* CDVLocalStorage */ = {+ isa = PBXGroup;+ children = (+ 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */,+ 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */,+ );+ path = CDVLocalStorage;+ sourceTree = "<group>";+ };+ 7ED95CFD1AB9028C008C4574 /* CDVUIWebViewEngine */ = {+ isa = PBXGroup;+ children = (+ 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */,+ 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */,+ 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */,+ 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */,+ 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */,+ 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */,+ );+ path = CDVUIWebViewEngine;+ sourceTree = "<group>";+ };+ 7ED95D0E1AB9029B008C4574 /* Public */ = {+ isa = PBXGroup;+ children = (+ 7ED95D0F1AB9029B008C4574 /* CDV.h */,+ 7ED95D101AB9029B008C4574 /* CDVAppDelegate.h */,+ 7ED95D111AB9029B008C4574 /* CDVAppDelegate.m */,+ 7ED95D121AB9029B008C4574 /* CDVAvailability.h */,+ 7ED95D131AB9029B008C4574 /* CDVAvailabilityDeprecated.h */,+ 7ED95D141AB9029B008C4574 /* CDVCommandDelegate.h */,+ 7ED95D151AB9029B008C4574 /* CDVCommandDelegateImpl.h */,+ 7ED95D161AB9029B008C4574 /* CDVCommandDelegateImpl.m */,+ 7ED95D171AB9029B008C4574 /* CDVCommandQueue.h */,+ 7ED95D181AB9029B008C4574 /* CDVCommandQueue.m */,+ 7ED95D191AB9029B008C4574 /* CDVConfigParser.h */,+ 7ED95D1A1AB9029B008C4574 /* CDVConfigParser.m */,+ 7ED95D1B1AB9029B008C4574 /* CDVInvokedUrlCommand.h */,+ 7ED95D1C1AB9029B008C4574 /* CDVInvokedUrlCommand.m */,+ 7ED95D1D1AB9029B008C4574 /* CDVPlugin+Resources.h */,+ 7ED95D1E1AB9029B008C4574 /* CDVPlugin+Resources.m */,+ 7ED95D1F1AB9029B008C4574 /* CDVPlugin.h */,+ 7ED95D201AB9029B008C4574 /* CDVPlugin.m */,+ 7ED95D211AB9029B008C4574 /* CDVPluginResult.h */,+ 7ED95D221AB9029B008C4574 /* CDVPluginResult.m */,+ 7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */,+ 7ED95D241AB9029B008C4574 /* CDVTimer.h */,+ 7ED95D251AB9029B008C4574 /* CDVTimer.m */,+ 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */,+ 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */,+ 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */,+ 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */,+ 7ED95D2A1AB9029B008C4574 /* CDVViewController.h */,+ 7ED95D2B1AB9029B008C4574 /* CDVViewController.m */,+ 7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */,+ 7ED95D2D1AB9029B008C4574 /* CDVWhitelist.h */,+ 7ED95D2E1AB9029B008C4574 /* CDVWhitelist.m */,+ 7ED95D311AB9029B008C4574 /* NSDictionary+CordovaPreferences.h */,+ 7ED95D321AB9029B008C4574 /* NSDictionary+CordovaPreferences.m */,+ 7ED95D331AB9029B008C4574 /* NSMutableArray+QueueAdditions.h */,+ 7ED95D341AB9029B008C4574 /* NSMutableArray+QueueAdditions.m */,+ );+ name = Public;+ path = Classes/Public;+ sourceTree = "<group>";+ };+ A3B082D11BB15CEA00D8DC35 /* CDVGestureHandler */ = {+ isa = PBXGroup;+ children = (+ A3B082D21BB15CEA00D8DC35 /* CDVGestureHandler.h */,+ A3B082D31BB15CEA00D8DC35 /* CDVGestureHandler.m */,+ );+ path = CDVGestureHandler;+ sourceTree = "<group>";+ };+ C0C01EB31E3911D50056E6CB /* Cordova */ = {+ isa = PBXGroup;+ children = (+ C0C01EB41E3911D50056E6CB /* Cordova.h */,+ C0C01EB51E3911D50056E6CB /* Info.plist */,+ );+ path = Cordova;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXHeadersBuildPhase section */+ C0C01EAF1E3911D50056E6CB /* Headers */ = {+ isa = PBXHeadersBuildPhase;+ buildActionMask = 2147483647;+ files = (+ C0C01EB61E3911D50056E6CB /* Cordova.h in Headers */,+ C0C01EBB1E39131A0056E6CB /* CDV.h in Headers */,+ C0C01EBC1E39131A0056E6CB /* CDVAppDelegate.h in Headers */,+ C0C01EBD1E39131A0056E6CB /* CDVAvailability.h in Headers */,+ C0C01EBE1E39131A0056E6CB /* CDVAvailabilityDeprecated.h in Headers */,+ C0C01EBF1E39131A0056E6CB /* CDVCommandDelegate.h in Headers */,+ C0C01EC01E39131A0056E6CB /* CDVCommandDelegateImpl.h in Headers */,+ C0C01EC11E39131A0056E6CB /* CDVCommandQueue.h in Headers */,+ C0C01EC21E39131A0056E6CB /* CDVConfigParser.h in Headers */,+ C0C01EC31E39131A0056E6CB /* CDVInvokedUrlCommand.h in Headers */,+ C0C01EC41E39131A0056E6CB /* CDVPlugin+Resources.h in Headers */,+ C0C01EC51E39131A0056E6CB /* CDVPlugin.h in Headers */,+ C0C01EC61E39131A0056E6CB /* CDVPluginResult.h in Headers */,+ C0C01EC71E39131A0056E6CB /* CDVScreenOrientationDelegate.h in Headers */,+ C0C01EC81E39131A0056E6CB /* CDVTimer.h in Headers */,+ C0C01EC91E39131A0056E6CB /* CDVURLProtocol.h in Headers */,+ C0C01ECA1E39131A0056E6CB /* CDVUserAgentUtil.h in Headers */,+ C0C01ECB1E39131A0056E6CB /* CDVViewController.h in Headers */,+ C0C01ECC1E39131A0056E6CB /* CDVWebViewEngineProtocol.h in Headers */,+ C0C01ECD1E39131A0056E6CB /* CDVWhitelist.h in Headers */,+ C0C01ECE1E39131A0056E6CB /* NSDictionary+CordovaPreferences.h in Headers */,+ C0C01ECF1E39131A0056E6CB /* NSMutableArray+QueueAdditions.h in Headers */,+ 9052DE892150D06B008E83D4 /* CDVDebug.h in Headers */,+ 9052DE8A2150D06B008E83D4 /* CDVJSON_private.h in Headers */,+ 9052DE8B2150D06B008E83D4 /* CDVPlugin+Private.h in Headers */,+ 9052DE8C2150D06B008E83D4 /* CDVLogger.h in Headers */,+ 9052DE8D2150D06B008E83D4 /* CDVGestureHandler.h in Headers */,+ 9052DE8E2150D06B008E83D4 /* CDVIntentAndNavigationFilter.h in Headers */,+ 9052DE8F2150D06B008E83D4 /* CDVHandleOpenURL.h in Headers */,+ 9052DE902150D06B008E83D4 /* CDVLocalStorage.h in Headers */,+ 9052DE912150D06B008E83D4 /* CDVUIWebViewNavigationDelegate.h in Headers */,+ C0C01ED01E3913610056E6CB /* CDVUIWebViewDelegate.h in Headers */,+ 9052DE922150D06B008E83D4 /* CDVUIWebViewEngine.h in Headers */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ D2AAC07A0554694100DB518D /* Headers */ = {+ isa = PBXHeadersBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 7ED95D351AB9029B008C4574 /* CDV.h in Headers */,+ 7ED95D361AB9029B008C4574 /* CDVAppDelegate.h in Headers */,+ 7ED95D381AB9029B008C4574 /* CDVAvailability.h in Headers */,+ 7ED95D391AB9029B008C4574 /* CDVAvailabilityDeprecated.h in Headers */,+ 7ED95D3A1AB9029B008C4574 /* CDVCommandDelegate.h in Headers */,+ 7ED95D3B1AB9029B008C4574 /* CDVCommandDelegateImpl.h in Headers */,+ 7ED95D3D1AB9029B008C4574 /* CDVCommandQueue.h in Headers */,+ 7ED95D3F1AB9029B008C4574 /* CDVConfigParser.h in Headers */,+ 7ED95D411AB9029B008C4574 /* CDVInvokedUrlCommand.h in Headers */,+ 7ED95D431AB9029B008C4574 /* CDVPlugin+Resources.h in Headers */,+ 7ED95D451AB9029B008C4574 /* CDVPlugin.h in Headers */,+ 7ED95D471AB9029B008C4574 /* CDVPluginResult.h in Headers */,+ 7ED95D491AB9029B008C4574 /* CDVScreenOrientationDelegate.h in Headers */,+ 7ED95D4A1AB9029B008C4574 /* CDVTimer.h in Headers */,+ 7ED95D4C1AB9029B008C4574 /* CDVURLProtocol.h in Headers */,+ 7ED95D4E1AB9029B008C4574 /* CDVUserAgentUtil.h in Headers */,+ 7ED95D501AB9029B008C4574 /* CDVViewController.h in Headers */,+ 7ED95D521AB9029B008C4574 /* CDVWebViewEngineProtocol.h in Headers */,+ 7ED95D531AB9029B008C4574 /* CDVWhitelist.h in Headers */,+ 7ED95D571AB9029B008C4574 /* NSDictionary+CordovaPreferences.h in Headers */,+ 7ED95D591AB9029B008C4574 /* NSMutableArray+QueueAdditions.h in Headers */,+ 7ED95D021AB9028C008C4574 /* CDVDebug.h in Headers */,+ 7ED95D031AB9028C008C4574 /* CDVJSON_private.h in Headers */,+ 7ED95D051AB9028C008C4574 /* CDVPlugin+Private.h in Headers */,+ 28BFF9141F355A4E00DDF01A /* CDVLogger.h in Headers */,+ A3B082D41BB15CEA00D8DC35 /* CDVGestureHandler.h in Headers */,+ 3093E2231B16D6A3003F381A /* CDVIntentAndNavigationFilter.h in Headers */,+ 7E7F69B91ABA3692007546F4 /* CDVHandleOpenURL.h in Headers */,+ 7E7F69B61ABA35D8007546F4 /* CDVLocalStorage.h in Headers */,+ 30193A511AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h in Headers */,+ 7ED95D0A1AB9028C008C4574 /* CDVUIWebViewDelegate.h in Headers */,+ 7E7F69B81ABA368F007546F4 /* CDVUIWebViewEngine.h in Headers */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXHeadersBuildPhase section */++/* Begin PBXNativeTarget section */+ C0C01EB11E3911D50056E6CB /* Cordova */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = C0C01EB91E3911D50056E6CB /* Build configuration list for PBXNativeTarget "Cordova" */;+ buildPhases = (+ C0C01EAD1E3911D50056E6CB /* Sources */,+ C0C01EAE1E3911D50056E6CB /* Frameworks */,+ C0C01EAF1E3911D50056E6CB /* Headers */,+ );+ buildRules = (+ );+ dependencies = (+ );+ name = Cordova;+ productName = Cordova;+ productReference = C0C01EB21E3911D50056E6CB /* Cordova.framework */;+ productType = "com.apple.product-type.framework";+ };+ D2AAC07D0554694100DB518D /* CordovaLib */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "CordovaLib" */;+ buildPhases = (+ D2AAC07A0554694100DB518D /* Headers */,+ D2AAC07B0554694100DB518D /* Sources */,+ D2AAC07C0554694100DB518D /* Frameworks */,+ );+ buildRules = (+ );+ dependencies = (+ );+ name = CordovaLib;+ productName = CordovaLib;+ productReference = 68A32D7114102E1C006B237C /* libCordova.a */;+ productType = "com.apple.product-type.library.static";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ 0867D690FE84028FC02AAC07 /* Project object */ = {+ isa = PBXProject;+ attributes = {+ LastUpgradeCheck = 1010;+ TargetAttributes = {+ C0C01EB11E3911D50056E6CB = {+ CreatedOnToolsVersion = 10.1;+ ProvisioningStyle = Automatic;+ };+ D2AAC07D0554694100DB518D = {+ CreatedOnToolsVersion = 10.1;+ ProvisioningStyle = Automatic;+ };+ };+ };+ buildConfigurationList = 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "CordovaLib" */;+ compatibilityVersion = "Xcode 8.0";+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ en,+ );+ mainGroup = 0867D691FE84028FC02AAC07;+ productRefGroup = 034768DFFF38A50411DB9C8B /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ D2AAC07D0554694100DB518D /* CordovaLib */,+ C0C01EB11E3911D50056E6CB /* Cordova */,+ );+ };+/* End PBXProject section */++/* Begin PBXSourcesBuildPhase section */+ C0C01EAD1E3911D50056E6CB /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 9052DE712150D040008E83D4 /* CDVAppDelegate.m in Sources */,+ 9052DE722150D040008E83D4 /* CDVCommandDelegateImpl.m in Sources */,+ 9052DE732150D040008E83D4 /* CDVCommandQueue.m in Sources */,+ 9052DE742150D040008E83D4 /* CDVConfigParser.m in Sources */,+ 9052DE752150D040008E83D4 /* CDVInvokedUrlCommand.m in Sources */,+ 9052DE762150D040008E83D4 /* CDVPlugin+Resources.m in Sources */,+ 9052DE772150D040008E83D4 /* CDVPlugin.m in Sources */,+ 9052DE782150D040008E83D4 /* CDVPluginResult.m in Sources */,+ 9052DE792150D040008E83D4 /* CDVTimer.m in Sources */,+ 9052DE7A2150D040008E83D4 /* CDVURLProtocol.m in Sources */,+ 9052DE7B2150D040008E83D4 /* CDVUserAgentUtil.m in Sources */,+ 9052DE7C2150D040008E83D4 /* CDVViewController.m in Sources */,+ 9052DE7D2150D040008E83D4 /* CDVWhitelist.m in Sources */,+ 9052DE7E2150D040008E83D4 /* NSDictionary+CordovaPreferences.m in Sources */,+ 9052DE7F2150D040008E83D4 /* NSMutableArray+QueueAdditions.m in Sources */,+ 9052DE802150D040008E83D4 /* CDVJSON_private.m in Sources */,+ 9052DE812150D040008E83D4 /* CDVLogger.m in Sources */,+ 9052DE822150D040008E83D4 /* CDVGestureHandler.m in Sources */,+ 9052DE832150D040008E83D4 /* CDVIntentAndNavigationFilter.m in Sources */,+ 9052DE842150D040008E83D4 /* CDVHandleOpenURL.m in Sources */,+ 9052DE852150D040008E83D4 /* CDVLocalStorage.m in Sources */,+ 9052DE862150D040008E83D4 /* CDVUIWebViewNavigationDelegate.m in Sources */,+ 9052DE872150D040008E83D4 /* CDVUIWebViewDelegate.m in Sources */,+ 9052DE882150D040008E83D4 /* CDVUIWebViewEngine.m in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ D2AAC07B0554694100DB518D /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 7ED95D371AB9029B008C4574 /* CDVAppDelegate.m in Sources */,+ 7ED95D3C1AB9029B008C4574 /* CDVCommandDelegateImpl.m in Sources */,+ 7ED95D3E1AB9029B008C4574 /* CDVCommandQueue.m in Sources */,+ 7ED95D401AB9029B008C4574 /* CDVConfigParser.m in Sources */,+ 7ED95D421AB9029B008C4574 /* CDVInvokedUrlCommand.m in Sources */,+ 7ED95D441AB9029B008C4574 /* CDVPlugin+Resources.m in Sources */,+ 7ED95D461AB9029B008C4574 /* CDVPlugin.m in Sources */,+ 7ED95D481AB9029B008C4574 /* CDVPluginResult.m in Sources */,+ 7ED95D4B1AB9029B008C4574 /* CDVTimer.m in Sources */,+ 7ED95D4D1AB9029B008C4574 /* CDVURLProtocol.m in Sources */,+ 7ED95D4F1AB9029B008C4574 /* CDVUserAgentUtil.m in Sources */,+ 7ED95D511AB9029B008C4574 /* CDVViewController.m in Sources */,+ 7ED95D541AB9029B008C4574 /* CDVWhitelist.m in Sources */,+ 7ED95D581AB9029B008C4574 /* NSDictionary+CordovaPreferences.m in Sources */,+ 7ED95D5A1AB9029B008C4574 /* NSMutableArray+QueueAdditions.m in Sources */,+ 7ED95D041AB9028C008C4574 /* CDVJSON_private.m in Sources */,+ 28BFF9151F355A4E00DDF01A /* CDVLogger.m in Sources */,+ A3B082D51BB15CEA00D8DC35 /* CDVGestureHandler.m in Sources */,+ 3093E2241B16D6A3003F381A /* CDVIntentAndNavigationFilter.m in Sources */,+ 7ED95D071AB9028C008C4574 /* CDVHandleOpenURL.m in Sources */,+ 7ED95D091AB9028C008C4574 /* CDVLocalStorage.m in Sources */,+ 30193A501AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m in Sources */,+ 7ED95D0B1AB9028C008C4574 /* CDVUIWebViewDelegate.m in Sources */,+ 7ED95D0D1AB9028C008C4574 /* CDVUIWebViewEngine.m in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin XCBuildConfiguration section */+ 1DEB921F08733DC00010E9CD /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ PUBLIC_HEADERS_FOLDER_PATH = include/Cordova;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Debug;+ };+ 1DEB922008733DC00010E9CD /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ PUBLIC_HEADERS_FOLDER_PATH = include/Cordova;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Release;+ };+ 1DEB922308733DC00010E9CD /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ CODE_SIGN_IDENTITY = "";+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = dwarf;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ GCC_C_LANGUAGE_STANDARD = gnu11;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PRECOMPILE_PREFIX_HEADER = YES;+ GCC_PREFIX_HEADER = CordovaLib_Prefix.pch;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "WK_WEB_VIEW_ONLY=$(WK_WEB_VIEW_ONLY)",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ OTHER_LDFLAGS = "-ObjC";+ PRODUCT_NAME = Cordova;+ SDKROOT = iphoneos;+ SKIP_INSTALL = YES;+ WK_WEB_VIEW_ONLY = 0;+ };+ name = Debug;+ };+ 1DEB922408733DC00010E9CD /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ CODE_SIGN_IDENTITY = "";+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ GCC_C_LANGUAGE_STANDARD = gnu11;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_PRECOMPILE_PREFIX_HEADER = YES;+ GCC_PREFIX_HEADER = CordovaLib_Prefix.pch;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "WK_WEB_VIEW_ONLY=$(WK_WEB_VIEW_ONLY)",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ MTL_ENABLE_DEBUG_INFO = NO;+ MTL_FAST_MATH = YES;+ OTHER_LDFLAGS = "-ObjC";+ PRODUCT_NAME = Cordova;+ SDKROOT = iphoneos;+ SKIP_INSTALL = YES;+ VALIDATE_PRODUCT = YES;+ WK_WEB_VIEW_ONLY = 0;+ };+ name = Release;+ };+ C0C01EB71E3911D50056E6CB /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ DEFINES_MODULE = YES;+ DYLIB_INSTALL_NAME_BASE = "@rpath";+ INFOPLIST_FILE = Cordova/Info.plist;+ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";+ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";+ PRODUCT_BUNDLE_IDENTIFIER = org.apache.cordova.Cordova;+ TARGETED_DEVICE_FAMILY = "1,2";+ VERSIONING_SYSTEM = "apple-generic";+ VERSION_INFO_PREFIX = "";+ };+ name = Debug;+ };+ C0C01EB81E3911D50056E6CB /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ DEFINES_MODULE = YES;+ DYLIB_INSTALL_NAME_BASE = "@rpath";+ INFOPLIST_FILE = Cordova/Info.plist;+ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";+ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";+ PRODUCT_BUNDLE_IDENTIFIER = org.apache.cordova.Cordova;+ TARGETED_DEVICE_FAMILY = "1,2";+ VERSIONING_SYSTEM = "apple-generic";+ VERSION_INFO_PREFIX = "";+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "CordovaLib" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 1DEB921F08733DC00010E9CD /* Debug */,+ 1DEB922008733DC00010E9CD /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "CordovaLib" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 1DEB922308733DC00010E9CD /* Debug */,+ 1DEB922408733DC00010E9CD /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ C0C01EB91E3911D50056E6CB /* Build configuration list for PBXNativeTarget "Cordova" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ C0C01EB71E3911D50056E6CB /* Debug */,+ C0C01EB81E3911D50056E6CB /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */+ };+ rootObject = 0867D690FE84028FC02AAC07 /* Project object */;+}diff --git a/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plistnew file mode 100644index 000000000..33ba33c28--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>SchemeUserState</key>+ <dict>+ <key>Cordova.xcscheme_^#shared#^_</key>+ <dict>+ <key>orderHint</key>+ <integer>2</integer>+ </dict>+ <key>CordovaLib.xcscheme_^#shared#^_</key>+ <dict>+ <key>orderHint</key>+ <integer>1</integer>+ </dict>+ </dict>+</dict>+</plist>diff --git a/cordova/platforms/ios/CordovaLib/CordovaLib_Prefix.pch b/cordova/platforms/ios/CordovaLib/CordovaLib_Prefix.pchnew file mode 100644index 000000000..954558070--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/CordovaLib_Prefix.pch@@ -0,0 +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.+ */++#ifdef __OBJC__+ #import <Foundation/Foundation.h>+#endifdiff --git a/cordova/platforms/ios/CordovaLib/VERSION b/cordova/platforms/ios/CordovaLib/VERSIONnew file mode 100644index 000000000..ac14c3dfa--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/VERSION@@ -0,0 +1 @@+5.1.1diff --git a/cordova/platforms/ios/CordovaLib/cordova.js b/cordova/platforms/ios/CordovaLib/cordova.jsnew file mode 100644index 000000000..9813b231f--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/cordova.js@@ -0,0 +1,2188 @@+// Platform: ios+// 9c79667cd175f51fd2edf2dc91ac8be98b89076a+/*+ 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.+*/+;(function() {+var PLATFORM_VERSION_BUILD_LABEL = '5.1.1';+// file: src/scripts/require.js+var require;+var define;++(function () {+ var modules = {};+ // Stack of moduleIds currently being built.+ var requireStack = [];+ // Map of module ID -> index into requireStack of modules currently being built.+ var inProgressModules = {};+ var SEPARATOR = '.';++ function build (module) {+ var factory = module.factory;+ var localRequire = function (id) {+ var resultantId = id;+ // Its a relative path, so lop off the last portion and add the id (minus "./")+ if (id.charAt(0) === '.') {+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2);+ }+ return require(resultantId);+ };+ module.exports = {};+ delete module.factory;+ factory(localRequire, module.exports, module);+ return module.exports;+ }++ require = function (id) {+ if (!modules[id]) {+ throw 'module ' + id + ' not found';+ } else if (id in inProgressModules) {+ var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;+ throw 'Cycle in require graph: ' + cycle;+ }+ if (modules[id].factory) {+ try {+ inProgressModules[id] = requireStack.length;+ requireStack.push(id);+ return build(modules[id]);+ } finally {+ delete inProgressModules[id];+ requireStack.pop();+ }+ }+ return modules[id].exports;+ };++ define = function (id, factory) {+ if (Object.prototype.hasOwnProperty.call(modules, id)) {+ throw 'module ' + id + ' already defined';+ }++ modules[id] = {+ id: id,+ factory: factory+ };+ };++ define.remove = function (id) {+ delete modules[id];+ };++ define.moduleMap = modules;+})();++// Export for use in node+if (typeof module === 'object' && typeof require === 'function') {+ module.exports.require = require;+ module.exports.define = define;+}++// file: src/cordova.js+define("cordova", function(require, exports, module) {++// Workaround for Windows 10 in hosted environment case+// http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object+if (window.cordova && !(window.cordova instanceof HTMLElement)) {+ throw new Error('cordova already defined');+}++var channel = require('cordova/channel');+var platform = require('cordova/platform');++/**+ * Intercept calls to addEventListener + removeEventListener and handle deviceready,+ * resume, and pause events.+ */+var m_document_addEventListener = document.addEventListener;+var m_document_removeEventListener = document.removeEventListener;+var m_window_addEventListener = window.addEventListener;+var m_window_removeEventListener = window.removeEventListener;++/**+ * Houses custom event handlers to intercept on document + window event listeners.+ */+var documentEventHandlers = {};+var windowEventHandlers = {};++document.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].subscribe(handler);+ } else {+ m_document_addEventListener.call(document, evt, handler, capture);+ }+};++window.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].subscribe(handler);+ } else {+ m_window_addEventListener.call(window, evt, handler, capture);+ }+};++document.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].unsubscribe(handler);+ } else {+ m_document_removeEventListener.call(document, evt, handler, capture);+ }+};++window.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].unsubscribe(handler);+ } else {+ m_window_removeEventListener.call(window, evt, handler, capture);+ }+};++function createEvent (type, data) {+ var event = document.createEvent('Events');+ event.initEvent(type, false, false);+ if (data) {+ for (var i in data) {+ if (data.hasOwnProperty(i)) {+ event[i] = data[i];+ }+ }+ }+ return event;+}++var cordova = {+ define: define,+ require: require,+ version: PLATFORM_VERSION_BUILD_LABEL,+ platformVersion: PLATFORM_VERSION_BUILD_LABEL,+ platformId: platform.id,++ /**+ * Methods to add/remove your own addEventListener hijacking on document + window.+ */+ addWindowEventHandler: function (event) {+ return (windowEventHandlers[event] = channel.create(event));+ },+ addStickyDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.createSticky(event));+ },+ addDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.create(event));+ },+ removeWindowEventHandler: function (event) {+ delete windowEventHandlers[event];+ },+ removeDocumentEventHandler: function (event) {+ delete documentEventHandlers[event];+ },++ /**+ * Retrieve original event handlers that were replaced by Cordova+ *+ * @return object+ */+ getOriginalHandlers: function () {+ return {+ document: {+ addEventListener: m_document_addEventListener,+ removeEventListener: m_document_removeEventListener+ },+ window: {+ addEventListener: m_window_addEventListener,+ removeEventListener: m_window_removeEventListener+ }+ };+ },++ /**+ * Method to fire event from native code+ * bNoDetach is required for events which cause an exception which needs to be caught in native code+ */+ fireDocumentEvent: function (type, data, bNoDetach) {+ var evt = createEvent(type, data);+ if (typeof documentEventHandlers[type] !== 'undefined') {+ if (bNoDetach) {+ documentEventHandlers[type].fire(evt);+ } else {+ setTimeout(function () {+ // Fire deviceready on listeners that were registered before cordova.js was loaded.+ if (type === 'deviceready') {+ document.dispatchEvent(evt);+ }+ documentEventHandlers[type].fire(evt);+ }, 0);+ }+ } else {+ document.dispatchEvent(evt);+ }+ },++ fireWindowEvent: function (type, data) {+ var evt = createEvent(type, data);+ if (typeof windowEventHandlers[type] !== 'undefined') {+ setTimeout(function () {+ windowEventHandlers[type].fire(evt);+ }, 0);+ } else {+ window.dispatchEvent(evt);+ }+ },++ /**+ * Plugin callback mechanism.+ */+ // Randomize the starting callbackId to avoid collisions after refreshing or navigating.+ // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.+ callbackId: Math.floor(Math.random() * 2000000000),+ callbacks: {},+ callbackStatus: {+ NO_RESULT: 0,+ OK: 1,+ CLASS_NOT_FOUND_EXCEPTION: 2,+ ILLEGAL_ACCESS_EXCEPTION: 3,+ INSTANTIATION_EXCEPTION: 4,+ MALFORMED_URL_EXCEPTION: 5,+ IO_EXCEPTION: 6,+ INVALID_ACTION: 7,+ JSON_EXCEPTION: 8,+ ERROR: 9+ },++ /**+ * Called by native code when returning successful result from an action.+ */+ callbackSuccess: function (callbackId, args) {+ cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning error result from an action.+ */+ callbackError: function (callbackId, args) {+ // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.+ // Derive success from status.+ cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning the result from an action.+ */+ callbackFromNative: function (callbackId, isSuccess, status, args, keepCallback) {+ try {+ var callback = cordova.callbacks[callbackId];+ if (callback) {+ if (isSuccess && status === cordova.callbackStatus.OK) {+ callback.success && callback.success.apply(null, args);+ } else if (!isSuccess) {+ callback.fail && callback.fail.apply(null, args);+ }+ /*+ else+ Note, this case is intentionally not caught.+ this can happen if isSuccess is true, but callbackStatus is NO_RESULT+ which is used to remove a callback from the list without calling the callbacks+ typically keepCallback is false in this case+ */+ // Clear callback if not expecting any more results+ if (!keepCallback) {+ delete cordova.callbacks[callbackId];+ }+ }+ } catch (err) {+ var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;+ console && console.log && console.log(msg);+ console && console.log && err.stack && console.log(err.stack);+ cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ throw err;+ }+ },++ addConstructor: function (func) {+ channel.onCordovaReady.subscribe(function () {+ try {+ func();+ } catch (e) {+ console.log('Failed to run constructor: ' + e);+ }+ });+ }+};++module.exports = cordova;++});++// file: src/common/argscheck.js+define("cordova/argscheck", function(require, exports, module) {++var utils = require('cordova/utils');++var moduleExports = module.exports;++var typeMap = {+ 'A': 'Array',+ 'D': 'Date',+ 'N': 'Number',+ 'S': 'String',+ 'F': 'Function',+ 'O': 'Object'+};++function extractParamName (callee, argIndex) {+ return (/\(\s*([^)]*?)\s*\)/).exec(callee)[1].split(/\s*,\s*/)[argIndex];+}++/**+ * Checks the given arguments' types and throws if they are not as expected.+ *+ * `spec` is a string where each character stands for the required type of the+ * argument at the same position. In other words: the character at `spec[i]`+ * specifies the required type for `args[i]`. The characters in `spec` are the+ * first letter of the required type's name. The supported types are:+ *+ * Array, Date, Number, String, Function, Object+ *+ * Lowercase characters specify arguments that must not be `null` or `undefined`+ * while uppercase characters allow those values to be passed.+ *+ * Finally, `*` can be used to allow any type at the corresponding position.+ *+ * @example+ * function foo (arr, opts) {+ * // require `arr` to be an Array and `opts` an Object, null or undefined+ * checkArgs('aO', 'my.package.foo', arguments);+ * // ...+ * }+ * @param {String} spec - the type specification for `args` as described above+ * @param {String} functionName - full name of the callee.+ * Used in the error message+ * @param {Array|arguments} args - the arguments to be checked against `spec`+ * @param {Function} [opt_callee=args.callee] - the recipient of `args`.+ * Used to extract parameter names for the error message+ * @throws {TypeError} if args do not satisfy spec+ */+function checkArgs (spec, functionName, args, opt_callee) {+ if (!moduleExports.enableChecks) {+ return;+ }+ var errMsg = null;+ var typeName;+ for (var i = 0; i < spec.length; ++i) {+ var c = spec.charAt(i);+ var cUpper = c.toUpperCase();+ var arg = args[i];+ // Asterix means allow anything.+ if (c === '*') {+ continue;+ }+ typeName = utils.typeName(arg);+ if ((arg === null || arg === undefined) && c === cUpper) {+ continue;+ }+ if (typeName !== typeMap[cUpper]) {+ errMsg = 'Expected ' + typeMap[cUpper];+ break;+ }+ }+ if (errMsg) {+ errMsg += ', but got ' + typeName + '.';+ errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;+ // Don't log when running unit tests.+ if (typeof jasmine === 'undefined') {+ console.error(errMsg);+ }+ throw TypeError(errMsg);+ }+}++function getValue (value, defaultValue) {+ return value === undefined ? defaultValue : value;+}++moduleExports.checkArgs = checkArgs;+moduleExports.getValue = getValue;+moduleExports.enableChecks = true;++});++// file: src/common/base64.js+define("cordova/base64", function(require, exports, module) {++var base64 = exports;++base64.fromArrayBuffer = function (arrayBuffer) {+ var array = new Uint8Array(arrayBuffer);+ return uint8ToBase64(array);+};++base64.toArrayBuffer = function (str) {+ var decodedStr = atob(str);+ var arrayBuffer = new ArrayBuffer(decodedStr.length);+ var array = new Uint8Array(arrayBuffer);+ for (var i = 0, len = decodedStr.length; i < len; i++) {+ array[i] = decodedStr.charCodeAt(i);+ }+ return arrayBuffer;+};++// ------------------------------------------------------------------------------++/* This code is based on the performance tests at http://jsperf.com/b64tests+ * This 12-bit-at-a-time algorithm was the best performing version on all+ * platforms tested.+ */++var b64_6bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';+var b64_12bit;++var b64_12bitTable = function () {+ b64_12bit = [];+ for (var i = 0; i < 64; i++) {+ for (var j = 0; j < 64; j++) {+ b64_12bit[i * 64 + j] = b64_6bit[i] + b64_6bit[j];+ }+ }+ b64_12bitTable = function () { return b64_12bit; };+ return b64_12bit;+};++function uint8ToBase64 (rawData) {+ var numBytes = rawData.byteLength;+ var output = '';+ var segment;+ var table = b64_12bitTable();+ for (var i = 0; i < numBytes - 2; i += 3) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8) + rawData[i + 2];+ output += table[segment >> 12];+ output += table[segment & 0xfff];+ }+ if (numBytes - i === 2) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8);+ output += table[segment >> 12];+ output += b64_6bit[(segment & 0xfff) >> 6];+ output += '=';+ } else if (numBytes - i === 1) {+ segment = (rawData[i] << 16);+ output += table[segment >> 12];+ output += '==';+ }+ return output;+}++});++// file: src/common/builder.js+define("cordova/builder", function(require, exports, module) {++var utils = require('cordova/utils');++function each (objects, func, context) {+ for (var prop in objects) {+ if (objects.hasOwnProperty(prop)) {+ func.apply(context, [objects[prop], prop]);+ }+ }+}++function clobber (obj, key, value) {+ var needsProperty = false;+ try {+ obj[key] = value;+ } catch (e) {+ needsProperty = true;+ }+ // Getters can only be overridden by getters.+ if (needsProperty || obj[key] !== value) {+ utils.defineGetter(obj, key, function () {+ return value;+ });+ }+}++function assignOrWrapInDeprecateGetter (obj, key, value, message) {+ if (message) {+ utils.defineGetter(obj, key, function () {+ console.log(message);+ delete obj[key];+ clobber(obj, key, value);+ return value;+ });+ } else {+ clobber(obj, key, value);+ }+}++function include (parent, objects, clobber, merge) {+ each(objects, function (obj, key) {+ try {+ var result = obj.path ? require(obj.path) : {};++ if (clobber) {+ // Clobber if it doesn't exist.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else if (typeof obj.path !== 'undefined') {+ // If merging, merge properties onto parent, otherwise, clobber.+ if (merge) {+ recursiveMerge(parent[key], result);+ } else {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ }+ }+ result = parent[key];+ } else {+ // Overwrite if not currently defined.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else {+ // Set result to what already exists, so we can build children into it if they exist.+ result = parent[key];+ }+ }++ if (obj.children) {+ include(result, obj.children, clobber, merge);+ }+ } catch (e) {+ utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');+ }+ });+}++/**+ * Merge properties from one object onto another recursively. Properties from+ * the src object will overwrite existing target property.+ *+ * @param target Object to merge properties into.+ * @param src Object to merge properties from.+ */+function recursiveMerge (target, src) {+ for (var prop in src) {+ if (src.hasOwnProperty(prop)) {+ if (target.prototype && target.prototype.constructor === target) {+ // If the target object is a constructor override off prototype.+ clobber(target.prototype, prop, src[prop]);+ } else {+ if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {+ recursiveMerge(target[prop], src[prop]);+ } else {+ clobber(target, prop, src[prop]);+ }+ }+ }+ }+}++exports.buildIntoButDoNotClobber = function (objects, target) {+ include(target, objects, false, false);+};+exports.buildIntoAndClobber = function (objects, target) {+ include(target, objects, true, false);+};+exports.buildIntoAndMerge = function (objects, target) {+ include(target, objects, true, true);+};+exports.recursiveMerge = recursiveMerge;+exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;++});++// file: src/common/channel.js+define("cordova/channel", function(require, exports, module) {++var utils = require('cordova/utils');+var nextGuid = 1;++/**+ * Custom pub-sub "channel" that can have functions subscribed to it+ * This object is used to define and control firing of events for+ * cordova initialization, as well as for custom events thereafter.+ *+ * The order of events during page load and Cordova startup is as follows:+ *+ * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.+ * onNativeReady* Internal event that indicates the Cordova native side is ready.+ * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.+ * onDeviceReady* User event fired to indicate that Cordova is ready+ * onResume User event fired to indicate a start/resume lifecycle event+ * onPause User event fired to indicate a pause lifecycle event+ *+ * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.+ * All listeners that subscribe after the event is fired will be executed right away.+ *+ * The only Cordova events that user code should register for are:+ * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript+ * pause App has moved to background+ * resume App has returned to foreground+ *+ * Listeners can be registered as:+ * document.addEventListener("deviceready", myDeviceReadyListener, false);+ * document.addEventListener("resume", myResumeListener, false);+ * document.addEventListener("pause", myPauseListener, false);+ *+ * The DOM lifecycle events should be used for saving and restoring state+ * window.onload+ * window.onunload+ *+ */++/**+ * Channel+ * @constructor+ * @param type String the channel name+ */+var Channel = function (type, sticky) {+ this.type = type;+ // Map of guid -> function.+ this.handlers = {};+ // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.+ this.state = sticky ? 1 : 0;+ // Used in sticky mode to remember args passed to fire().+ this.fireArgs = null;+ // Used by onHasSubscribersChange to know if there are any listeners.+ this.numHandlers = 0;+ // Function that is called when the first listener is subscribed, or when+ // the last listener is unsubscribed.+ this.onHasSubscribersChange = null;+};+var channel = {+ /**+ * Calls the provided function only after all of the channels specified+ * have been fired. All channels must be sticky channels.+ */+ join: function (h, c) {+ var len = c.length;+ var i = len;+ var f = function () {+ if (!(--i)) h();+ };+ for (var j = 0; j < len; j++) {+ if (c[j].state === 0) {+ throw Error('Can only use join with sticky channels.');+ }+ c[j].subscribe(f);+ }+ if (!len) h();+ },++ create: function (type) {+ return (channel[type] = new Channel(type, false));+ },+ createSticky: function (type) {+ return (channel[type] = new Channel(type, true));+ },++ /**+ * cordova Channels that must fire before "deviceready" is fired.+ */+ deviceReadyChannelsArray: [],+ deviceReadyChannelsMap: {},++ /**+ * Indicate that a feature needs to be initialized before it is ready to be used.+ * This holds up Cordova's "deviceready" event until the feature has been initialized+ * and Cordova.initComplete(feature) is called.+ *+ * @param feature {String} The unique feature name+ */+ waitForInitialization: function (feature) {+ if (feature) {+ var c = channel[feature] || this.createSticky(feature);+ this.deviceReadyChannelsMap[feature] = c;+ this.deviceReadyChannelsArray.push(c);+ }+ },++ /**+ * Indicate that initialization code has completed and the feature is ready to be used.+ *+ * @param feature {String} The unique feature name+ */+ initializationComplete: function (feature) {+ var c = this.deviceReadyChannelsMap[feature];+ if (c) {+ c.fire();+ }+ }+};++function checkSubscriptionArgument (argument) {+ if (typeof argument !== 'function' && typeof argument.handleEvent !== 'function') {+ throw new Error(+ 'Must provide a function or an EventListener object ' ++ 'implementing the handleEvent interface.'+ );+ }+}++/**+ * Subscribes the given function to the channel. Any time that+ * Channel.fire is called so too will the function.+ * Optionally specify an execution context for the function+ * and a guid that can be used to stop subscribing to the channel.+ * Returns the guid.+ */+Channel.prototype.subscribe = function (eventListenerOrFunction, eventListener) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ eventListener = eventListenerOrFunction;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ if (this.state === 2) {+ handleEvent.apply(eventListener || this, this.fireArgs);+ return;+ }++ guid = eventListenerOrFunction.observer_guid;+ if (typeof eventListener === 'object') {+ handleEvent = utils.close(eventListener, handleEvent);+ }++ if (!guid) {+ // First time any channel has seen this subscriber+ guid = '' + nextGuid++;+ }+ handleEvent.observer_guid = guid;+ eventListenerOrFunction.observer_guid = guid;++ // Don't add the same handler more than once.+ if (!this.handlers[guid]) {+ this.handlers[guid] = handleEvent;+ this.numHandlers++;+ if (this.numHandlers === 1) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Unsubscribes the function with the given guid from the channel.+ */+Channel.prototype.unsubscribe = function (eventListenerOrFunction) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid, handler;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ guid = handleEvent.observer_guid;+ handler = this.handlers[guid];+ if (handler) {+ delete this.handlers[guid];+ this.numHandlers--;+ if (this.numHandlers === 0) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Calls all functions subscribed to this channel.+ */+Channel.prototype.fire = function (e) {+ var fireArgs = Array.prototype.slice.call(arguments);+ // Apply stickiness.+ if (this.state === 1) {+ this.state = 2;+ this.fireArgs = fireArgs;+ }+ if (this.numHandlers) {+ // Copy the values first so that it is safe to modify it from within+ // callbacks.+ var toCall = [];+ for (var item in this.handlers) {+ toCall.push(this.handlers[item]);+ }+ for (var i = 0; i < toCall.length; ++i) {+ toCall[i].apply(this, fireArgs);+ }+ if (this.state === 2 && this.numHandlers) {+ this.numHandlers = 0;+ this.handlers = {};+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++// defining them here so they are ready super fast!+// DOM event that is received when the web page is loaded and parsed.+channel.createSticky('onDOMContentLoaded');++// Event to indicate the Cordova native side is ready.+channel.createSticky('onNativeReady');++// Event to indicate that all Cordova JavaScript objects have been created+// and it's time to run plugin constructors.+channel.createSticky('onCordovaReady');++// Event to indicate that all automatically loaded JS plugins are loaded and ready.+// FIXME remove this+channel.createSticky('onPluginsReady');++// Event to indicate that Cordova is ready+channel.createSticky('onDeviceReady');++// Event to indicate a resume lifecycle event+channel.create('onResume');++// Event to indicate a pause lifecycle event+channel.create('onPause');++// Channels that must fire before "deviceready" is fired.+channel.waitForInitialization('onCordovaReady');+channel.waitForInitialization('onDOMContentLoaded');++module.exports = channel;++});++// file: ../cordova-ios/cordova-js-src/exec.js+define("cordova/exec", function(require, exports, module) {++/* global require, module, atob, document */++/**+ * Creates a gap bridge iframe used to notify the native code about queued+ * commands.+ */+var cordova = require('cordova');+var utils = require('cordova/utils');+var base64 = require('cordova/base64');+var execIframe;+var commandQueue = []; // Contains pending JS->Native messages.+var isInContextOfEvalJs = 0;+var failSafeTimerId = 0;++function massageArgsJsToNative (args) {+ if (!args || utils.typeName(args) !== 'Array') {+ return args;+ }+ var ret = [];+ args.forEach(function (arg, i) {+ if (utils.typeName(arg) === 'ArrayBuffer') {+ ret.push({+ 'CDVType': 'ArrayBuffer',+ 'data': base64.fromArrayBuffer(arg)+ });+ } else {+ ret.push(arg);+ }+ });+ return ret;+}++function massageMessageNativeToJs (message) {+ if (message.CDVType === 'ArrayBuffer') {+ var stringToArrayBuffer = function (str) {+ var ret = new Uint8Array(str.length);+ for (var i = 0; i < str.length; i++) {+ ret[i] = str.charCodeAt(i);+ }+ return ret.buffer;+ };+ var base64ToArrayBuffer = function (b64) {+ return stringToArrayBuffer(atob(b64));+ };+ message = base64ToArrayBuffer(message.data);+ }+ return message;+}++function convertMessageToArgsNativeToJs (message) {+ var args = [];+ if (!message || !message.hasOwnProperty('CDVType')) {+ args.push(message);+ } else if (message.CDVType === 'MultiPart') {+ message.messages.forEach(function (e) {+ args.push(massageMessageNativeToJs(e));+ });+ } else {+ args.push(massageMessageNativeToJs(message));+ }+ return args;+}++function iOSExec () {++ var successCallback, failCallback, service, action, actionArgs;+ var callbackId = null;+ if (typeof arguments[0] !== 'string') {+ // FORMAT ONE+ successCallback = arguments[0];+ failCallback = arguments[1];+ service = arguments[2];+ action = arguments[3];+ actionArgs = arguments[4];++ // Since we need to maintain backwards compatibility, we have to pass+ // an invalid callbackId even if no callback was provided since plugins+ // will be expecting it. The Cordova.exec() implementation allocates+ // an invalid callbackId and passes it even if no callbacks were given.+ callbackId = 'INVALID';+ } else {+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' ++ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'+ );+ }++ // If actionArgs is not provided, default to an empty array+ actionArgs = actionArgs || [];++ // Register the callbacks and add the callbackId to the positional+ // arguments if given.+ if (successCallback || failCallback) {+ callbackId = service + cordova.callbackId++;+ cordova.callbacks[callbackId] =+ { success: successCallback, fail: failCallback };+ }++ actionArgs = massageArgsJsToNative(actionArgs);++ var command = [callbackId, service, action, actionArgs];++ // Stringify and queue the command. We stringify to command now to+ // effectively clone the command arguments in case they are mutated before+ // the command is executed.+ commandQueue.push(JSON.stringify(command));++ // If we're in the context of a stringByEvaluatingJavaScriptFromString call,+ // then the queue will be flushed when it returns; no need for a poke.+ // Also, if there is already a command in the queue, then we've already+ // poked the native side, so there is no reason to do so again.+ if (!isInContextOfEvalJs && commandQueue.length === 1) {+ pokeNative();+ }+}++// CB-10530+function proxyChanged () {+ var cexec = cordovaExec();++ return (execProxy !== cexec && // proxy objects are different+ iOSExec !== cexec // proxy object is not the current iOSExec+ );+}++// CB-10106+function handleBridgeChange () {+ if (proxyChanged()) {+ var commandString = commandQueue.shift();+ while (commandString) {+ var command = JSON.parse(commandString);+ var callbackId = command[0];+ var service = command[1];+ var action = command[2];+ var actionArgs = command[3];+ var callbacks = cordova.callbacks[callbackId] || {};++ execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);++ commandString = commandQueue.shift();+ }+ return true;+ }++ return false;+}++function pokeNative () {+ // CB-5488 - Don't attempt to create iframe before document.body is available.+ if (!document.body) {+ setTimeout(pokeNative);+ return;+ }++ // Check if they've removed it from the DOM, and put it back if so.+ if (execIframe && execIframe.contentWindow) {+ execIframe.contentWindow.location = 'gap://ready';+ } else {+ execIframe = document.createElement('iframe');+ execIframe.style.display = 'none';+ execIframe.src = 'gap://ready';+ document.body.appendChild(execIframe);+ }+ // Use a timer to protect against iframe being unloaded during the poke (CB-7735).+ // This makes the bridge ~ 7% slower, but works around the poke getting lost+ // when the iframe is removed from the DOM.+ // An onunload listener could be used in the case where the iframe has just been+ // created, but since unload events fire only once, it doesn't work in the normal+ // case of iframe reuse (where unload will have already fired due to the attempted+ // navigation of the page).+ failSafeTimerId = setTimeout(function () {+ if (commandQueue.length) {+ // CB-10106 - flush the queue on bridge change+ if (!handleBridgeChange()) {+ pokeNative();+ }+ }+ }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).+}++iOSExec.nativeFetchMessages = function () {+ // Stop listing for window detatch once native side confirms poke.+ if (failSafeTimerId) {+ clearTimeout(failSafeTimerId);+ failSafeTimerId = 0;+ }+ // Each entry in commandQueue is a JSON string already.+ if (!commandQueue.length) {+ return '';+ }+ var json = '[' + commandQueue.join(',') + ']';+ commandQueue.length = 0;+ return json;+};++iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {+ return iOSExec.nativeEvalAndFetch(function () {+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ function nc2 () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback);+ }+ setTimeout(nc2, 0);+ });+};++iOSExec.nativeEvalAndFetch = function (func) {+ // This shouldn't be nested, but better to be safe.+ isInContextOfEvalJs++;+ try {+ func();+ return iOSExec.nativeFetchMessages();+ } finally {+ isInContextOfEvalJs--;+ }+};++// Proxy the exec for bridge changes. See CB-10106++function cordovaExec () {+ var cexec = require('cordova/exec');+ var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function');+ return (cexec_valid && execProxy !== cexec) ? cexec : iOSExec;+}++function execProxy () {+ cordovaExec().apply(null, arguments);+}++execProxy.nativeFetchMessages = function () {+ return cordovaExec().nativeFetchMessages.apply(null, arguments);+};++execProxy.nativeEvalAndFetch = function () {+ return cordovaExec().nativeEvalAndFetch.apply(null, arguments);+};++execProxy.nativeCallback = function () {+ return cordovaExec().nativeCallback.apply(null, arguments);+};++module.exports = execProxy;++});++// file: src/common/exec/proxy.js+define("cordova/exec/proxy", function(require, exports, module) {++// internal map of proxy function+var CommandProxyMap = {};++module.exports = {++ // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);+ add: function (id, proxyObj) {+ console.log('adding proxy for ' + id);+ CommandProxyMap[id] = proxyObj;+ return proxyObj;+ },++ // cordova.commandProxy.remove("Accelerometer");+ remove: function (id) {+ var proxy = CommandProxyMap[id];+ delete CommandProxyMap[id];+ CommandProxyMap[id] = null;+ return proxy;+ },++ get: function (service, action) {+ return (CommandProxyMap[service] ? CommandProxyMap[service][action] : null);+ }+};++});++// file: src/common/init.js+define("cordova/init", function(require, exports, module) {++var channel = require('cordova/channel');+var cordova = require('cordova');+var modulemapper = require('cordova/modulemapper');+var platform = require('cordova/platform');+var pluginloader = require('cordova/pluginloader');+var utils = require('cordova/utils');++var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];++function logUnfiredChannels (arr) {+ for (var i = 0; i < arr.length; ++i) {+ if (arr[i].state !== 2) {+ console.log('Channel not fired: ' + arr[i].type);+ }+ }+}++window.setTimeout(function () {+ if (channel.onDeviceReady.state !== 2) {+ console.log('deviceready has not fired after 5 seconds.');+ logUnfiredChannels(platformInitChannelsArray);+ logUnfiredChannels(channel.deviceReadyChannelsArray);+ }+}, 5000);++// Replace navigator before any modules are required(), to ensure it happens as soon as possible.+// We replace it so that properties that can't be clobbered can instead be overridden.+function replaceNavigator (origNavigator) {+ var CordovaNavigator = function () {};+ CordovaNavigator.prototype = origNavigator;+ var newNavigator = new CordovaNavigator();+ // This work-around really only applies to new APIs that are newer than Function.bind.+ // Without it, APIs such as getGamepads() break.+ if (CordovaNavigator.bind) {+ for (var key in origNavigator) {+ if (typeof origNavigator[key] === 'function') {+ newNavigator[key] = origNavigator[key].bind(origNavigator);+ } else {+ (function (k) {+ utils.defineGetterSetter(newNavigator, key, function () {+ return origNavigator[k];+ });+ })(key);+ }+ }+ }+ return newNavigator;+}++if (window.navigator) {+ window.navigator = replaceNavigator(window.navigator);+}++if (!window.console) {+ window.console = {+ log: function () {}+ };+}+if (!window.console.warn) {+ window.console.warn = function (msg) {+ this.log('warn: ' + msg);+ };+}++// Register pause, resume and deviceready channels as events on document.+channel.onPause = cordova.addDocumentEventHandler('pause');+channel.onResume = cordova.addDocumentEventHandler('resume');+channel.onActivated = cordova.addDocumentEventHandler('activated');+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');++// Listen for DOMContentLoaded and notify our channel subscribers.+if (document.readyState === 'complete' || document.readyState === 'interactive') {+ channel.onDOMContentLoaded.fire();+} else {+ document.addEventListener('DOMContentLoaded', function () {+ channel.onDOMContentLoaded.fire();+ }, false);+}++// _nativeReady is global variable that the native side can set+// to signify that the native code is ready. It is a global since+// it may be called before any cordova JS is ready.+if (window._nativeReady) {+ channel.onNativeReady.fire();+}++modulemapper.clobbers('cordova', 'cordova');+modulemapper.clobbers('cordova/exec', 'cordova.exec');+modulemapper.clobbers('cordova/exec', 'Cordova.exec');++// Call the platform-specific initialization.+platform.bootstrap && platform.bootstrap();++// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.+// The delay allows the attached modules to be defined before the plugin loader looks for them.+setTimeout(function () {+ pluginloader.load(function () {+ channel.onPluginsReady.fire();+ });+}, 0);++/**+ * Create all cordova objects once native side is ready.+ */+channel.join(function () {+ modulemapper.mapModules(window);++ platform.initialize && platform.initialize();++ // Fire event to notify that all objects are created+ channel.onCordovaReady.fire();++ // Fire onDeviceReady event once page has fully loaded, all+ // constructors have run and cordova info has been received from native+ // side.+ channel.join(function () {+ require('cordova').fireDocumentEvent('deviceready');+ }, channel.deviceReadyChannelsArray);++}, platformInitChannelsArray);++});++// file: src/common/modulemapper.js+define("cordova/modulemapper", function(require, exports, module) {++var builder = require('cordova/builder');+var moduleMap = define.moduleMap;+var symbolList;+var deprecationMap;++exports.reset = function () {+ symbolList = [];+ deprecationMap = {};+};++function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {+ if (!(moduleName in moduleMap)) {+ throw new Error('Module ' + moduleName + ' does not exist.');+ }+ symbolList.push(strategy, moduleName, symbolPath);+ if (opt_deprecationMessage) {+ deprecationMap[symbolPath] = opt_deprecationMessage;+ }+}++// Note: Android 2.3 does have Function.bind().+exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('c', moduleName, symbolPath, opt_deprecationMessage);+};++exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('m', moduleName, symbolPath, opt_deprecationMessage);+};++exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('d', moduleName, symbolPath, opt_deprecationMessage);+};++exports.runs = function (moduleName) {+ addEntry('r', moduleName, null);+};++function prepareNamespace (symbolPath, context) {+ if (!symbolPath) {+ return context;+ }+ return symbolPath.split('.').reduce(function (cur, part) {+ return (cur[part] = cur[part] || {});+ }, context);+}++exports.mapModules = function (context) {+ var origSymbols = {};+ context.CDV_origSymbols = origSymbols;+ for (var i = 0, len = symbolList.length; i < len; i += 3) {+ var strategy = symbolList[i];+ var moduleName = symbolList[i + 1];+ var module = require(moduleName);+ // <runs/>+ if (strategy === 'r') {+ continue;+ }+ var symbolPath = symbolList[i + 2];+ var lastDot = symbolPath.lastIndexOf('.');+ var namespace = symbolPath.substr(0, lastDot);+ var lastName = symbolPath.substr(lastDot + 1);++ var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;+ var parentObj = prepareNamespace(namespace, context);+ var target = parentObj[lastName];++ if (strategy === 'm' && target) {+ builder.recursiveMerge(target, module);+ } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {+ if (!(symbolPath in origSymbols)) {+ origSymbols[symbolPath] = target;+ }+ builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);+ }+ }+};++exports.getOriginalSymbol = function (context, symbolPath) {+ var origSymbols = context.CDV_origSymbols;+ if (origSymbols && (symbolPath in origSymbols)) {+ return origSymbols[symbolPath];+ }+ var parts = symbolPath.split('.');+ var obj = context;+ for (var i = 0; i < parts.length; ++i) {+ obj = obj && obj[parts[i]];+ }+ return obj;+};++exports.reset();++});++// file: ../cordova-ios/cordova-js-src/platform.js+define("cordova/platform", function(require, exports, module) {++module.exports = {+ id: 'ios',+ bootstrap: function () {+ // Attach the console polyfill that is iOS-only to window.console+ // see the file under plugin/ios/console.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');++ require('cordova/channel').onNativeReady.fire();+ }+};++});++// file: ../cordova-ios/cordova-js-src/plugin/ios/console.js+define("cordova/plugin/ios/console", function(require, exports, module) {++// ------------------------------------------------------------------------------++var logger = require('cordova/plugin/ios/logger');++// ------------------------------------------------------------------------------+// object that we're exporting+// ------------------------------------------------------------------------------+var console = module.exports;++// ------------------------------------------------------------------------------+// copy of the original console object+// ------------------------------------------------------------------------------+var WinConsole = window.console;++// ------------------------------------------------------------------------------+// whether to use the logger+// ------------------------------------------------------------------------------+var UseLogger = false;++// ------------------------------------------------------------------------------+// Timers+// ------------------------------------------------------------------------------+var Timers = {};++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+function noop () {}++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+console.useLogger = function (value) {+ if (arguments.length) UseLogger = !!value;++ if (UseLogger) {+ if (logger.useConsole()) {+ throw new Error('console and logger are too intertwingly');+ }+ }++ return UseLogger;+};++// ------------------------------------------------------------------------------+console.log = function () {+ if (logger.useConsole()) return;+ logger.log.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.error = function () {+ if (logger.useConsole()) return;+ logger.error.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.warn = function () {+ if (logger.useConsole()) return;+ logger.warn.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.info = function () {+ if (logger.useConsole()) return;+ logger.info.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.debug = function () {+ if (logger.useConsole()) return;+ logger.debug.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.assert = function (expression) {+ if (expression) return;++ var message = logger.format.apply(logger.format, [].slice.call(arguments, 1));+ console.log('ASSERT: ' + message);+};++// ------------------------------------------------------------------------------+console.clear = function () {};++// ------------------------------------------------------------------------------+console.dir = function (object) {+ console.log('%o', object);+};++// ------------------------------------------------------------------------------+console.dirxml = function (node) {+ console.log(node.innerHTML);+};++// ------------------------------------------------------------------------------+console.trace = noop;++// ------------------------------------------------------------------------------+console.group = console.log;++// ------------------------------------------------------------------------------+console.groupCollapsed = console.log;++// ------------------------------------------------------------------------------+console.groupEnd = noop;++// ------------------------------------------------------------------------------+console.time = function (name) {+ Timers[name] = new Date().valueOf();+};++// ------------------------------------------------------------------------------+console.timeEnd = function (name) {+ var timeStart = Timers[name];+ if (!timeStart) {+ console.warn('unknown timer: ' + name);+ return;+ }++ var timeElapsed = new Date().valueOf() - timeStart;+ console.log(name + ': ' + timeElapsed + 'ms');+};++// ------------------------------------------------------------------------------+console.timeStamp = noop;++// ------------------------------------------------------------------------------+console.profile = noop;++// ------------------------------------------------------------------------------+console.profileEnd = noop;++// ------------------------------------------------------------------------------+console.count = noop;++// ------------------------------------------------------------------------------+console.exception = console.log;++// ------------------------------------------------------------------------------+console.table = function (data, columns) {+ console.log('%o', data);+};++// ------------------------------------------------------------------------------+// return a new function that calls both functions passed as args+// ------------------------------------------------------------------------------+function wrappedOrigCall (orgFunc, newFunc) {+ return function () {+ var args = [].slice.call(arguments);+ try { orgFunc.apply(WinConsole, args); } catch (e) {}+ try { newFunc.apply(console, args); } catch (e) {}+ };+}++// ------------------------------------------------------------------------------+// For every function that exists in the original console object, that+// also exists in the new console object, wrap the new console method+// with one that calls both+// ------------------------------------------------------------------------------+for (var key in console) {+ if (typeof WinConsole[key] === 'function') {+ console[key] = wrappedOrigCall(WinConsole[key], console[key]);+ }+}++});++// file: ../cordova-ios/cordova-js-src/plugin/ios/logger.js+define("cordova/plugin/ios/logger", function(require, exports, module) {++// ------------------------------------------------------------------------------+// The logger module exports the following properties/functions:+//+// LOG - constant for the level LOG+// ERROR - constant for the level ERROR+// WARN - constant for the level WARN+// INFO - constant for the level INFO+// DEBUG - constant for the level DEBUG+// logLevel() - returns current log level+// logLevel(value) - sets and returns a new log level+// useConsole() - returns whether logger is using console+// useConsole(value) - sets and returns whether logger is using console+// log(message,...) - logs a message at level LOG+// error(message,...) - logs a message at level ERROR+// warn(message,...) - logs a message at level WARN+// info(message,...) - logs a message at level INFO+// debug(message,...) - logs a message at level DEBUG+// logLevel(level,message,...) - logs a message specified level+//+// ------------------------------------------------------------------------------++var logger = exports;++var exec = require('cordova/exec');++var UseConsole = false;+var UseLogger = true;+var Queued = [];+var DeviceReady = false;+var CurrentLevel;++var originalConsole = console;++/**+ * Logging levels+ */++var Levels = [+ 'LOG',+ 'ERROR',+ 'WARN',+ 'INFO',+ 'DEBUG'+];++/*+ * add the logging levels to the logger object and+ * to a separate levelsMap object for testing+ */++var LevelsMap = {};+for (var i = 0; i < Levels.length; i++) {+ var level = Levels[i];+ LevelsMap[level] = i;+ logger[level] = level;+}++CurrentLevel = LevelsMap.WARN;++/**+ * Getter/Setter for the logging level+ *+ * Returns the current logging level.+ *+ * When a value is passed, sets the logging level to that value.+ * The values should be one of the following constants:+ * logger.LOG+ * logger.ERROR+ * logger.WARN+ * logger.INFO+ * logger.DEBUG+ *+ * The value used determines which messages get printed. The logging+ * values above are in order, and only messages logged at the logging+ * level or above will actually be displayed to the user. E.g., the+ * default level is WARN, so only messages logged with LOG, ERROR, or+ * WARN will be displayed; INFO and DEBUG messages will be ignored.+ */+logger.level = function (value) {+ if (arguments.length) {+ if (LevelsMap[value] === null) {+ throw new Error('invalid logging level: ' + value);+ }+ CurrentLevel = LevelsMap[value];+ }++ return Levels[CurrentLevel];+};++/**+ * Getter/Setter for the useConsole functionality+ *+ * When useConsole is true, the logger will log via the+ * browser 'console' object.+ */+logger.useConsole = function (value) {+ if (arguments.length) UseConsole = !!value;++ if (UseConsole) {+ if (typeof console === 'undefined') {+ throw new Error('global console object is not defined');+ }++ if (typeof console.log !== 'function') {+ throw new Error('global console object does not have a log function');+ }++ if (typeof console.useLogger === 'function') {+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }+ }+ }++ return UseConsole;+};++/**+ * Getter/Setter for the useLogger functionality+ *+ * When useLogger is true, the logger will log via the+ * native Logger plugin.+ */+logger.useLogger = function (value) {+ // Enforce boolean+ if (arguments.length) UseLogger = !!value;+ return UseLogger;+};++/**+ * Logs a message at the LOG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.log = function (message) { logWithArgs('LOG', arguments); };++/**+ * Logs a message at the ERROR level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.error = function (message) { logWithArgs('ERROR', arguments); };++/**+ * Logs a message at the WARN level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.warn = function (message) { logWithArgs('WARN', arguments); };++/**+ * Logs a message at the INFO level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.info = function (message) { logWithArgs('INFO', arguments); };++/**+ * Logs a message at the DEBUG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.debug = function (message) { logWithArgs('DEBUG', arguments); };++// log at the specified level with args+function logWithArgs (level, args) {+ args = [level].concat([].slice.call(args));+ logger.logLevel.apply(logger, args);+}++// return the correct formatString for an object+function formatStringForMessage (message) {+ return (typeof message === 'string') ? '' : '%o';+}++/**+ * Logs a message at the specified level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.logLevel = function (level /* , ... */) {+ // format the message with the parameters+ var formatArgs = [].slice.call(arguments, 1);+ var fmtString = formatStringForMessage(formatArgs[0]);+ if (fmtString.length > 0) {+ formatArgs.unshift(fmtString); // add formatString+ }++ var message = logger.format.apply(logger.format, formatArgs);++ if (LevelsMap[level] === null) {+ throw new Error('invalid logging level: ' + level);+ }++ if (LevelsMap[level] > CurrentLevel) return;++ // queue the message if not yet at deviceready+ if (!DeviceReady && !UseConsole) {+ Queued.push([level, message]);+ return;+ }++ // Log using the native logger if that is enabled+ if (UseLogger) {+ exec(null, null, 'Console', 'logLevel', [level, message]);+ }++ // Log using the console if that is enabled+ if (UseConsole) {+ // make sure console is not using logger+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }++ // log to the console+ switch (level) {+ case logger.LOG: originalConsole.log(message); break;+ case logger.ERROR: originalConsole.log('ERROR: ' + message); break;+ case logger.WARN: originalConsole.log('WARN: ' + message); break;+ case logger.INFO: originalConsole.log('INFO: ' + message); break;+ case logger.DEBUG: originalConsole.log('DEBUG: ' + message); break;+ }+ }+};++/**+ * Formats a string and arguments following it ala console.log()+ *+ * Any remaining arguments will be appended to the formatted string.+ *+ * for rationale, see FireBug's Console API:+ * http://getfirebug.com/wiki/index.php/Console_API+ */+logger.format = function (formatString, args) {+ return __format(arguments[0], [].slice.call(arguments, 1)).join(' ');+};++// ------------------------------------------------------------------------------+/**+ * Formats a string and arguments following it ala vsprintf()+ *+ * format chars:+ * %j - format arg as JSON+ * %o - format arg as JSON+ * %c - format arg as ''+ * %% - replace with '%'+ * any other char following % will format it's+ * arg via toString().+ *+ * Returns an array containing the formatted string and any remaining+ * arguments.+ */+function __format (formatString, args) {+ if (formatString === null || formatString === undefined) return [''];+ if (arguments.length === 1) return [formatString.toString()];++ if (typeof formatString !== 'string') { formatString = formatString.toString(); }++ var pattern = /(.*?)%(.)(.*)/;+ var rest = formatString;+ var result = [];++ while (args.length) {+ var match = pattern.exec(rest);+ if (!match) break;++ var arg = args.shift();+ rest = match[3];+ result.push(match[1]);++ if (match[2] === '%') {+ result.push('%');+ args.unshift(arg);+ continue;+ }++ result.push(__formatted(arg, match[2]));+ }++ result.push(rest);++ var remainingArgs = [].slice.call(args);+ remainingArgs.unshift(result.join(''));+ return remainingArgs;+}++function __formatted (object, formatChar) {++ try {+ switch (formatChar) {+ case 'j':+ case 'o': return JSON.stringify(object);+ case 'c': return '';+ }+ } catch (e) {+ return 'error JSON.stringify()ing argument: ' + e;+ }++ if ((object === null) || (object === undefined)) {+ return Object.prototype.toString.call(object);+ }++ return object.toString();+}++// ------------------------------------------------------------------------------+// when deviceready fires, log queued messages+logger.__onDeviceReady = function () {+ if (DeviceReady) return;++ DeviceReady = true;++ for (var i = 0; i < Queued.length; i++) {+ var messageArgs = Queued[i];+ logger.logLevel(messageArgs[0], messageArgs[1]);+ }++ Queued = null;+};++// add a deviceready event to log queued messages+document.addEventListener('deviceready', logger.__onDeviceReady, false);++});++// file: src/common/pluginloader.js+define("cordova/pluginloader", function(require, exports, module) {++var modulemapper = require('cordova/modulemapper');++// Helper function to inject a <script> tag.+// Exported for testing.+exports.injectScript = function (url, onload, onerror) {+ var script = document.createElement('script');+ // onload fires even when script fails loads with an error.+ script.onload = onload;+ // onerror fires for malformed URLs.+ script.onerror = onerror;+ script.src = url;+ document.head.appendChild(script);+};++function injectIfNecessary (id, url, onload, onerror) {+ onerror = onerror || onload;+ if (id in define.moduleMap) {+ onload();+ } else {+ exports.injectScript(url, function () {+ if (id in define.moduleMap) {+ onload();+ } else {+ onerror();+ }+ }, onerror);+ }+}++function onScriptLoadingComplete (moduleList, finishPluginLoading) {+ // Loop through all the plugins and then through their clobbers and merges.+ for (var i = 0, module; (module = moduleList[i]); i++) {+ if (module.clobbers && module.clobbers.length) {+ for (var j = 0; j < module.clobbers.length; j++) {+ modulemapper.clobbers(module.id, module.clobbers[j]);+ }+ }++ if (module.merges && module.merges.length) {+ for (var k = 0; k < module.merges.length; k++) {+ modulemapper.merges(module.id, module.merges[k]);+ }+ }++ // Finally, if runs is truthy we want to simply require() the module.+ if (module.runs) {+ modulemapper.runs(module.id);+ }+ }++ finishPluginLoading();+}++// Handler for the cordova_plugins.js content.+// See plugman's plugin_loader.js for the details of this object.+// This function is only called if the really is a plugins array that isn't empty.+// Otherwise the onerror response handler will just call finishPluginLoading().+function handlePluginsObject (path, moduleList, finishPluginLoading) {+ // Now inject the scripts.+ var scriptCounter = moduleList.length;++ if (!scriptCounter) {+ finishPluginLoading();+ return;+ }+ function scriptLoadedCallback () {+ if (!--scriptCounter) {+ onScriptLoadingComplete(moduleList, finishPluginLoading);+ }+ }++ for (var i = 0; i < moduleList.length; i++) {+ injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback);+ }+}++function findCordovaPath () {+ var path = null;+ var scripts = document.getElementsByTagName('script');+ var term = '/cordova.js';+ for (var n = scripts.length - 1; n > -1; n--) {+ var src = scripts[n].src.replace(/\?.*$/, ''); // Strip any query param (CB-6007).+ if (src.indexOf(term) === (src.length - term.length)) {+ path = src.substring(0, src.length - term.length) + '/';+ break;+ }+ }+ return path;+}++// Tries to load all plugins' js-modules.+// This is an async process, but onDeviceReady is blocked on onPluginsReady.+// onPluginsReady is fired when there are no plugins to load, or they are all done.+exports.load = function (callback) {+ var pathPrefix = findCordovaPath();+ if (pathPrefix === null) {+ console.log('Could not find cordova.js script tag. Plugin loading may fail.');+ pathPrefix = '';+ }+ injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function () {+ var moduleList = require('cordova/plugin_list');+ handlePluginsObject(pathPrefix, moduleList, callback);+ }, callback);+};++});++// file: src/common/urlutil.js+define("cordova/urlutil", function(require, exports, module) {++/**+ * For already absolute URLs, returns what is passed in.+ * For relative URLs, converts them to absolute ones.+ */+exports.makeAbsolute = function makeAbsolute (url) {+ var anchorEl = document.createElement('a');+ anchorEl.href = url;+ return anchorEl.href;+};++});++// file: src/common/utils.js+define("cordova/utils", function(require, exports, module) {++var utils = exports;++/**+ * Defines a property getter / setter for obj[key].+ */+utils.defineGetterSetter = function (obj, key, getFunc, opt_setFunc) {+ if (Object.defineProperty) {+ var desc = {+ get: getFunc,+ configurable: true+ };+ if (opt_setFunc) {+ desc.set = opt_setFunc;+ }+ Object.defineProperty(obj, key, desc);+ } else {+ obj.__defineGetter__(key, getFunc);+ if (opt_setFunc) {+ obj.__defineSetter__(key, opt_setFunc);+ }+ }+};++/**+ * Defines a property getter for obj[key].+ */+utils.defineGetter = utils.defineGetterSetter;++utils.arrayIndexOf = function (a, item) {+ if (a.indexOf) {+ return a.indexOf(item);+ }+ var len = a.length;+ for (var i = 0; i < len; ++i) {+ if (a[i] === item) {+ return i;+ }+ }+ return -1;+};++/**+ * Returns whether the item was found in the array.+ */+utils.arrayRemove = function (a, item) {+ var index = utils.arrayIndexOf(a, item);+ if (index !== -1) {+ a.splice(index, 1);+ }+ return index !== -1;+};++utils.typeName = function (val) {+ return Object.prototype.toString.call(val).slice(8, -1);+};++/**+ * Returns an indication of whether the argument is an array or not+ */+utils.isArray = Array.isArray ||+ function (a) { return utils.typeName(a) === 'Array'; };++/**+ * Returns an indication of whether the argument is a Date or not+ */+utils.isDate = function (d) {+ return (d instanceof Date);+};++/**+ * Does a deep clone of the object.+ */+utils.clone = function (obj) {+ if (!obj || typeof obj === 'function' || utils.isDate(obj) || typeof obj !== 'object') {+ return obj;+ }++ var retVal, i;++ if (utils.isArray(obj)) {+ retVal = [];+ for (i = 0; i < obj.length; ++i) {+ retVal.push(utils.clone(obj[i]));+ }+ return retVal;+ }++ retVal = {};+ for (i in obj) {+ // 'unknown' type may be returned in custom protocol activation case on+ // Windows Phone 8.1 causing "No such interface supported" exception on+ // cloning (https://issues.apache.org/jira/browse/CB-11522)+ // eslint-disable-next-line valid-typeof+ if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') {+ retVal[i] = utils.clone(obj[i]);+ }+ }+ return retVal;+};++/**+ * Returns a wrapped version of the function+ */+utils.close = function (context, func, params) {+ return function () {+ var args = params || arguments;+ return func.apply(context, args);+ };+};++// ------------------------------------------------------------------------------+function UUIDcreatePart (length) {+ var uuidpart = '';+ for (var i = 0; i < length; i++) {+ var uuidchar = parseInt((Math.random() * 256), 10).toString(16);+ if (uuidchar.length === 1) {+ uuidchar = '0' + uuidchar;+ }+ uuidpart += uuidchar;+ }+ return uuidpart;+}++/**+ * Create a UUID+ */+utils.createUUID = function () {+ return UUIDcreatePart(4) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(6);+};++/**+ * Extends a child object from a parent object using classical inheritance+ * pattern.+ */+utils.extend = (function () {+ // proxy used to establish prototype chain+ var F = function () {};+ // extend Child from Parent+ return function (Child, Parent) {++ F.prototype = Parent.prototype;+ Child.prototype = new F();+ Child.__super__ = Parent.prototype;+ Child.prototype.constructor = Child;+ };+}());++/**+ * Alerts a message in any available way: alert or console.log.+ */+utils.alert = function (msg) {+ if (window.alert) {+ window.alert(msg);+ } else if (console && console.log) {+ console.log(msg);+ }+};++});++window.cordova = require('cordova');+// file: src/scripts/bootstrap.js+require('cordova/init');++})();diff --git a/cordova/platforms/ios/Podfile b/cordova/platforms/ios/Podfilenew file mode 100644index 000000000..2fcf677c5--- /dev/null+++ b/cordova/platforms/ios/Podfile@@ -0,0 +1,8 @@+# DO NOT MODIFY -- auto-generated by Apache Cordova++platform :ios, '10.0'++target 'TagSpaces Beta' do+ project 'TagSpaces Beta.xcodeproj'++enddiff --git a/cordova/platforms/ios/TagSpaces Beta.xcodeproj/project.pbxproj b/cordova/platforms/ios/TagSpaces Beta.xcodeproj/project.pbxprojnew file mode 100755index 000000000..72f1d55ea--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta.xcodeproj/project.pbxproj@@ -0,0 +1,540 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 46;+ objects = {++/* Begin PBXBuildFile section */+ 0207DA581B56EA530066E2B4 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0207DA571B56EA530066E2B4 /* Images.xcassets */; };+ 1D3623260D0F684500981E51 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* AppDelegate.m */; };+ 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; };+ 301BF552109A68D80062928A /* libCordova.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF535109A57CC0062928A /* libCordova.a */; settings = {ATTRIBUTES = (Required, ); }; };+ 302D95F114D2391D003F00A1 /* MainViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 302D95EF14D2391D003F00A1 /* MainViewController.m */; };+ 302D95F214D2391D003F00A1 /* MainViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 302D95F014D2391D003F00A1 /* MainViewController.xib */; };+ 6AFF5BF91D6E424B00AB3073 /* CDVLaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6AFF5BF81D6E424B00AB3073 /* CDVLaunchScreen.storyboard */; };+ FD08D10174C049C9B2AF1045 /* CDVDevice.m in Sources */ = {isa = PBXBuildFile; fileRef = 3D4B8429E3AA4CCABA3483C2 /* CDVDevice.m */; };+ 55E6C374E3FD4A4CABBDF7A2 /* APPBackgroundMode.m in Sources */ = {isa = PBXBuildFile; fileRef = 4A95936F2A674A518C47DC9D /* APPBackgroundMode.m */; };+ D542412872474BA08645A2B6 /* APPMethodMagic.m in Sources */ = {isa = PBXBuildFile; fileRef = D68F7DFBF1BD4A08A2CA9BB5 /* APPMethodMagic.m */; };+ 721F0E8CD32D41C399A0407B /* appbeep.wav in Resources */ = {isa = PBXBuildFile; fileRef = 101925A545E94A63B15DB828 /* appbeep.wav */; };+ 5330031C98004A548A04FB04 /* UIImage+CropScaleOrientation.m in Sources */ = {isa = PBXBuildFile; fileRef = 49D060970246496597C22CAD /* UIImage+CropScaleOrientation.m */; };+ CDBEA11FAD00489CAAD7BCB3 /* CDVCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 93FC43CFD33C4C9B89754A11 /* CDVCamera.m */; };+ 44ACB9D58C8147E2AECFD8E3 /* CDVJpegHeaderWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 1EC446528AF448AB9C17958C /* CDVJpegHeaderWriter.m */; };+ 3419DFF8E26C40049D27FEF9 /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 40A26423D0AF4AE598297D25 /* ImageIO.framework */; settings = {ATTRIBUTES = (Weak, ); }; };+ 68EEB8A986134A178EACDC51 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0C212A0B05B3406590A5DE1A /* CoreLocation.framework */; };+ 53F98373E0254B50ADFC7482 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 720D38A8FC114FB9860E24F1 /* AVFoundation.framework */; };+ 16B2D55C46694FAB859B04D1 /* CDVFile.m in Sources */ = {isa = PBXBuildFile; fileRef = B8464A38DD2D4F7FADA4A05D /* CDVFile.m */; };+ 93C68FEC56FE482C8A4A2E86 /* CDVLocalFilesystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 476A44F1A9C44535A0A00615 /* CDVLocalFilesystem.m */; };+ ED2346D5DC534F0E8A5C4B72 /* CDVAssetLibraryFilesystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 0B70DBAD7A3346F4A04BEB0D /* CDVAssetLibraryFilesystem.m */; };+ 9160B31B3A944071B00DBEAA /* FileOpener2.m in Sources */ = {isa = PBXBuildFile; fileRef = 4B5AE9F692F74481BC1E0C86 /* FileOpener2.m */; };+/* End PBXBuildFile section */++/* Begin PBXContainerItemProxy section */+ 301BF534109A57CC0062928A /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = 301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */;+ proxyType = 2;+ remoteGlobalIDString = D2AAC07E0554694100DB518D;+ remoteInfo = CordovaLib;+ };+ 301BF550109A68C00062928A /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = 301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */;+ proxyType = 1;+ remoteGlobalIDString = D2AAC07D0554694100DB518D;+ remoteInfo = CordovaLib;+ };+ 907D8123214C687600058A10 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = 301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */;+ proxyType = 2;+ remoteGlobalIDString = C0C01EB21E3911D50056E6CB;+ remoteInfo = Cordova;+ };+/* End PBXContainerItemProxy section */++/* Begin PBXFileReference section */+ 0207DA571B56EA530066E2B4 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = "TagSpaces Beta/Images.xcassets"; sourceTree = SOURCE_ROOT; };+ 1D3623240D0F684500981E51 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };+ 1D3623250D0F684500981E51 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };+ 1D6058910D05DD3D006BFB54 /* TagSpaces Beta.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "TagSpaces Beta.app"; sourceTree = BUILT_PRODUCTS_DIR; };+ 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };+ 301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = CordovaLib.xcodeproj; path = CordovaLib/CordovaLib.xcodeproj; sourceTree = "<group>"; };+ 301BF56E109A69640062928A /* www */ = {isa = PBXFileReference; lastKnownFileType = folder; path = www; sourceTree = SOURCE_ROOT; };+ 302D95EE14D2391D003F00A1 /* MainViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MainViewController.h; sourceTree = "<group>"; };+ 302D95EF14D2391D003F00A1 /* MainViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MainViewController.m; sourceTree = "<group>"; };+ 302D95F014D2391D003F00A1 /* MainViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = MainViewController.xib; sourceTree = "<group>"; };+ 3047A50F1AB8059700498E2A /* build-debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = "build-debug.xcconfig"; path = "cordova/build-debug.xcconfig"; sourceTree = SOURCE_ROOT; };+ 3047A5101AB8059700498E2A /* build-release.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = "build-release.xcconfig"; path = "cordova/build-release.xcconfig"; sourceTree = SOURCE_ROOT; };+ 3047A5111AB8059700498E2A /* build.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = build.xcconfig; path = cordova/build.xcconfig; sourceTree = SOURCE_ROOT; };+ 32CA4F630368D1EE00C91783 /* TagSpaces Beta-Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "TagSpaces Beta-Prefix.pch"; sourceTree = "<group>"; };+ 6AFF5BF81D6E424B00AB3073 /* CDVLaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = CDVLaunchScreen.storyboard; path = "TagSpaces Beta/CDVLaunchScreen.storyboard"; sourceTree = SOURCE_ROOT; };+ 8D1107310486CEB800E47090 /* TagSpaces Beta-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "TagSpaces Beta-Info.plist"; path = "TagSpaces Beta/TagSpaces Beta-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = SOURCE_ROOT; };+ EB87FDF31871DA8E0020F90C /* www */ = {isa = PBXFileReference; lastKnownFileType = folder; name = www; path = ../../www; sourceTree = "<group>"; };+ EB87FDF41871DAF40020F90C /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = ../../config.xml; sourceTree = "<group>"; };+ ED33DF2A687741AEAF9F8254 /* Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "Bridging-Header.h"; path = "Bridging-Header.h"; sourceTree = "<group>"; };+ F840E1F0165FE0F500CFE078 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = "TagSpaces Beta/config.xml"; sourceTree = "<group>"; };+ 3D4B8429E3AA4CCABA3483C2 /* CDVDevice.m */ = {isa = PBXFileReference; name = "CDVDevice.m"; path = "cordova-plugin-device/CDVDevice.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ B1E38A50DE384D2BB20890EB /* CDVDevice.h */ = {isa = PBXFileReference; name = "CDVDevice.h"; path = "cordova-plugin-device/CDVDevice.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 4A95936F2A674A518C47DC9D /* APPBackgroundMode.m */ = {isa = PBXFileReference; name = "APPBackgroundMode.m"; path = "cordova-plugin-background-mode/APPBackgroundMode.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ D68F7DFBF1BD4A08A2CA9BB5 /* APPMethodMagic.m */ = {isa = PBXFileReference; name = "APPMethodMagic.m"; path = "cordova-plugin-background-mode/APPMethodMagic.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ F0F164CAE6E346428F43D0C9 /* APPBackgroundMode.h */ = {isa = PBXFileReference; name = "APPBackgroundMode.h"; path = "cordova-plugin-background-mode/APPBackgroundMode.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 450308C53A3E4D278EC4286B /* APPMethodMagic.h */ = {isa = PBXFileReference; name = "APPMethodMagic.h"; path = "cordova-plugin-background-mode/APPMethodMagic.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 101925A545E94A63B15DB828 /* appbeep.wav */ = {isa = PBXFileReference; name = "appbeep.wav"; path = "appbeep.wav"; sourceTree = "<group>"; fileEncoding = undefined; lastKnownFileType = unknown; explicitFileType = undefined; includeInIndex = 0; };+ 49D060970246496597C22CAD /* UIImage+CropScaleOrientation.m */ = {isa = PBXFileReference; name = "UIImage+CropScaleOrientation.m"; path = "cordova-plugin-camera/UIImage+CropScaleOrientation.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ 93FC43CFD33C4C9B89754A11 /* CDVCamera.m */ = {isa = PBXFileReference; name = "CDVCamera.m"; path = "cordova-plugin-camera/CDVCamera.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ 1EC446528AF448AB9C17958C /* CDVJpegHeaderWriter.m */ = {isa = PBXFileReference; name = "CDVJpegHeaderWriter.m"; path = "cordova-plugin-camera/CDVJpegHeaderWriter.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ 7FD56FBDFA8B4E0A906A97B0 /* UIImage+CropScaleOrientation.h */ = {isa = PBXFileReference; name = "UIImage+CropScaleOrientation.h"; path = "cordova-plugin-camera/UIImage+CropScaleOrientation.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 3F8642D53B1A40708D0784D1 /* CDVCamera.h */ = {isa = PBXFileReference; name = "CDVCamera.h"; path = "cordova-plugin-camera/CDVCamera.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ FDB5379162244D3F92106617 /* CDVJpegHeaderWriter.h */ = {isa = PBXFileReference; name = "CDVJpegHeaderWriter.h"; path = "cordova-plugin-camera/CDVJpegHeaderWriter.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 00BBD8B96CA64BC19D7F67BE /* CDVExif.h */ = {isa = PBXFileReference; name = "CDVExif.h"; path = "cordova-plugin-camera/CDVExif.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 40A26423D0AF4AE598297D25 /* ImageIO.framework */ = {isa = PBXFileReference; name = "ImageIO.framework"; path = "System/Library/Frameworks/ImageIO.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };+ 0C212A0B05B3406590A5DE1A /* CoreLocation.framework */ = {isa = PBXFileReference; name = "CoreLocation.framework"; path = "System/Library/Frameworks/CoreLocation.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };+ 720D38A8FC114FB9860E24F1 /* AVFoundation.framework */ = {isa = PBXFileReference; name = "AVFoundation.framework"; path = "System/Library/Frameworks/AVFoundation.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };+ B8464A38DD2D4F7FADA4A05D /* CDVFile.m */ = {isa = PBXFileReference; name = "CDVFile.m"; path = "cordova-plugin-file/CDVFile.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ 476A44F1A9C44535A0A00615 /* CDVLocalFilesystem.m */ = {isa = PBXFileReference; name = "CDVLocalFilesystem.m"; path = "cordova-plugin-file/CDVLocalFilesystem.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ 0B70DBAD7A3346F4A04BEB0D /* CDVAssetLibraryFilesystem.m */ = {isa = PBXFileReference; name = "CDVAssetLibraryFilesystem.m"; path = "cordova-plugin-file/CDVAssetLibraryFilesystem.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ FFEEE9F8C3654B1D80D32A88 /* CDVFile.h */ = {isa = PBXFileReference; name = "CDVFile.h"; path = "cordova-plugin-file/CDVFile.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ BBE6D0DB8D0C48C3A48B5D6A /* CDVLocalFilesystem.h */ = {isa = PBXFileReference; name = "CDVLocalFilesystem.h"; path = "cordova-plugin-file/CDVLocalFilesystem.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ F69E9D0C17334829B9EA3A3F /* CDVAssetLibraryFilesystem.h */ = {isa = PBXFileReference; name = "CDVAssetLibraryFilesystem.h"; path = "cordova-plugin-file/CDVAssetLibraryFilesystem.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 4B5AE9F692F74481BC1E0C86 /* FileOpener2.m */ = {isa = PBXFileReference; name = "FileOpener2.m"; path = "cordova-plugin-file-opener2/FileOpener2.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ 032B343EF5F94282A58A7531 /* FileOpener2.h */ = {isa = PBXFileReference; name = "FileOpener2.h"; path = "cordova-plugin-file-opener2/FileOpener2.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+/* End PBXFileReference section */++/* Begin PBXFrameworksBuildPhase section */+ 1D60588F0D05DD3D006BFB54 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 301BF552109A68D80062928A /* libCordova.a in Frameworks */,+ 3419DFF8E26C40049D27FEF9 /* ImageIO.framework in Frameworks */,+ 68EEB8A986134A178EACDC51 /* CoreLocation.framework in Frameworks */,+ 53F98373E0254B50ADFC7482 /* AVFoundation.framework in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ 080E96DDFE201D6D7F000001 /* Classes */ = {+ isa = PBXGroup;+ children = (+ 302D95EE14D2391D003F00A1 /* MainViewController.h */,+ 302D95EF14D2391D003F00A1 /* MainViewController.m */,+ 302D95F014D2391D003F00A1 /* MainViewController.xib */,+ 1D3623240D0F684500981E51 /* AppDelegate.h */,+ 1D3623250D0F684500981E51 /* AppDelegate.m */,+ );+ name = Classes;+ path = "TagSpaces Beta/Classes";+ sourceTree = SOURCE_ROOT;+ };+ 19C28FACFE9D520D11CA2CBB /* Products */ = {+ isa = PBXGroup;+ children = (+ 1D6058910D05DD3D006BFB54 /* TagSpaces Beta.app */,+ );+ name = Products;+ sourceTree = "<group>";+ };+ 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = {+ isa = PBXGroup;+ children = (+ EB87FDF41871DAF40020F90C /* config.xml */,+ EB87FDF31871DA8E0020F90C /* www */,+ EB87FDF11871DA420020F90C /* Staging */,+ 301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */,+ 080E96DDFE201D6D7F000001 /* Classes */,+ 307C750510C5A3420062BCA9 /* Plugins */,+ 29B97315FDCFA39411CA2CEA /* Other Sources */,+ 29B97317FDCFA39411CA2CEA /* Resources */,+ 29B97323FDCFA39411CA2CEA /* Frameworks */,+ 19C28FACFE9D520D11CA2CBB /* Products */,+ );+ name = CustomTemplate;+ sourceTree = "<group>";+ };+ 29B97315FDCFA39411CA2CEA /* Other Sources */ = {+ isa = PBXGroup;+ children = (+ 32CA4F630368D1EE00C91783 /* TagSpaces Beta-Prefix.pch */,+ 29B97316FDCFA39411CA2CEA /* main.m */,+ ED33DF2A687741AEAF9F8254 /* Bridging-Header.h */,+ );+ name = "Other Sources";+ path = "TagSpaces Beta";+ sourceTree = "<group>";+ };+ 29B97317FDCFA39411CA2CEA /* Resources */ = {+ isa = PBXGroup;+ children = (+ 0207DA571B56EA530066E2B4 /* Images.xcassets */,+ 3047A50E1AB8057F00498E2A /* config */,+ 8D1107310486CEB800E47090 /* TagSpaces Beta-Info.plist */,+ 6AFF5BF81D6E424B00AB3073 /* CDVLaunchScreen.storyboard */,+ 101925A545E94A63B15DB828 /* appbeep.wav */,+ );+ name = Resources;+ path = "TagSpaces Beta/Resources";+ sourceTree = "<group>";+ };+ 29B97323FDCFA39411CA2CEA /* Frameworks */ = {+ isa = PBXGroup;+ children = (+ 40A26423D0AF4AE598297D25 /* ImageIO.framework */,+ 0C212A0B05B3406590A5DE1A /* CoreLocation.framework */,+ 720D38A8FC114FB9860E24F1 /* AVFoundation.framework */,+ );+ name = Frameworks;+ sourceTree = "<group>";+ };+ 301BF52E109A57CC0062928A /* Products */ = {+ isa = PBXGroup;+ children = (+ 301BF535109A57CC0062928A /* libCordova.a */,+ 907D8124214C687600058A10 /* Cordova.framework */,+ );+ name = Products;+ sourceTree = "<group>";+ };+ 3047A50E1AB8057F00498E2A /* config */ = {+ isa = PBXGroup;+ children = (+ 3047A50F1AB8059700498E2A /* build-debug.xcconfig */,+ 3047A5101AB8059700498E2A /* build-release.xcconfig */,+ 3047A5111AB8059700498E2A /* build.xcconfig */,+ );+ name = config;+ sourceTree = "<group>";+ };+ 307C750510C5A3420062BCA9 /* Plugins */ = {+ isa = PBXGroup;+ children = (+ 3D4B8429E3AA4CCABA3483C2 /* CDVDevice.m */,+ B1E38A50DE384D2BB20890EB /* CDVDevice.h */,+ 4A95936F2A674A518C47DC9D /* APPBackgroundMode.m */,+ D68F7DFBF1BD4A08A2CA9BB5 /* APPMethodMagic.m */,+ F0F164CAE6E346428F43D0C9 /* APPBackgroundMode.h */,+ 450308C53A3E4D278EC4286B /* APPMethodMagic.h */,+ 49D060970246496597C22CAD /* UIImage+CropScaleOrientation.m */,+ 93FC43CFD33C4C9B89754A11 /* CDVCamera.m */,+ 1EC446528AF448AB9C17958C /* CDVJpegHeaderWriter.m */,+ 7FD56FBDFA8B4E0A906A97B0 /* UIImage+CropScaleOrientation.h */,+ 3F8642D53B1A40708D0784D1 /* CDVCamera.h */,+ FDB5379162244D3F92106617 /* CDVJpegHeaderWriter.h */,+ 00BBD8B96CA64BC19D7F67BE /* CDVExif.h */,+ B8464A38DD2D4F7FADA4A05D /* CDVFile.m */,+ 476A44F1A9C44535A0A00615 /* CDVLocalFilesystem.m */,+ 0B70DBAD7A3346F4A04BEB0D /* CDVAssetLibraryFilesystem.m */,+ FFEEE9F8C3654B1D80D32A88 /* CDVFile.h */,+ BBE6D0DB8D0C48C3A48B5D6A /* CDVLocalFilesystem.h */,+ F69E9D0C17334829B9EA3A3F /* CDVAssetLibraryFilesystem.h */,+ 4B5AE9F692F74481BC1E0C86 /* FileOpener2.m */,+ 032B343EF5F94282A58A7531 /* FileOpener2.h */,+ );+ name = Plugins;+ path = "TagSpaces Beta/Plugins";+ sourceTree = SOURCE_ROOT;+ };+ EB87FDF11871DA420020F90C /* Staging */ = {+ isa = PBXGroup;+ children = (+ F840E1F0165FE0F500CFE078 /* config.xml */,+ 301BF56E109A69640062928A /* www */,+ );+ name = Staging;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ 1D6058900D05DD3D006BFB54 /* TagSpaces Beta */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "TagSpaces Beta" */;+ buildPhases = (+ 304B58A110DAC018002A0835 /* Copy www directory */,+ 1D60588D0D05DD3D006BFB54 /* Resources */,+ 1D60588E0D05DD3D006BFB54 /* Sources */,+ 1D60588F0D05DD3D006BFB54 /* Frameworks */,+ );+ buildRules = (+ );+ dependencies = (+ 301BF551109A68C00062928A /* PBXTargetDependency */,+ );+ name = "TagSpaces Beta";+ productName = "TagSpaces Beta";+ productReference = 1D6058910D05DD3D006BFB54 /* TagSpaces Beta.app */;+ productType = "com.apple.product-type.application";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ 29B97313FDCFA39411CA2CEA /* Project object */ = {+ isa = PBXProject;+ attributes = {+ LastUpgradeCheck = 510;+ TargetAttributes = {+ 1D6058900D05DD3D006BFB54 = {+ ProvisioningStyle = Automatic;+ };+ };+ };+ buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "TagSpaces Beta" */;+ compatibilityVersion = "Xcode 3.2";+ developmentRegion = English;+ hasScannedForEncodings = 1;+ mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */;+ projectDirPath = "";+ projectReferences = (+ {+ ProductGroup = 301BF52E109A57CC0062928A /* Products */;+ ProjectRef = 301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */;+ },+ );+ projectRoot = "";+ targets = (+ 1D6058900D05DD3D006BFB54 /* TagSpaces Beta */,+ );+ };+/* End PBXProject section */++/* Begin PBXReferenceProxy section */+ 301BF535109A57CC0062928A /* libCordova.a */ = {+ isa = PBXReferenceProxy;+ fileType = archive.ar;+ path = libCordova.a;+ remoteRef = 301BF534109A57CC0062928A /* PBXContainerItemProxy */;+ sourceTree = BUILT_PRODUCTS_DIR;+ };+ 907D8124214C687600058A10 /* Cordova.framework */ = {+ isa = PBXReferenceProxy;+ fileType = wrapper.framework;+ path = Cordova.framework;+ remoteRef = 907D8123214C687600058A10 /* PBXContainerItemProxy */;+ sourceTree = BUILT_PRODUCTS_DIR;+ };+/* End PBXReferenceProxy section */++/* Begin PBXResourcesBuildPhase section */+ 1D60588D0D05DD3D006BFB54 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 302D95F214D2391D003F00A1 /* MainViewController.xib in Resources */,+ 0207DA581B56EA530066E2B4 /* Images.xcassets in Resources */,+ 6AFF5BF91D6E424B00AB3073 /* CDVLaunchScreen.storyboard in Resources */,+ 721F0E8CD32D41C399A0407B /* appbeep.wav in Resources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXShellScriptBuildPhase section */+ 304B58A110DAC018002A0835 /* Copy www directory */ = {+ isa = PBXShellScriptBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ inputPaths = (+ );+ name = "Copy www directory";+ outputPaths = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "\"$SRCROOT/TagSpaces Beta/Scripts/copy-www-build-step.sh\"";+ showEnvVarsInLog = 0;+ };+/* End PBXShellScriptBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ 1D60588E0D05DD3D006BFB54 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 1D60589B0D05DD56006BFB54 /* main.m in Sources */,+ 1D3623260D0F684500981E51 /* AppDelegate.m in Sources */,+ 302D95F114D2391D003F00A1 /* MainViewController.m in Sources */,+ FD08D10174C049C9B2AF1045 /* CDVDevice.m in Sources */,+ 55E6C374E3FD4A4CABBDF7A2 /* APPBackgroundMode.m in Sources */,+ D542412872474BA08645A2B6 /* APPMethodMagic.m in Sources */,+ 5330031C98004A548A04FB04 /* UIImage+CropScaleOrientation.m in Sources */,+ CDBEA11FAD00489CAAD7BCB3 /* CDVCamera.m in Sources */,+ 44ACB9D58C8147E2AECFD8E3 /* CDVJpegHeaderWriter.m in Sources */,+ 16B2D55C46694FAB859B04D1 /* CDVFile.m in Sources */,+ 93C68FEC56FE482C8A4A2E86 /* CDVLocalFilesystem.m in Sources */,+ ED2346D5DC534F0E8A5C4B72 /* CDVAssetLibraryFilesystem.m in Sources */,+ 9160B31B3A944071B00DBEAA /* FileOpener2.m in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin PBXTargetDependency section */+ 301BF551109A68C00062928A /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ name = CordovaLib;+ targetProxy = 301BF550109A68C00062928A /* PBXContainerItemProxy */;+ };+/* End PBXTargetDependency section */++/* Begin XCBuildConfiguration section */+ 1D6058940D05DD3E006BFB54 /* Debug */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 3047A50F1AB8059700498E2A /* build-debug.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ COPY_PHASE_STRIP = NO;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PRECOMPILE_PREFIX_HEADER = YES;+ GCC_PREFIX_HEADER = "TagSpaces Beta/TagSpaces Beta-Prefix.pch";+ GCC_THUMB_SUPPORT = NO;+ GCC_VERSION = "";+ INFOPLIST_FILE = "TagSpaces Beta/TagSpaces Beta-Info.plist";+ IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";+ PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;+ PRODUCT_NAME = "$(TARGET_NAME)";+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Debug;+ };+ 1D6058950D05DD3E006BFB54 /* Release */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 3047A5101AB8059700498E2A /* build-release.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ COPY_PHASE_STRIP = YES;+ GCC_PRECOMPILE_PREFIX_HEADER = YES;+ GCC_PREFIX_HEADER = "TagSpaces Beta/TagSpaces Beta-Prefix.pch";+ GCC_THUMB_SUPPORT = NO;+ GCC_VERSION = "";+ INFOPLIST_FILE = "TagSpaces Beta/TagSpaces Beta-Info.plist";+ IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";+ PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;+ PRODUCT_NAME = "$(TARGET_NAME)";+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Release;+ };+ C01FCF4F08A954540054247B /* Debug */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 3047A5111AB8059700498E2A /* build.xcconfig */;+ buildSettings = {+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ GCC_C_LANGUAGE_STANDARD = c99;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_THUMB_SUPPORT = NO;+ GCC_VERSION = "";+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = iphoneos;+ SKIP_INSTALL = NO;+ WK_WEB_VIEW_ONLY = 0;+ PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;+ };+ name = Debug;+ };+ C01FCF5008A954540054247B /* Release */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 3047A5111AB8059700498E2A /* build.xcconfig */;+ buildSettings = {+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ GCC_C_LANGUAGE_STANDARD = c99;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_THUMB_SUPPORT = NO;+ GCC_VERSION = "";+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ SDKROOT = iphoneos;+ SKIP_INSTALL = NO;+ WK_WEB_VIEW_ONLY = 0;+ PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "TagSpaces Beta" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 1D6058940D05DD3E006BFB54 /* Debug */,+ 1D6058950D05DD3E006BFB54 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ C01FCF4E08A954540054247B /* Build configuration list for PBXProject "TagSpaces Beta" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ C01FCF4F08A954540054247B /* Debug */,+ C01FCF5008A954540054247B /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */+ };+ rootObject = 29B97313FDCFA39411CA2CEA /* Project object */;+}diff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/contents.xcworkspacedata b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/contents.xcworkspacedatanew file mode 100644index 000000000..81fbd16f1--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "group:TagSpaces Beta.xcodeproj">+ </FileRef>+</Workspace>diff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/IDEWorkspaceChecks.plistnew file mode 100644index 000000000..18d981003--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>IDEDidComputeMac32BitWarning</key>+ <true/>+</dict>+</plist>diff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/xcschemes/TagSpaces Beta.xcscheme b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/xcschemes/TagSpaces Beta.xcschemenew file mode 100644index 000000000..7ae666f35--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/xcschemes/TagSpaces Beta.xcscheme@@ -0,0 +1,91 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme+ LastUpgradeVersion = "0730"+ version = "1.3">+ <BuildAction+ parallelizeBuildables = "YES"+ buildImplicitDependencies = "YES">+ <BuildActionEntries>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "YES"+ buildForProfiling = "YES"+ buildForArchiving = "YES"+ buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "1D6058900D05DD3D006BFB54"+ BuildableName = "TagSpaces Beta.app"+ BlueprintName = "TagSpaces Beta"+ ReferencedContainer = "container:TagSpaces Beta.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ shouldUseLaunchSchemeArgsEnv = "YES">+ <Testables>+ </Testables>+ <MacroExpansion>+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "1D6058900D05DD3D006BFB54"+ BuildableName = "TagSpaces Beta.app"+ BlueprintName = "TagSpaces Beta"+ ReferencedContainer = "container:TagSpaces Beta.xcodeproj">+ </BuildableReference>+ </MacroExpansion>+ <AdditionalOptions>+ </AdditionalOptions>+ </TestAction>+ <LaunchAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ launchStyle = "0"+ useCustomWorkingDirectory = "NO"+ ignoresPersistentStateOnLaunch = "NO"+ debugDocumentVersioning = "YES"+ debugServiceExtension = "internal"+ allowLocationSimulation = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "1D6058900D05DD3D006BFB54"+ BuildableName = "TagSpaces Beta.app"+ BlueprintName = "TagSpaces Beta"+ ReferencedContainer = "container:TagSpaces Beta.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ <AdditionalOptions>+ </AdditionalOptions>+ </LaunchAction>+ <ProfileAction+ buildConfiguration = "Release"+ shouldUseLaunchSchemeArgsEnv = "YES"+ savedToolIdentifier = ""+ useCustomWorkingDirectory = "NO"+ debugDocumentVersioning = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "1D6058900D05DD3D006BFB54"+ BuildableName = "TagSpaces Beta.app"+ BlueprintName = "TagSpaces Beta"+ ReferencedContainer = "container:TagSpaces Beta.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction+ buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction+ buildConfiguration = "Release"+ revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>diff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/UserInterfaceState.xcuserstate b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/UserInterfaceState.xcuserstatenew file mode 100644index 000000000..edca4e942Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/UserInterfaceState.xcuserstate differdiff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plistnew file mode 100644index 000000000..06a18638c--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>SchemeUserState</key>+ <dict>+ <key>TagSpaces Beta.xcscheme_^#shared#^_</key>+ <dict>+ <key>orderHint</key>+ <integer>0</integer>+ </dict>+ </dict>+</dict>+</plist>diff --git a/cordova/platforms/ios/TagSpaces Beta/.gitignore b/cordova/platforms/ios/TagSpaces Beta/.gitignorenew file mode 100644index 000000000..cc76483f6--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/.gitignore@@ -0,0 +1,5 @@+*.mode1v3+*.perspectivev3+*.pbxuser+.DS_Store+build/diff --git a/cordova/platforms/ios/TagSpaces Beta/Bridging-Header.h b/cordova/platforms/ios/TagSpaces Beta/Bridging-Header.hnew file mode 100644index 000000000..5d8abc988--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Bridging-Header.h@@ -0,0 +1,28 @@+/*+ 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.+ */+//+// Bridging-Header.h+// __PROJECT_NAME__+//+// Created by ___FULLUSERNAME___ on ___DATE___.+// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.+//+//+// Use this file to import your target's public headers that you would like to expose to Swift.+//++#import <Cordova/CDV.h>diff --git a/cordova/platforms/ios/TagSpaces Beta/CDVLaunchScreen.storyboard b/cordova/platforms/ios/TagSpaces Beta/CDVLaunchScreen.storyboardnew file mode 100644index 000000000..ffc1d1d65--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/CDVLaunchScreen.storyboard@@ -0,0 +1,60 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<!--+ 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.+-->+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G1004" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">+ <dependencies>+ <deployment identifier="iOS"/>+ <development version="6100" identifier="xcode"/>+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>+ </dependencies>+ <scenes>+ <!--View Controller-->+ <scene sceneID="EHf-IW-A2E">+ <objects>+ <viewController id="01J-lp-oVM" sceneMemberID="viewController">+ <layoutGuides>+ <viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>+ <viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>+ </layoutGuides>+ <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">+ <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>+ <subviews>+ <imageView userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchStoryboard" translatesAutoresizingMaskIntoConstraints="NO" id="2ns-9I-Qjs">+ <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>+ </imageView>+ </subviews>+ <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>+ <constraints>+ <constraint firstAttribute="trailing" secondItem="2ns-9I-Qjs" secondAttribute="trailing" id="FZL-3Z-NFz"/>+ <constraint firstItem="2ns-9I-Qjs" firstAttribute="bottom" secondItem="Ze5-6b-2t3" secondAttribute="bottom" id="L9l-pw-wXj"/>+ <constraint firstItem="2ns-9I-Qjs" firstAttribute="top" secondItem="Ze5-6b-2t3" secondAttribute="top" id="oGN-hc-Uzj"/>+ <constraint firstItem="2ns-9I-Qjs" firstAttribute="leading" secondItem="Ze5-6b-2t3" secondAttribute="leading" id="rS9-Wd-zY4"/>+ </constraints>+ </view>+ </viewController>+ <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>+ </objects>+ <point key="canvasLocation" x="53" y="375"/>+ </scene>+ </scenes>+ <resources>+ <image name="LaunchStoryboard" width="1366" height="1366"/>+ </resources>+</document>diff --git a/cordova/platforms/ios/TagSpaces Beta/Classes/AppDelegate.h b/cordova/platforms/ios/TagSpaces Beta/Classes/AppDelegate.hnew file mode 100644index 000000000..4600dd980--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Classes/AppDelegate.h@@ -0,0 +1,33 @@+/*+ 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.+ */++//+// AppDelegate.h+// TagSpaces Beta+//+// Created by ___FULLUSERNAME___ on ___DATE___.+// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.+//++#import <Cordova/CDVViewController.h>+#import <Cordova/CDVAppDelegate.h>++@interface AppDelegate : CDVAppDelegate {}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Classes/AppDelegate.m b/cordova/platforms/ios/TagSpaces Beta/Classes/AppDelegate.mnew file mode 100644index 000000000..8a998a53e--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Classes/AppDelegate.m@@ -0,0 +1,39 @@+/*+ 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.+ */++//+// AppDelegate.m+// TagSpaces Beta+//+// Created by ___FULLUSERNAME___ on ___DATE___.+// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.+//++#import "AppDelegate.h"+#import "MainViewController.h"++@implementation AppDelegate++- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions+{+ self.viewController = [[MainViewController alloc] init];+ return [super application:application didFinishLaunchingWithOptions:launchOptions];+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.h b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.hnew file mode 100644index 000000000..278854866--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.h@@ -0,0 +1,40 @@+/*+ 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.+ */++//+// MainViewController.h+// TagSpaces Beta+//+// Created by ___FULLUSERNAME___ on ___DATE___.+// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.+//++#import <Cordova/CDVViewController.h>+#import <Cordova/CDVCommandDelegateImpl.h>+#import <Cordova/CDVCommandQueue.h>++@interface MainViewController : CDVViewController++@end++@interface MainCommandDelegate : CDVCommandDelegateImpl+@end++@interface MainCommandQueue : CDVCommandQueue+@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.m b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.mnew file mode 100644index 000000000..633d184f6--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.m@@ -0,0 +1,148 @@+/*+ 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.+ */++//+// MainViewController.h+// TagSpaces Beta+//+// Created by ___FULLUSERNAME___ on ___DATE___.+// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.+//++#import "MainViewController.h"++@implementation MainViewController++- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil+{+ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];+ if (self) {+ // Uncomment to override the CDVCommandDelegateImpl used+ // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];+ // Uncomment to override the CDVCommandQueue used+ // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];+ }+ return self;+}++- (id)init+{+ self = [super init];+ if (self) {+ // Uncomment to override the CDVCommandDelegateImpl used+ // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];+ // Uncomment to override the CDVCommandQueue used+ // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];+ }+ return self;+}++- (void)didReceiveMemoryWarning+{+ // Releases the view if it doesn't have a superview.+ [super didReceiveMemoryWarning];++ // Release any cached data, images, etc that aren't in use.+}++#pragma mark View lifecycle++- (void)viewWillAppear:(BOOL)animated+{+ // View defaults to full size. If you want to customize the view's size, or its subviews (e.g. webView),+ // you can do so here.++ [super viewWillAppear:animated];+}++- (void)viewDidLoad+{+ [super viewDidLoad];+ // Do any additional setup after loading the view from its nib.+}++- (void)viewDidUnload+{+ [super viewDidUnload];+ // Release any retained subviews of the main view.+ // e.g. self.myOutlet = nil;+}++/* Comment out the block below to over-ride */++/*+- (UIWebView*) newCordovaViewWithFrame:(CGRect)bounds+{+ return[super newCordovaViewWithFrame:bounds];+}++// CB-12098+#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000+- (NSUInteger)supportedInterfaceOrientations+#else+- (UIInterfaceOrientationMask)supportedInterfaceOrientations+#endif+{+ return [super supportedInterfaceOrientations];+}++- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation+{+ return [super shouldAutorotateToInterfaceOrientation:interfaceOrientation];+}++- (BOOL)shouldAutorotate+{+ return [super shouldAutorotate];+}+*/++@end++@implementation MainCommandDelegate++/* To override the methods, uncomment the line in the init function(s)+ in MainViewController.m+ */++#pragma mark CDVCommandDelegate implementation++- (id)getCommandInstance:(NSString*)className+{+ return [super getCommandInstance:className];+}++- (NSString*)pathForResource:(NSString*)resourcepath+{+ return [super pathForResource:resourcepath];+}++@end++@implementation MainCommandQueue++/* To override, uncomment the line in the init function(s)+ in MainViewController.m+ */+- (BOOL)execute:(CDVInvokedUrlCommand*)command+{+ return [super execute:command];+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.xib b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.xibnew file mode 100644index 000000000..e45d65c61--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.xib@@ -0,0 +1,138 @@+<?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.+#+-->+<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="8.00">+ <data>+ <int key="IBDocument.SystemTarget">1280</int>+ <string key="IBDocument.SystemVersion">11C25</string>+ <string key="IBDocument.InterfaceBuilderVersion">1919</string>+ <string key="IBDocument.AppKitVersion">1138.11</string>+ <string key="IBDocument.HIToolboxVersion">566.00</string>+ <object class="NSMutableDictionary" key="IBDocument.PluginVersions">+ <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>+ <string key="NS.object.0">916</string>+ </object>+ <array key="IBDocument.IntegratedClassDependencies">+ <string>IBProxyObject</string>+ <string>IBUIView</string>+ </array>+ <array key="IBDocument.PluginDependencies">+ <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>+ </array>+ <object class="NSMutableDictionary" key="IBDocument.Metadata">+ <string key="NS.key.0">PluginDependencyRecalculationVersion</string>+ <integer value="1" key="NS.object.0"/>+ </object>+ <array class="NSMutableArray" key="IBDocument.RootObjects" id="1000">+ <object class="IBProxyObject" id="372490531">+ <string key="IBProxiedObjectIdentifier">IBFilesOwner</string>+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>+ </object>+ <object class="IBProxyObject" id="975951072">+ <string key="IBProxiedObjectIdentifier">IBFirstResponder</string>+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>+ </object>+ <object class="IBUIView" id="191373211">+ <reference key="NSNextResponder"/>+ <int key="NSvFlags">274</int>+ <string key="NSFrame">{{0, 20}, {320, 460}}</string>+ <reference key="NSSuperview"/>+ <reference key="NSWindow"/>+ <object class="NSColor" key="IBUIBackgroundColor">+ <int key="NSColorSpace">3</int>+ <bytes key="NSWhite">MQA</bytes>+ <object class="NSColorSpace" key="NSCustomColorSpace">+ <int key="NSID">2</int>+ </object>+ </object>+ <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics"/>+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>+ </object>+ </array>+ <object class="IBObjectContainer" key="IBDocument.Objects">+ <array class="NSMutableArray" key="connectionRecords">+ <object class="IBConnectionRecord">+ <object class="IBCocoaTouchOutletConnection" key="connection">+ <string key="label">view</string>+ <reference key="source" ref="372490531"/>+ <reference key="destination" ref="191373211"/>+ </object>+ <int key="connectionID">3</int>+ </object>+ </array>+ <object class="IBMutableOrderedSet" key="objectRecords">+ <array key="orderedObjects">+ <object class="IBObjectRecord">+ <int key="objectID">0</int>+ <array key="object" id="0"/>+ <reference key="children" ref="1000"/>+ <nil key="parent"/>+ </object>+ <object class="IBObjectRecord">+ <int key="objectID">1</int>+ <reference key="object" ref="191373211"/>+ <reference key="parent" ref="0"/>+ </object>+ <object class="IBObjectRecord">+ <int key="objectID">-1</int>+ <reference key="object" ref="372490531"/>+ <reference key="parent" ref="0"/>+ <string key="objectName">File's Owner</string>+ </object>+ <object class="IBObjectRecord">+ <int key="objectID">-2</int>+ <reference key="object" ref="975951072"/>+ <reference key="parent" ref="0"/>+ </object>+ </array>+ </object>+ <dictionary class="NSMutableDictionary" key="flattenedProperties">+ <string key="-1.CustomClassName">MainViewController</string>+ <string key="-1.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>+ <string key="-2.CustomClassName">UIResponder</string>+ <string key="-2.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>+ <string key="1.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>+ </dictionary>+ <dictionary class="NSMutableDictionary" key="unlocalizedProperties"/>+ <nil key="activeLocalization"/>+ <dictionary class="NSMutableDictionary" key="localizations"/>+ <nil key="sourceID"/>+ <int key="maxID">3</int>+ </object>+ <object class="IBClassDescriber" key="IBDocument.Classes">+ <array class="NSMutableArray" key="referencedPartialClassDescriptions">+ <object class="IBPartialClassDescription">+ <string key="className">MainViewController</string>+ <string key="superclassName">UIViewController</string>+ <object class="IBClassDescriptionSource" key="sourceIdentifier">+ <string key="majorKey">IBProjectSource</string>+ <string key="minorKey">./Classes/MainViewController.h</string>+ </object>+ </object>+ </array>+ </object>+ <int key="IBDocument.localizationMode">0</int>+ <string key="IBDocument.TargetRuntimeIdentifier">IBCocoaTouchFramework</string>+ <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>+ <int key="IBDocument.defaultPropertyAccessControl">3</int>+ <string key="IBCocoaTouchPluginVersion">916</string>+ </data>+</archive>diff --git a/cordova/platforms/ios/TagSpaces Beta/Entitlements-Debug.plist b/cordova/platforms/ios/TagSpaces Beta/Entitlements-Debug.plistnew file mode 100644index 000000000..1ed4ae5b9--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Entitlements-Debug.plist@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!--+ 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.+-->+<plist version="1.0">+ <dict>+ </dict>+</plist>diff --git a/cordova/platforms/ios/TagSpaces Beta/Entitlements-Release.plist b/cordova/platforms/ios/TagSpaces Beta/Entitlements-Release.plistnew file mode 100644index 000000000..1ed4ae5b9--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Entitlements-Release.plist@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<!--+ 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.+-->+<plist version="1.0">+ <dict>+ </dict>+</plist>diff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/Contents.json b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 000000000..2ce78c1b3--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,241 @@+{+ "images" : [+ {+ "size" : "20x20",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "20x20",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "29x29",+ "idiom" : "iphone",+ "filename" : "icon-29.png",+ "scale" : "1x"+ },+ {+ "size" : "29x29",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "29x29",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "40x40",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "40x40",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "57x57",+ "idiom" : "iphone",+ "filename" : "icon.png",+ "scale" : "1x"+ },+ {+ "size" : "57x57",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "60x60",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "60x60",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "20x20",+ "idiom" : "ipad",+ "filename" : "icon-20.png",+ "scale" : "1x"+ },+ {+ "size" : "20x20",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "29x29",+ "idiom" : "ipad",+ "filename" : "icon-29.png",+ "scale" : "1x"+ },+ {+ "size" : "29x29",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "40x40",+ "idiom" : "ipad",+ "filename" : "icon-40.png",+ "scale" : "1x"+ },+ {+ "size" : "40x40",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "50x50",+ "idiom" : "ipad",+ "filename" : "icon-50.png",+ "scale" : "1x"+ },+ {+ "size" : "50x50",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "72x72",+ "idiom" : "ipad",+ "filename" : "icon-72.png",+ "scale" : "1x"+ },+ {+ "size" : "72x72",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "76x76",+ "idiom" : "ipad",+ "filename" : "icon-76.png",+ "scale" : "1x"+ },+ {+ "size" : "76x76",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "83.5x83.5",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "1024x1024",+ "idiom" : "ios-marketing",+ "filename" : "icon-1024.png",+ "scale" : "1x"+ },+ {+ "size" : "24x24",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "scale" : "2x",+ "role" : "notificationCenter",+ "subtype" : "38mm"+ },+ {+ "size" : "27.5x27.5",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "scale" : "2x",+ "role" : "notificationCenter",+ "subtype" : "42mm"+ },+ {+ "size" : "29x29",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "role" : "companionSettings",+ "scale" : "2x"+ },+ {+ "size" : "29x29",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "role" : "companionSettings",+ "scale" : "3x"+ },+ {+ "size" : "40x40",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "scale" : "2x",+ "role" : "appLauncher",+ "subtype" : "38mm"+ },+ {+ "size" : "44x44",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "scale" : "2x",+ "role" : "appLauncher",+ "subtype" : "40mm"+ },+ {+ "size" : "50x50",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "scale" : "2x",+ "role" : "appLauncher",+ "subtype" : "44mm"+ },+ {+ "size" : "86x86",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "scale" : "2x",+ "role" : "quickLook",+ "subtype" : "38mm"+ },+ {+ "size" : "98x98",+ "idiom" : "watch",+ "filename" : "[email protected]",+ "scale" : "2x",+ "role" : "quickLook",+ "subtype" : "42mm"+ },+ {+ "size" : "108x108",+ "idiom" : "watch",+ "scale" : "2x",+ "role" : "quickLook",+ "subtype" : "44mm"+ },+ {+ "size" : "1024x1024",+ "idiom" : "watch-marketing",+ "filename" : "icon-1024.png",+ "scale" : "1x"+ }+ ],+ "info" : {+ "version" : 1,+ "author" : "xcode"+ }+}\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-1024.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-1024.pngnew file mode 100644index 000000000..1b9cbb91eBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-1024.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-20.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-20.pngnew file mode 100644index 000000000..5788eed9fBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-20.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..4feefdf8cBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..69ce592c2Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..f0babf9d3Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..78f21bb35Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-29.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-29.pngnew file mode 100644index 000000000..5dff98e93Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-29.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..34b390857Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..c63fd7766Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-40.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-40.pngnew file mode 100644index 000000000..4feefdf8cBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-40.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..328973636Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..01c5af720Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-50.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-50.pngnew file mode 100644index 000000000..81f93f16cBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-50.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..a980efe1cBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..1e794a481Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..db10c5532Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-72.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-72.pngnew file mode 100644index 000000000..097f5b40aBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-72.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..e3d49a2f1Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-76.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-76.pngnew file mode 100644index 000000000..aa6810c37Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon-76.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..da3a050ffBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..039a02aefBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..f32a034a0Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..85ec9e369Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon.pngnew file mode 100644index 000000000..bbdba9ee0Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/icon.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 000000000..41e6be4a6Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/Contents.json b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/Contents.jsonnew file mode 100644index 000000000..da4a164c9--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info" : {+ "version" : 1,+ "author" : "xcode"+ }+}\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Contents.json b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Contents.jsonnew file mode 100644index 000000000..58735deb7--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Contents.json@@ -0,0 +1,176 @@+{+ "images" : [+ {+ "extent": "full-screen",+ "idiom": "iphone",+ "subtype": "2436h",+ "filename": "Default-2436h.png",+ "minimum-system-version": "11.0",+ "orientation": "portrait",+ "scale": "3x"+ },+ {+ "extent": "full-screen",+ "idiom": "iphone",+ "subtype": "2436h",+ "filename": "Default-Landscape-2436h.png",+ "minimum-system-version": "11.0",+ "orientation": "landscape",+ "scale": "3x"+ },+ {+ "extent" : "full-screen",+ "idiom" : "iphone",+ "subtype" : "736h",+ "filename" : "Default-736h.png",+ "minimum-system-version" : "8.0",+ "orientation" : "portrait",+ "scale" : "3x"+ },+ {+ "extent" : "full-screen",+ "idiom" : "iphone",+ "subtype" : "736h",+ "filename" : "Default-Landscape-736h.png",+ "minimum-system-version" : "8.0",+ "orientation" : "landscape",+ "scale" : "3x"+ },+ {+ "extent" : "full-screen",+ "idiom" : "iphone",+ "subtype" : "667h",+ "filename" : "Default-667h.png",+ "minimum-system-version" : "8.0",+ "orientation" : "portrait",+ "scale" : "2x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "iphone",+ "filename" : "Default@2x~iphone.png",+ "extent" : "full-screen",+ "minimum-system-version" : "7.0",+ "scale" : "2x"+ },+ {+ "extent" : "full-screen",+ "idiom" : "iphone",+ "subtype" : "retina4",+ "filename" : "Default-568h@2x~iphone.png",+ "minimum-system-version" : "7.0",+ "orientation" : "portrait",+ "scale" : "2x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "ipad",+ "filename" : "Default-Portrait~ipad.png",+ "extent" : "full-screen",+ "minimum-system-version" : "7.0",+ "scale" : "1x"+ },+ {+ "orientation" : "landscape",+ "idiom" : "ipad",+ "filename" : "Default-Landscape~ipad.png",+ "extent" : "full-screen",+ "minimum-system-version" : "7.0",+ "scale" : "1x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "ipad",+ "filename" : "Default-Portrait@2x~ipad.png",+ "extent" : "full-screen",+ "minimum-system-version" : "7.0",+ "scale" : "2x"+ },+ {+ "orientation" : "landscape",+ "idiom" : "ipad",+ "filename" : "Default-Landscape@2x~ipad.png",+ "extent" : "full-screen",+ "minimum-system-version" : "7.0",+ "scale" : "2x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "iphone",+ "filename" : "Default~iphone.png",+ "extent" : "full-screen",+ "scale" : "1x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "iphone",+ "filename" : "Default@2x~iphone.png",+ "extent" : "full-screen",+ "scale" : "2x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "iphone",+ "filename" : "Default-568h@2x~iphone.png",+ "extent" : "full-screen",+ "subtype" : "retina4",+ "scale" : "2x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "ipad",+ "extent" : "to-status-bar",+ "scale" : "1x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "ipad",+ "filename" : "Default-Portrait~ipad.png",+ "extent" : "full-screen",+ "scale" : "1x"+ },+ {+ "orientation" : "landscape",+ "idiom" : "ipad",+ "extent" : "to-status-bar",+ "scale" : "1x"+ },+ {+ "orientation" : "landscape",+ "idiom" : "ipad",+ "filename": "Default-Landscape~ipad.png",+ "extent" : "full-screen",+ "scale" : "1x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "ipad",+ "extent" : "to-status-bar",+ "scale" : "2x"+ },+ {+ "orientation" : "portrait",+ "idiom" : "ipad",+ "filename" : "Default-Portrait@2x~ipad.png",+ "extent" : "full-screen",+ "scale" : "2x"+ },+ {+ "orientation" : "landscape",+ "idiom" : "ipad",+ "extent" : "to-status-bar",+ "scale" : "2x"+ },+ {+ "orientation" : "landscape",+ "idiom" : "ipad",+ "filename": "Default-Landscape@2x~ipad.png",+ "extent" : "full-screen",+ "scale" : "2x"+ }+ ],+ "info" : {+ "version" : 1,+ "author" : "xcode"+ }+}diff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-2436h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-2436h.pngnew file mode 100644index 000000000..b124dcf05Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-2436h.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-568h@2x~iphone.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-568h@2x~iphone.pngnew file mode 100644index 000000000..f353b070fBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-568h@2x~iphone.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-667h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-667h.pngnew file mode 100644index 000000000..d5f371857Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-667h.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-736h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-736h.pngnew file mode 100644index 000000000..f70767a2cBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-736h.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-2436h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-2436h.pngnew file mode 100644index 000000000..c062b2accBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-2436h.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h.pngnew file mode 100644index 000000000..321ca2ea3Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape@2x~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape@2x~ipad.pngnew file mode 100644index 000000000..62b212ebcBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape@2x~ipad.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape~ipad.pngnew file mode 100644index 000000000..00169cbf3Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape~ipad.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait@2x~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait@2x~ipad.pngnew file mode 100644index 000000000..e4a8a1971Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait@2x~ipad.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait~ipad.pngnew file mode 100644index 000000000..d9597f4e3Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait~ipad.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default@2x~iphone.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default@2x~iphone.pngnew file mode 100644index 000000000..e01371585Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default@2x~iphone.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default~iphone.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default~iphone.pngnew file mode 100644index 000000000..0266273a2Binary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default~iphone.png differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchStoryboard.imageset/Contents.json b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchStoryboard.imageset/Contents.jsonnew file mode 100644index 000000000..621019de2--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchStoryboard.imageset/Contents.json@@ -0,0 +1,168 @@+{+ "images": [+ {+ "idiom": "universal",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "1x",+ "width-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "1x",+ "height-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "1x"+ },+ {+ "idiom": "universal",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "2x",+ "width-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "2x",+ "height-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "2x"+ },+ {+ "idiom": "universal",+ "scale": "3x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "3x",+ "width-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "3x",+ "height-class": "compact"+ },+ {+ "idiom": "universal",+ "scale": "3x"+ },+ {+ "idiom": "ipad",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "ipad",+ "scale": "1x",+ "width-class": "compact"+ },+ {+ "idiom": "ipad",+ "scale": "1x",+ "height-class": "compact"+ },+ {+ "idiom": "ipad",+ "scale": "1x"+ },+ {+ "idiom": "ipad",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "ipad",+ "scale": "2x",+ "width-class": "compact"+ },+ {+ "idiom": "ipad",+ "scale": "2x",+ "height-class": "compact"+ },+ {+ "idiom": "ipad",+ "scale": "2x"+ },+ {+ "idiom": "iphone",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "1x",+ "width-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "1x",+ "height-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "1x"+ },+ {+ "idiom": "iphone",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "2x",+ "width-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "2x",+ "height-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "2x"+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "width-class": "compact",+ "height-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "width-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "height-class": "compact"+ },+ {+ "idiom": "iphone",+ "scale": "3x"+ }+ ],+ "info": {+ "author": "Xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/README b/cordova/platforms/ios/TagSpaces Beta/Plugins/READMEnew file mode 100644index 000000000..87df09f2c--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/README@@ -0,0 +1,20 @@+#+# 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.+#++Put the .h and .m files of your plugin here. The .js files of your plugin belong in the www folder.diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPBackgroundMode.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPBackgroundMode.hnew file mode 100644index 000000000..e7ed1e5a3--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPBackgroundMode.h@@ -0,0 +1,35 @@+/*+ Copyright 2013-2017 appPlant GmbH++ 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 <AVFoundation/AVFoundation.h>+#import <Cordova/CDVPlugin.h>++@interface APPBackgroundMode : CDVPlugin {+ AVAudioPlayer* audioPlayer;+ BOOL enabled;+}++// Activate the background mode+- (void) enable:(CDVInvokedUrlCommand*)command;+// Deactivate the background mode+- (void) disable:(CDVInvokedUrlCommand*)command;++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPBackgroundMode.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPBackgroundMode.mnew file mode 100644index 000000000..e0792cccc--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPBackgroundMode.m@@ -0,0 +1,276 @@+/*+ Copyright 2013-2017 appPlant GmbH++ 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 "APPMethodMagic.h"+#import "APPBackgroundMode.h"+#import <Cordova/CDVAvailability.h>++@implementation APPBackgroundMode++#pragma mark -+#pragma mark Constants++NSString* const kAPPBackgroundJsNamespace = @"cordova.plugins.backgroundMode";+NSString* const kAPPBackgroundEventActivate = @"activate";+NSString* const kAPPBackgroundEventDeactivate = @"deactivate";+++#pragma mark -+#pragma mark Life Cycle++/**+ * Called by runtime once the Class has been loaded.+ * Exchange method implementations to hook into their execution.+ */++ (void) load+{+ [self swizzleWKWebViewEngine];+}++/**+ * Initialize the plugin.+ */+- (void) pluginInitialize+{+ enabled = NO;+ [self configureAudioPlayer];+ [self configureAudioSession];+ [self observeLifeCycle];+}++/**+ * Register the listener for pause and resume events.+ */+- (void) observeLifeCycle+{+ NSNotificationCenter* listener = [NSNotificationCenter+ defaultCenter];++ [listener addObserver:self+ selector:@selector(keepAwake)+ name:UIApplicationDidEnterBackgroundNotification+ object:nil];++ [listener addObserver:self+ selector:@selector(stopKeepingAwake)+ name:UIApplicationWillEnterForegroundNotification+ object:nil];++ [listener addObserver:self+ selector:@selector(handleAudioSessionInterruption:)+ name:AVAudioSessionInterruptionNotification+ object:nil];+}++#pragma mark -+#pragma mark Interface++/**+ * Enable the mode to stay awake+ * when switching to background for the next time.+ */+- (void) enable:(CDVInvokedUrlCommand*)command+{+ if (enabled)+ return;++ enabled = YES;+ [self execCallback:command];+}++/**+ * Disable the background mode+ * and stop being active in background.+ */+- (void) disable:(CDVInvokedUrlCommand*)command+{+ if (!enabled)+ return;++ enabled = NO;+ [self stopKeepingAwake];+ [self execCallback:command];+}++#pragma mark -+#pragma mark Core++/**+ * Keep the app awake.+ */+- (void) keepAwake+{+ if (!enabled)+ return;++ [audioPlayer play];+ [self fireEvent:kAPPBackgroundEventActivate];+}++/**+ * Let the app going to sleep.+ */+- (void) stopKeepingAwake+{+ if (TARGET_IPHONE_SIMULATOR) {+ NSLog(@"BackgroundMode: On simulator apps never pause in background!");+ }++ if (audioPlayer.isPlaying) {+ [self fireEvent:kAPPBackgroundEventDeactivate];+ }++ [audioPlayer pause];+}++/**+ * Configure the audio player.+ */+- (void) configureAudioPlayer+{+ NSString* path = [[NSBundle mainBundle]+ pathForResource:@"appbeep" ofType:@"wav"];++ NSURL* url = [NSURL fileURLWithPath:path];+++ audioPlayer = [[AVAudioPlayer alloc]+ initWithContentsOfURL:url error:NULL];++ audioPlayer.volume = 0;+ audioPlayer.numberOfLoops = -1;+};++/**+ * Configure the audio session.+ */+- (void) configureAudioSession+{+ AVAudioSession* session = [AVAudioSession+ sharedInstance];++ // Don't activate the audio session yet+ [session setActive:NO error:NULL];++ // Play music even in background and dont stop playing music+ // even another app starts playing sound+ [session setCategory:AVAudioSessionCategoryPlayback+ error:NULL];++ // Active the audio session+ [session setActive:YES error:NULL];+};++#pragma mark -+#pragma mark Helper++/**+ * Simply invokes the callback without any parameter.+ */+- (void) execCallback:(CDVInvokedUrlCommand*)command+{+ CDVPluginResult *result = [CDVPluginResult+ resultWithStatus:CDVCommandStatus_OK];++ [self.commandDelegate sendPluginResult:result+ callbackId:command.callbackId];+}++/**+ * Restart playing sound when interrupted by phone calls.+ */+- (void) handleAudioSessionInterruption:(NSNotification*)notification+{+ [self fireEvent:kAPPBackgroundEventDeactivate];+ [self keepAwake];+}++/**+ * Find out if the app runs inside the webkit powered webview.+ */++ (BOOL) isRunningWebKit+{+ return IsAtLeastiOSVersion(@"8.0") && NSClassFromString(@"CDVWKWebViewEngine");+}++/**+ * Method to fire an event with some parameters in the browser.+ */+- (void) fireEvent:(NSString*)event+{+ NSString* active =+ [event isEqualToString:kAPPBackgroundEventActivate] ? @"true" : @"false";++ NSString* flag = [NSString stringWithFormat:@"%@._isActive=%@;",+ kAPPBackgroundJsNamespace, active];++ NSString* depFn = [NSString stringWithFormat:@"%@.on('%@');",+ kAPPBackgroundJsNamespace, event];++ NSString* fn = [NSString stringWithFormat:@"%@.fireEvent('%@');",+ kAPPBackgroundJsNamespace, event];++ NSString* js = [NSString stringWithFormat:@"%@%@%@", flag, depFn, fn];++ [self.commandDelegate evalJs:js];+}++#pragma mark -+#pragma mark Swizzling++/**+ * Method to swizzle.+ */++ (NSString*) wkProperty+{+ NSString* str = @"YWx3YXlzUnVuc0F0Rm9yZWdyb3VuZFByaW9yaXR5";+ NSData* data = [[NSData alloc] initWithBase64EncodedString:str options:0];++ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];+}++/**+ * Swizzle some implementations of CDVWKWebViewEngine.+ */++ (void) swizzleWKWebViewEngine+{+ if (![self isRunningWebKit])+ return;++ Class wkWebViewEngineCls = NSClassFromString(@"CDVWKWebViewEngine");+ SEL selector = NSSelectorFromString(@"createConfigurationFromSettings:");++ SwizzleSelectorWithBlock_Begin(wkWebViewEngineCls, selector)+ ^(CDVPlugin *self, NSDictionary *settings) {+ id obj = ((id (*)(id, SEL, NSDictionary*))_imp)(self, _cmd, settings);++ [obj setValue:[NSNumber numberWithBool:YES]+ forKey:[APPBackgroundMode wkProperty]];++ [obj setValue:[NSNumber numberWithBool:NO]+ forKey:@"requiresUserActionForMediaPlayback"];++ return obj;+ }+ SwizzleSelectorWithBlock_End;+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPMethodMagic.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPMethodMagic.hnew file mode 100644index 000000000..84de79111--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPMethodMagic.h@@ -0,0 +1,93 @@+/*+ Copyright 2013-2017 appPlant GmbH++ 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.+*/++/**+ * Code extracted from+ * - http://defagos.github.io/yet_another_article_about_method_swizzling/+ * - https://gist.github.com/defagos/1312fec96b48540efa5c+ */++#import <objc/runtime.h>+#import <objc/message.h>++#define SwizzleSelector(clazz, selector, newImpl, oldImpl) \+(*oldImpl) = (__typeof((*oldImpl)))class_swizzleSelector((clazz), (selector), (IMP)(newImpl))++#define SwizzleClassSelector(clazz, selector, newImpl, oldImpl) \+(*oldImpl) = (__typeof((*oldImpl)))class_swizzleClassSelector((clazz), (selector), (IMP)(newImpl))++#define SwizzleSelectorWithBlock_Begin(clazz, selector) { \+SEL _cmd = selector; \+__block IMP _imp = class_swizzleSelectorWithBlock((clazz), (selector),+#define SwizzleSelectorWithBlock_End );}++#define SwizzleClassSelectorWithBlock_Begin(clazz, selector) { \+SEL _cmd = selector; \+__block IMP _imp = class_swizzleClassSelectorWithBlock((clazz), (selector),+#define SwizzleClassSelectorWithBlock_End );}++/**+ * Swizzle class method specified by class and selector+ * through the provided method implementation.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ IMP ] newImpl The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleClassSelector(Class clazz, SEL selector, IMP newImpl);++/**+ * Swizzle class method specified by class and selector+ * through the provided code block.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ id ] newImplBlock The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleClassSelectorWithBlock(Class clazz, SEL selector, id newImplBlock);++/**+ * Swizzle method specified by class and selector+ * through the provided code block.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ id ] newImplBlock The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleSelectorWithBlock(Class clazz, SEL selector, id newImplBlock);++/**+ * Swizzle method specified by class and selector+ * through the provided method implementation.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ IMP ] newImpl The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleSelector(Class clazz, SEL selector, IMP newImpl);diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPMethodMagic.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPMethodMagic.mnew file mode 100644index 000000000..cb9cc35f5--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-background-mode/APPMethodMagic.m@@ -0,0 +1,105 @@+/*+ Copyright 2013-2017 appPlant GmbH++ 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.+*/++/**+ * Code extracted from+ * - http://defagos.github.io/yet_another_article_about_method_swizzling/+ * - https://gist.github.com/defagos/1312fec96b48540efa5c+ */++#import "APPMethodMagic.h"+#import <objc/runtime.h>+#import <objc/message.h>++/**+ * Swizzle class method specified by class and selector+ * through the provided method implementation.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ IMP ] newImpl The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleClassSelector(Class clazz, SEL selector, IMP newImpl)+{+ return class_swizzleSelector(object_getClass(clazz), selector, newImpl);+}++/**+ * Swizzle class method specified by class and selector+ * through the provided code block.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ id ] newImplBlock The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleClassSelectorWithBlock(Class clazz, SEL selector, id newImplBlock)+{+ IMP newImpl = imp_implementationWithBlock(newImplBlock);+ return class_swizzleClassSelector(clazz, selector, newImpl);+}++/**+ * Swizzle method specified by class and selector+ * through the provided code block.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ id ] newImplBlock The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleSelectorWithBlock(Class clazz, SEL selector, id newImplBlock)+{+ IMP newImpl = imp_implementationWithBlock(newImplBlock);+ return class_swizzleSelector(clazz, selector, newImpl);+}++/**+ * Swizzle method specified by class and selector+ * through the provided method implementation.+ *+ * @param [ Class ] clazz The class containing the method.+ * @param [ SEL ] selector The selector of the method.+ * @param [ IMP ] newImpl The new implementation of the method.+ *+ * @return [ IMP ] The previous implementation of the method.+ */+IMP class_swizzleSelector(Class clazz, SEL selector, IMP newImpl)+{+ Method method = class_getInstanceMethod(clazz, selector);+ const char *types = method_getTypeEncoding(method);++ class_addMethod(clazz, selector, imp_implementationWithBlock(^(__unsafe_unretained id self, va_list argp) {+ struct objc_super super = {+ .receiver = self,+ .super_class = class_getSuperclass(clazz)+ };++ id (*objc_msgSendSuper_typed)(struct objc_super*, SEL, va_list) = (void*)&objc_msgSendSuper;+ return objc_msgSendSuper_typed(&super, selector, argp);+ }), types);++ return class_replaceMethod(clazz, selector, newImpl, types);+}diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVCamera.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVCamera.hnew file mode 100644index 000000000..f64f66c27--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVCamera.h@@ -0,0 +1,116 @@+/*+ 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 <CoreLocation/CoreLocation.h>+#import <CoreLocation/CLLocationManager.h>+#import <Cordova/CDVPlugin.h>++enum CDVDestinationType {+ DestinationTypeDataUrl = 0,+ DestinationTypeFileUri,+ DestinationTypeNativeUri+};+typedef NSUInteger CDVDestinationType;++enum CDVEncodingType {+ EncodingTypeJPEG = 0,+ EncodingTypePNG+};+typedef NSUInteger CDVEncodingType;++enum CDVMediaType {+ MediaTypePicture = 0,+ MediaTypeVideo,+ MediaTypeAll+};+typedef NSUInteger CDVMediaType;++@interface CDVPictureOptions : NSObject++@property (strong) NSNumber* quality;+@property (assign) CDVDestinationType destinationType;+@property (assign) UIImagePickerControllerSourceType sourceType;+@property (assign) CGSize targetSize;+@property (assign) CDVEncodingType encodingType;+@property (assign) CDVMediaType mediaType;+@property (assign) BOOL allowsEditing;+@property (assign) BOOL correctOrientation;+@property (assign) BOOL saveToPhotoAlbum;+@property (strong) NSDictionary* popoverOptions;+@property (assign) UIImagePickerControllerCameraDevice cameraDirection;++@property (assign) BOOL popoverSupported;+@property (assign) BOOL usesGeolocation;+@property (assign) BOOL cropToSize;+++ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand*)command;++@end++@interface CDVCameraPicker : UIImagePickerController++@property (strong) CDVPictureOptions* pictureOptions;++@property (copy) NSString* callbackId;+@property (copy) NSString* postUrl;+@property (strong) UIPopoverController* pickerPopoverController;+@property (assign) BOOL cropToSize;+@property (strong) UIView* webView;+++ (instancetype) createFromPictureOptions:(CDVPictureOptions*)options;++@end++// ======================================================================= //++@interface CDVCamera : CDVPlugin <UIImagePickerControllerDelegate,+ UINavigationControllerDelegate,+ UIPopoverControllerDelegate,+ CLLocationManagerDelegate>+{}++@property (strong) CDVCameraPicker* pickerController;+@property (strong) NSMutableDictionary *metadata;+@property (strong, nonatomic) CLLocationManager *locationManager;+@property (strong) NSData* data;++/*+ * getPicture+ *+ * arguments:+ * 1: this is the javascript function that will be called with the results, the first parameter passed to the+ * javascript function is the picture as a Base64 encoded string+ * 2: this is the javascript function to be called if there was an error+ * options:+ * quality: integer between 1 and 100+ */+- (void)takePicture:(CDVInvokedUrlCommand*)command;+- (void)cleanup:(CDVInvokedUrlCommand*)command;+- (void)repositionPopover:(CDVInvokedUrlCommand*)command;++- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info;+- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo;+- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker;+- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;++- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation;+- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVCamera.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVCamera.mnew file mode 100644index 000000000..bf02ca2e6--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVCamera.m@@ -0,0 +1,773 @@+/*+ 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 "CDVCamera.h"+#import "CDVJpegHeaderWriter.h"+#import "UIImage+CropScaleOrientation.h"+#import <ImageIO/CGImageProperties.h>+#import <AssetsLibrary/ALAssetRepresentation.h>+#import <AssetsLibrary/AssetsLibrary.h>+#import <AVFoundation/AVFoundation.h>+#import <ImageIO/CGImageSource.h>+#import <ImageIO/CGImageProperties.h>+#import <ImageIO/CGImageDestination.h>+#import <MobileCoreServices/UTCoreTypes.h>+#import <objc/message.h>++#ifndef __CORDOVA_4_0_0+ #import <Cordova/NSData+Base64.h>+#endif++#define CDV_PHOTO_PREFIX @"cdv_photo_"++static NSSet* org_apache_cordova_validArrowDirections;++static NSString* toBase64(NSData* data) {+ SEL s1 = NSSelectorFromString(@"cdv_base64EncodedString");+ SEL s2 = NSSelectorFromString(@"base64EncodedString");+ SEL s3 = NSSelectorFromString(@"base64EncodedStringWithOptions:");++ if ([data respondsToSelector:s1]) {+ NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s1];+ return func(data, s1);+ } else if ([data respondsToSelector:s2]) {+ NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s2];+ return func(data, s2);+ } else if ([data respondsToSelector:s3]) {+ NSString* (*func)(id, SEL, NSUInteger) = (void *)[data methodForSelector:s3];+ return func(data, s3, 0);+ } else {+ return nil;+ }+}++@implementation CDVPictureOptions+++ (instancetype) createFromTakePictureArguments:(CDVInvokedUrlCommand*)command+{+ CDVPictureOptions* pictureOptions = [[CDVPictureOptions alloc] init];++ pictureOptions.quality = [command argumentAtIndex:0 withDefault:@(50)];+ pictureOptions.destinationType = [[command argumentAtIndex:1 withDefault:@(DestinationTypeFileUri)] unsignedIntegerValue];+ pictureOptions.sourceType = [[command argumentAtIndex:2 withDefault:@(UIImagePickerControllerSourceTypeCamera)] unsignedIntegerValue];++ NSNumber* targetWidth = [command argumentAtIndex:3 withDefault:nil];+ NSNumber* targetHeight = [command argumentAtIndex:4 withDefault:nil];+ pictureOptions.targetSize = CGSizeMake(0, 0);+ if ((targetWidth != nil) && (targetHeight != nil)) {+ pictureOptions.targetSize = CGSizeMake([targetWidth floatValue], [targetHeight floatValue]);+ }++ pictureOptions.encodingType = [[command argumentAtIndex:5 withDefault:@(EncodingTypeJPEG)] unsignedIntegerValue];+ pictureOptions.mediaType = [[command argumentAtIndex:6 withDefault:@(MediaTypePicture)] unsignedIntegerValue];+ pictureOptions.allowsEditing = [[command argumentAtIndex:7 withDefault:@(NO)] boolValue];+ pictureOptions.correctOrientation = [[command argumentAtIndex:8 withDefault:@(NO)] boolValue];+ pictureOptions.saveToPhotoAlbum = [[command argumentAtIndex:9 withDefault:@(NO)] boolValue];+ pictureOptions.popoverOptions = [command argumentAtIndex:10 withDefault:nil];+ pictureOptions.cameraDirection = [[command argumentAtIndex:11 withDefault:@(UIImagePickerControllerCameraDeviceRear)] unsignedIntegerValue];++ pictureOptions.popoverSupported = NO;+ pictureOptions.usesGeolocation = NO;++ return pictureOptions;+}++@end+++@interface CDVCamera ()++@property (readwrite, assign) BOOL hasPendingOperation;++@end++@implementation CDVCamera+++ (void)initialize+{+ org_apache_cordova_validArrowDirections = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:UIPopoverArrowDirectionUp], [NSNumber numberWithInt:UIPopoverArrowDirectionDown], [NSNumber numberWithInt:UIPopoverArrowDirectionLeft], [NSNumber numberWithInt:UIPopoverArrowDirectionRight], [NSNumber numberWithInt:UIPopoverArrowDirectionAny], nil];+}++@synthesize hasPendingOperation, pickerController, locationManager;++- (NSURL*) urlTransformer:(NSURL*)url+{+ NSURL* urlToTransform = url;++ // for backwards compatibility - we check if this property is there+ SEL sel = NSSelectorFromString(@"urlTransformer");+ if ([self.commandDelegate respondsToSelector:sel]) {+ // grab the block from the commandDelegate+ NSURL* (^urlTransformer)(NSURL*) = ((id(*)(id, SEL))objc_msgSend)(self.commandDelegate, sel);+ // if block is not null, we call it+ if (urlTransformer) {+ urlToTransform = urlTransformer(url);+ }+ }++ return urlToTransform;+}++- (BOOL)usesGeolocation+{+ id useGeo = [self.commandDelegate.settings objectForKey:[@"CameraUsesGeolocation" lowercaseString]];+ return [(NSNumber*)useGeo boolValue];+}++- (BOOL)popoverSupported+{+ return (NSClassFromString(@"UIPopoverController") != nil) &&+ (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);+}++- (void)takePicture:(CDVInvokedUrlCommand*)command+{+ self.hasPendingOperation = YES;+ __weak CDVCamera* weakSelf = self;++ [self.commandDelegate runInBackground:^{+ CDVPictureOptions* pictureOptions = [CDVPictureOptions createFromTakePictureArguments:command];+ pictureOptions.popoverSupported = [weakSelf popoverSupported];+ pictureOptions.usesGeolocation = [weakSelf usesGeolocation];+ pictureOptions.cropToSize = NO;++ BOOL hasCamera = [UIImagePickerController isSourceTypeAvailable:pictureOptions.sourceType];+ if (!hasCamera) {+ NSLog(@"Camera.getPicture: source type %lu not available.", (unsigned long)pictureOptions.sourceType);+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No camera available"];+ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ return;+ }++ // Validate the app has permission to access the camera+ if (pictureOptions.sourceType == UIImagePickerControllerSourceTypeCamera) {+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted)+ {+ if(!granted)+ {+ // Denied; show an alert+ dispatch_async(dispatch_get_main_queue(), ^{+ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] message:NSLocalizedString(@"Access to the camera has been prohibited; please enable it in the Settings app to continue.", nil) preferredStyle:UIAlertControllerStyleAlert];+ [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {+ [weakSelf sendNoPermissionResult:command.callbackId];+ }]];+ [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Settings", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {+ [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];+ [weakSelf sendNoPermissionResult:command.callbackId];+ }]];+ [weakSelf.viewController presentViewController:alertController animated:YES completion:nil];+ });+ } else {+ [weakSelf showCameraPicker:command.callbackId withOptions:pictureOptions];+ }+ }];+ } else {+ [weakSelf showCameraPicker:command.callbackId withOptions:pictureOptions];+ }+ }];+}++- (void)showCameraPicker:(NSString*)callbackId withOptions:(CDVPictureOptions *) pictureOptions+{+ CDVCameraPicker* cameraPicker = [CDVCameraPicker createFromPictureOptions:pictureOptions];+ self.pickerController = cameraPicker;++ cameraPicker.delegate = self;+ cameraPicker.callbackId = callbackId;+ // we need to capture this state for memory warnings that dealloc this object+ cameraPicker.webView = self.webView;++ // Perform UI operations on the main thread+ dispatch_async(dispatch_get_main_queue(), ^{+ // If a popover is already open, close it; we only want one at a time.+ if (([[self pickerController] pickerPopoverController] != nil) && [[[self pickerController] pickerPopoverController] isPopoverVisible]) {+ [[[self pickerController] pickerPopoverController] dismissPopoverAnimated:YES];+ [[[self pickerController] pickerPopoverController] setDelegate:nil];+ [[self pickerController] setPickerPopoverController:nil];+ }++ if ([self popoverSupported] && (pictureOptions.sourceType != UIImagePickerControllerSourceTypeCamera)) {+ if (cameraPicker.pickerPopoverController == nil) {+ cameraPicker.pickerPopoverController = [[NSClassFromString(@"UIPopoverController") alloc] initWithContentViewController:cameraPicker];+ }+ [self displayPopover:pictureOptions.popoverOptions];+ self.hasPendingOperation = NO;+ } else {+ cameraPicker.modalPresentationStyle = UIModalPresentationCurrentContext;+ [self.viewController presentViewController:cameraPicker animated:YES completion:^{+ self.hasPendingOperation = NO;+ }];+ }+ });+}++- (void)sendNoPermissionResult:(NSString*)callbackId+{+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"has no access to camera"]; // error callback expects string ATM++ [self.commandDelegate sendPluginResult:result callbackId:callbackId];++ self.hasPendingOperation = NO;+ self.pickerController = nil;+}++- (void)repositionPopover:(CDVInvokedUrlCommand*)command+{+ if (([[self pickerController] pickerPopoverController] != nil) && [[[self pickerController] pickerPopoverController] isPopoverVisible]) {++ [[[self pickerController] pickerPopoverController] dismissPopoverAnimated:NO];++ NSDictionary* options = [command argumentAtIndex:0 withDefault:nil];+ [self displayPopover:options];+ }+}++- (NSInteger)integerValueForKey:(NSDictionary*)dict key:(NSString*)key defaultValue:(NSInteger)defaultValue+{+ NSInteger value = defaultValue;++ NSNumber* val = [dict valueForKey:key]; // value is an NSNumber++ if (val != nil) {+ value = [val integerValue];+ }+ return value;+}++- (void)displayPopover:(NSDictionary*)options+{+ NSInteger x = 0;+ NSInteger y = 32;+ NSInteger width = 320;+ NSInteger height = 480;+ UIPopoverArrowDirection arrowDirection = UIPopoverArrowDirectionAny;++ if (options) {+ x = [self integerValueForKey:options key:@"x" defaultValue:0];+ y = [self integerValueForKey:options key:@"y" defaultValue:32];+ width = [self integerValueForKey:options key:@"width" defaultValue:320];+ height = [self integerValueForKey:options key:@"height" defaultValue:480];+ arrowDirection = [self integerValueForKey:options key:@"arrowDir" defaultValue:UIPopoverArrowDirectionAny];+ if (![org_apache_cordova_validArrowDirections containsObject:[NSNumber numberWithUnsignedInteger:arrowDirection]]) {+ arrowDirection = UIPopoverArrowDirectionAny;+ }+ }++ [[[self pickerController] pickerPopoverController] setDelegate:self];+ [[[self pickerController] pickerPopoverController] presentPopoverFromRect:CGRectMake(x, y, width, height)+ inView:[self.webView superview]+ permittedArrowDirections:arrowDirection+ animated:YES];+}++- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated+{+ if([navigationController isKindOfClass:[UIImagePickerController class]]){++ // If popoverWidth and popoverHeight are specified and are greater than 0, then set popover size, else use apple's default popoverSize+ NSDictionary* options = self.pickerController.pictureOptions.popoverOptions;+ if(options) {+ NSInteger popoverWidth = [self integerValueForKey:options key:@"popoverWidth" defaultValue:0];+ NSInteger popoverHeight = [self integerValueForKey:options key:@"popoverHeight" defaultValue:0];+ if(popoverWidth > 0 && popoverHeight > 0)+ {+ [viewController setPreferredContentSize:CGSizeMake(popoverWidth,popoverHeight)];+ }+ }+++ UIImagePickerController* cameraPicker = (UIImagePickerController*)navigationController;++ if(![cameraPicker.mediaTypes containsObject:(NSString*)kUTTypeImage]){+ [viewController.navigationItem setTitle:NSLocalizedString(@"Videos", nil)];+ }+ }+}++- (void)cleanup:(CDVInvokedUrlCommand*)command+{+ // empty the tmp directory+ NSFileManager* fileMgr = [[NSFileManager alloc] init];+ NSError* err = nil;+ BOOL hasErrors = NO;++ // clear contents of NSTemporaryDirectory+ NSString* tempDirectoryPath = NSTemporaryDirectory();+ NSDirectoryEnumerator* directoryEnumerator = [fileMgr enumeratorAtPath:tempDirectoryPath];+ NSString* fileName = nil;+ BOOL result;++ while ((fileName = [directoryEnumerator nextObject])) {+ // only delete the files we created+ if (![fileName hasPrefix:CDV_PHOTO_PREFIX]) {+ continue;+ }+ NSString* filePath = [tempDirectoryPath stringByAppendingPathComponent:fileName];+ result = [fileMgr removeItemAtPath:filePath error:&err];+ if (!result && err) {+ NSLog(@"Failed to delete: %@ (error: %@)", filePath, err);+ hasErrors = YES;+ }+ }++ CDVPluginResult* pluginResult;+ if (hasErrors) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:@"One or more files failed to be deleted."];+ } else {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ }+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+}++- (void)popoverControllerDidDismissPopover:(id)popoverController+{+ UIPopoverController* pc = (UIPopoverController*)popoverController;++ [pc dismissPopoverAnimated:YES];+ pc.delegate = nil;+ if (self.pickerController && self.pickerController.callbackId && self.pickerController.pickerPopoverController) {+ self.pickerController.pickerPopoverController = nil;+ NSString* callbackId = self.pickerController.callbackId;+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"no image selected"]; // error callback expects string ATM+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];+ }+ self.hasPendingOperation = NO;+}++- (NSData*)processImage:(UIImage*)image info:(NSDictionary*)info options:(CDVPictureOptions*)options+{+ NSData* data = nil;++ switch (options.encodingType) {+ case EncodingTypePNG:+ data = UIImagePNGRepresentation(image);+ break;+ case EncodingTypeJPEG:+ {+ if ((options.allowsEditing == NO) && (options.targetSize.width <= 0) && (options.targetSize.height <= 0) && (options.correctOrientation == NO) && (([options.quality integerValue] == 100) || (options.sourceType != UIImagePickerControllerSourceTypeCamera))){+ // use image unedited as requested , don't resize+ data = UIImageJPEGRepresentation(image, 1.0);+ } else {+ data = UIImageJPEGRepresentation(image, [options.quality floatValue] / 100.0f);+ }++ if (options.usesGeolocation) {+ NSDictionary* controllerMetadata = [info objectForKey:@"UIImagePickerControllerMediaMetadata"];+ if (controllerMetadata) {+ self.data = data;+ self.metadata = [[NSMutableDictionary alloc] init];++ NSMutableDictionary* EXIFDictionary = [[controllerMetadata objectForKey:(NSString*)kCGImagePropertyExifDictionary]mutableCopy];+ if (EXIFDictionary) {+ [self.metadata setObject:EXIFDictionary forKey:(NSString*)kCGImagePropertyExifDictionary];+ }++ if (IsAtLeastiOSVersion(@"8.0")) {+ [[self locationManager] performSelector:NSSelectorFromString(@"requestWhenInUseAuthorization") withObject:nil afterDelay:0];+ }+ [[self locationManager] startUpdatingLocation];+ }+ }+ }+ break;+ default:+ break;+ };++ return data;+}++- (NSString*)tempFilePath:(NSString*)extension+{+ NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath];+ NSFileManager* fileMgr = [[NSFileManager alloc] init]; // recommended by Apple (vs [NSFileManager defaultManager]) to be threadsafe+ NSString* filePath;++ // generate unique file name+ int i = 1;+ do {+ filePath = [NSString stringWithFormat:@"%@/%@%03d.%@", docsPath, CDV_PHOTO_PREFIX, i++, extension];+ } while ([fileMgr fileExistsAtPath:filePath]);++ return filePath;+}++- (UIImage*)retrieveImage:(NSDictionary*)info options:(CDVPictureOptions*)options+{+ // get the image+ UIImage* image = nil;+ if (options.allowsEditing && [info objectForKey:UIImagePickerControllerEditedImage]) {+ image = [info objectForKey:UIImagePickerControllerEditedImage];+ } else {+ image = [info objectForKey:UIImagePickerControllerOriginalImage];+ }++ if (options.correctOrientation) {+ image = [image imageCorrectedForCaptureOrientation];+ }++ UIImage* scaledImage = nil;++ if ((options.targetSize.width > 0) && (options.targetSize.height > 0)) {+ // if cropToSize, resize image and crop to target size, otherwise resize to fit target without cropping+ if (options.cropToSize) {+ scaledImage = [image imageByScalingAndCroppingForSize:options.targetSize];+ } else {+ scaledImage = [image imageByScalingNotCroppingForSize:options.targetSize];+ }+ }++ return (scaledImage == nil ? image : scaledImage);+}++- (void)resultForImage:(CDVPictureOptions*)options info:(NSDictionary*)info completion:(void (^)(CDVPluginResult* res))completion+{+ CDVPluginResult* result = nil;+ BOOL saveToPhotoAlbum = options.saveToPhotoAlbum;+ UIImage* image = nil;++ switch (options.destinationType) {+ case DestinationTypeNativeUri:+ {+ NSURL* url = [info objectForKey:UIImagePickerControllerReferenceURL];+ saveToPhotoAlbum = NO;+ // If, for example, we use sourceType = Camera, URL might be nil because image is stored in memory.+ // In this case we must save image to device before obtaining an URI.+ if (url == nil) {+ image = [self retrieveImage:info options:options];+ ALAssetsLibrary* library = [ALAssetsLibrary new];+ [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)(image.imageOrientation) completionBlock:^(NSURL *assetURL, NSError *error) {+ CDVPluginResult* resultToReturn = nil;+ if (error) {+ resultToReturn = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]];+ } else {+ NSString* nativeUri = [[self urlTransformer:assetURL] absoluteString];+ resultToReturn = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:nativeUri];+ }+ completion(resultToReturn);+ }];+ return;+ } else {+ NSString* nativeUri = [[self urlTransformer:url] absoluteString];+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:nativeUri];+ }+ }+ break;+ case DestinationTypeFileUri:+ {+ image = [self retrieveImage:info options:options];+ NSData* data = [self processImage:image info:info options:options];+ if (data) {++ NSString* extension = options.encodingType == EncodingTypePNG? @"png" : @"jpg";+ NSString* filePath = [self tempFilePath:extension];+ NSError* err = nil;++ // save file+ if (![data writeToFile:filePath options:NSAtomicWrite error:&err]) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[err localizedDescription]];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[self urlTransformer:[NSURL fileURLWithPath:filePath]] absoluteString]];+ }+ }+ }+ break;+ case DestinationTypeDataUrl:+ {+ image = [self retrieveImage:info options:options];+ NSData* data = [self processImage:image info:info options:options];+ if (data) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:toBase64(data)];+ }+ }+ break;+ default:+ break;+ };++ if (saveToPhotoAlbum && image) {+ ALAssetsLibrary* library = [ALAssetsLibrary new];+ [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)(image.imageOrientation) completionBlock:nil];+ }++ completion(result);+}++- (CDVPluginResult*)resultForVideo:(NSDictionary*)info+{+ NSString* moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] absoluteString];+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:moviePath];+}++- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info+{+ __weak CDVCameraPicker* cameraPicker = (CDVCameraPicker*)picker;+ __weak CDVCamera* weakSelf = self;++ dispatch_block_t invoke = ^(void) {+ __block CDVPluginResult* result = nil;++ NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];+ if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {+ [weakSelf resultForImage:cameraPicker.pictureOptions info:info completion:^(CDVPluginResult* res) {+ if (![self usesGeolocation] || picker.sourceType != UIImagePickerControllerSourceTypeCamera) {+ [weakSelf.commandDelegate sendPluginResult:res callbackId:cameraPicker.callbackId];+ weakSelf.hasPendingOperation = NO;+ weakSelf.pickerController = nil;+ }+ }];+ }+ else {+ result = [weakSelf resultForVideo:info];+ [weakSelf.commandDelegate sendPluginResult:result callbackId:cameraPicker.callbackId];+ weakSelf.hasPendingOperation = NO;+ weakSelf.pickerController = nil;+ }+ };++ if (cameraPicker.pictureOptions.popoverSupported && (cameraPicker.pickerPopoverController != nil)) {+ [cameraPicker.pickerPopoverController dismissPopoverAnimated:YES];+ cameraPicker.pickerPopoverController.delegate = nil;+ cameraPicker.pickerPopoverController = nil;+ invoke();+ } else {+ [[cameraPicker presentingViewController] dismissViewControllerAnimated:YES completion:invoke];+ }+}++// older api calls newer didFinishPickingMediaWithInfo+- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo+{+ NSDictionary* imageInfo = [NSDictionary dictionaryWithObject:image forKey:UIImagePickerControllerOriginalImage];++ [self imagePickerController:picker didFinishPickingMediaWithInfo:imageInfo];+}++- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker+{+ __weak CDVCameraPicker* cameraPicker = (CDVCameraPicker*)picker;+ __weak CDVCamera* weakSelf = self;++ dispatch_block_t invoke = ^ (void) {+ CDVPluginResult* result;+ if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] != ALAuthorizationStatusAuthorized) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"has no access to camera"];+ } else if (picker.sourceType != UIImagePickerControllerSourceTypeCamera && ! IsAtLeastiOSVersion(@"11.0") && [ALAssetsLibrary authorizationStatus] != ALAuthorizationStatusAuthorized) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"has no access to assets"];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No Image Selected"];+ }+++ [weakSelf.commandDelegate sendPluginResult:result callbackId:cameraPicker.callbackId];++ weakSelf.hasPendingOperation = NO;+ weakSelf.pickerController = nil;+ };++ [[cameraPicker presentingViewController] dismissViewControllerAnimated:YES completion:invoke];+}++- (CLLocationManager*)locationManager+{+ if (locationManager != nil) {+ return locationManager;+ }++ locationManager = [[CLLocationManager alloc] init];+ [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];+ [locationManager setDelegate:self];++ return locationManager;+}++- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation+{+ if (locationManager == nil) {+ return;+ }++ [self.locationManager stopUpdatingLocation];+ self.locationManager = nil;++ NSMutableDictionary *GPSDictionary = [[NSMutableDictionary dictionary] init];++ CLLocationDegrees latitude = newLocation.coordinate.latitude;+ CLLocationDegrees longitude = newLocation.coordinate.longitude;++ // latitude+ if (latitude < 0.0) {+ latitude = latitude * -1.0f;+ [GPSDictionary setObject:@"S" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];+ } else {+ [GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];+ }+ [GPSDictionary setObject:[NSNumber numberWithFloat:latitude] forKey:(NSString*)kCGImagePropertyGPSLatitude];++ // longitude+ if (longitude < 0.0) {+ longitude = longitude * -1.0f;+ [GPSDictionary setObject:@"W" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];+ }+ else {+ [GPSDictionary setObject:@"E" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];+ }+ [GPSDictionary setObject:[NSNumber numberWithFloat:longitude] forKey:(NSString*)kCGImagePropertyGPSLongitude];++ // altitude+ CGFloat altitude = newLocation.altitude;+ if (!isnan(altitude)){+ if (altitude < 0) {+ altitude = -altitude;+ [GPSDictionary setObject:@"1" forKey:(NSString *)kCGImagePropertyGPSAltitudeRef];+ } else {+ [GPSDictionary setObject:@"0" forKey:(NSString *)kCGImagePropertyGPSAltitudeRef];+ }+ [GPSDictionary setObject:[NSNumber numberWithFloat:altitude] forKey:(NSString *)kCGImagePropertyGPSAltitude];+ }++ // Time and date+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];+ [formatter setDateFormat:@"HH:mm:ss.SSSSSS"];+ [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];+ [GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSTimeStamp];+ [formatter setDateFormat:@"yyyy:MM:dd"];+ [GPSDictionary setObject:[formatter stringFromDate:newLocation.timestamp] forKey:(NSString *)kCGImagePropertyGPSDateStamp];++ [self.metadata setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];+ [self imagePickerControllerReturnImageResult];+}++- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error+{+ if (locationManager == nil) {+ return;+ }++ [self.locationManager stopUpdatingLocation];+ self.locationManager = nil;++ [self imagePickerControllerReturnImageResult];+}++- (void)imagePickerControllerReturnImageResult+{+ CDVPictureOptions* options = self.pickerController.pictureOptions;+ CDVPluginResult* result = nil;++ if (self.metadata) {+ CGImageSourceRef sourceImage = CGImageSourceCreateWithData((__bridge CFDataRef)self.data, NULL);+ CFStringRef sourceType = CGImageSourceGetType(sourceImage);++ CGImageDestinationRef destinationImage = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)self.data, sourceType, 1, NULL);+ CGImageDestinationAddImageFromSource(destinationImage, sourceImage, 0, (__bridge CFDictionaryRef)self.metadata);+ CGImageDestinationFinalize(destinationImage);++ CFRelease(sourceImage);+ CFRelease(destinationImage);+ }++ switch (options.destinationType) {+ case DestinationTypeFileUri:+ {+ NSError* err = nil;+ NSString* extension = self.pickerController.pictureOptions.encodingType == EncodingTypePNG ? @"png":@"jpg";+ NSString* filePath = [self tempFilePath:extension];++ // save file+ if (![self.data writeToFile:filePath options:NSAtomicWrite error:&err]) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[err localizedDescription]];+ }+ else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[self urlTransformer:[NSURL fileURLWithPath:filePath]] absoluteString]];+ }+ }+ break;+ case DestinationTypeDataUrl:+ {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:toBase64(self.data)];+ }+ break;+ case DestinationTypeNativeUri:+ default:+ break;+ };++ if (result) {+ [self.commandDelegate sendPluginResult:result callbackId:self.pickerController.callbackId];+ }++ self.hasPendingOperation = NO;+ self.pickerController = nil;+ self.data = nil;+ self.metadata = nil;++ if (options.saveToPhotoAlbum) {+ ALAssetsLibrary *library = [ALAssetsLibrary new];+ [library writeImageDataToSavedPhotosAlbum:self.data metadata:self.metadata completionBlock:nil];+ }+}++@end++@implementation CDVCameraPicker++- (BOOL)prefersStatusBarHidden+{+ return YES;+}++- (UIViewController*)childViewControllerForStatusBarHidden+{+ return nil;+}++- (void)viewWillAppear:(BOOL)animated+{+ SEL sel = NSSelectorFromString(@"setNeedsStatusBarAppearanceUpdate");+ if ([self respondsToSelector:sel]) {+ [self performSelector:sel withObject:nil afterDelay:0];+ }++ [super viewWillAppear:animated];+}+++ (instancetype) createFromPictureOptions:(CDVPictureOptions*)pictureOptions;+{+ CDVCameraPicker* cameraPicker = [[CDVCameraPicker alloc] init];+ cameraPicker.pictureOptions = pictureOptions;+ cameraPicker.sourceType = pictureOptions.sourceType;+ cameraPicker.allowsEditing = pictureOptions.allowsEditing;++ if (cameraPicker.sourceType == UIImagePickerControllerSourceTypeCamera) {+ // We only allow taking pictures (no video) in this API.+ cameraPicker.mediaTypes = @[(NSString*)kUTTypeImage];+ // We can only set the camera device if we're actually using the camera.+ cameraPicker.cameraDevice = pictureOptions.cameraDirection;+ } else if (pictureOptions.mediaType == MediaTypeAll) {+ cameraPicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:cameraPicker.sourceType];+ } else {+ NSArray* mediaArray = @[(NSString*)(pictureOptions.mediaType == MediaTypeVideo ? kUTTypeMovie : kUTTypeImage)];+ cameraPicker.mediaTypes = mediaArray;+ }++ return cameraPicker;+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVExif.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVExif.hnew file mode 100644index 000000000..3e8adbd02--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVExif.h@@ -0,0 +1,43 @@+/*+ 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.+ */++#ifndef CordovaLib_ExifData_h+#define CordovaLib_ExifData_h++// exif data types+typedef enum exifDataTypes {+ EDT_UBYTE = 1, // 8 bit unsigned integer+ EDT_ASCII_STRING, // 8 bits containing 7 bit ASCII code, null terminated+ EDT_USHORT, // 16 bit unsigned integer+ EDT_ULONG, // 32 bit unsigned integer+ EDT_URATIONAL, // 2 longs, first is numerator and second is denominator+ EDT_SBYTE,+ EDT_UNDEFINED, // 8 bits+ EDT_SSHORT,+ EDT_SLONG, // 32bit signed integer (2's complement)+ EDT_SRATIONAL, // 2 SLONGS, first long is numerator, second is denominator+ EDT_SINGLEFLOAT,+ EDT_DOUBLEFLOAT+} ExifDataTypes;++// maps integer code for exif data types to width in bytes+static const int DataTypeToWidth[] = {1,1,2,4,8,1,1,2,4,8,4,8};++static const int RECURSE_HORIZON = 8;+#endifdiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVJpegHeaderWriter.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVJpegHeaderWriter.hnew file mode 100644index 000000000..3b43ef0b7--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVJpegHeaderWriter.h@@ -0,0 +1,62 @@+/*+ 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>++@interface CDVJpegHeaderWriter : NSObject {+ NSDictionary * SubIFDTagFormatDict;+ NSDictionary * IFD0TagFormatDict;+}++- (NSData*) spliceExifBlockIntoJpeg: (NSData*) jpegdata+ withExifBlock: (NSString*) exifstr;+- (NSString*) createExifAPP1 : (NSDictionary*) datadict;+- (NSString*) formattedHexStringFromDecimalNumber: (NSNumber*) numb+ withPlaces: (NSNumber*) width;+- (NSString*) formatNumberWithLeadingZeroes: (NSNumber*) numb+ withPlaces: (NSNumber*) places;+- (NSString*) decimalToUnsignedRational: (NSNumber*) numb+ withResultNumerator: (NSNumber**) numerator+ withResultDenominator: (NSNumber**) denominator;+- (void) continuedFraction: (double) val+ withFractionList: (NSMutableArray*) fractionlist+ withHorizon: (int) horizon;+//- (void) expandContinuedFraction: (NSArray*) fractionlist;+- (void) splitDouble: (double) val+ withIntComponent: (int*) rightside+ withFloatRemainder: (double*) leftside;+- (NSString*) formatRationalWithNumerator: (NSNumber*) numerator+ withDenominator: (NSNumber*) denominator+ asSigned: (Boolean) signedFlag;+- (NSString*) hexStringFromData : (NSData*) data;+- (NSNumber*) numericFromHexString : (NSString *) hexstring;++/*+- (void) readExifMetaData : (NSData*) imgdata;+- (void) spliceImageData : (NSData*) imgdata withExifData: (NSDictionary*) exifdata;+- (void) locateExifMetaData : (NSData*) imgdata;+- (NSString*) createExifAPP1 : (NSDictionary*) datadict;+- (void) createExifDataString : (NSDictionary*) datadict;+- (NSString*) createDataElement : (NSString*) element+ withElementData: (NSString*) data+ withExternalDataBlock: (NSDictionary*) memblock;+- (NSString*) hexStringFromData : (NSData*) data;+- (NSNumber*) numericFromHexString : (NSString *) hexstring;+*/+@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVJpegHeaderWriter.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVJpegHeaderWriter.mnew file mode 100644index 000000000..4d3ea2443--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/CDVJpegHeaderWriter.m@@ -0,0 +1,547 @@+/*+ 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 "CDVJpegHeaderWriter.h"+#include "CDVExif.h"++/* macros for tag info shorthand:+ tagno : tag number+ typecode : data type+ components : number of components+ appendString (TAGINF_W_APPEND only) : string to append to data+ Exif date data format include an extra 0x00 to the end of the data+ */+#define TAGINF(tagno, typecode, components) [NSArray arrayWithObjects: tagno, typecode, components, nil]+#define TAGINF_W_APPEND(tagno, typecode, components, appendString) [NSArray arrayWithObjects: tagno, typecode, components, appendString, nil]++const uint mJpegId = 0xffd8; // JPEG format marker+const uint mExifMarker = 0xffe1; // APP1 jpeg header marker+const uint mExif = 0x45786966; // ASCII 'Exif', first characters of valid exif header after size+const uint mMotorallaByteAlign = 0x4d4d; // 'MM', motorola byte align, msb first or 'sane'+const uint mIntelByteAlgin = 0x4949; // 'II', Intel byte align, lsb first or 'batshit crazy reverso world'+const uint mTiffLength = 0x2a; // after byte align bits, next to bits are 0x002a(MM) or 0x2a00(II), tiff version number+++@implementation CDVJpegHeaderWriter++- (id) init {+ self = [super init];+ // supported tags for exif IFD+ IFD0TagFormatDict = [[NSDictionary alloc] initWithObjectsAndKeys:+ // TAGINF(@"010e", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"ImageDescription",+ TAGINF_W_APPEND(@"0132", [NSNumber numberWithInt:EDT_ASCII_STRING], @20, @"00"), @"DateTime",+ TAGINF(@"010f", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"Make",+ TAGINF(@"0110", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"Model",+ TAGINF(@"0131", [NSNumber numberWithInt:EDT_ASCII_STRING], @0), @"Software",+ TAGINF(@"011a", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"XResolution",+ TAGINF(@"011b", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"YResolution",+ // currently supplied outside of Exif data block by UIImagePickerControllerMediaMetadata, this is set manually in CDVCamera.m+ /* TAGINF(@"0112", [NSNumber numberWithInt:EDT_USHORT], @1), @"Orientation",++ // rest of the tags are supported by exif spec, but are not specified by UIImagePickerControllerMediaMedadata+ // should camera hardware supply these values in future versions, or if they can be derived, ImageHeaderWriter will include them gracefully+ TAGINF(@"0128", [NSNumber numberWithInt:EDT_USHORT], @1), @"ResolutionUnit",+ TAGINF(@"013e", [NSNumber numberWithInt:EDT_URATIONAL], @2), @"WhitePoint",+ TAGINF(@"013f", [NSNumber numberWithInt:EDT_URATIONAL], @6), @"PrimaryChromaticities",+ TAGINF(@"0211", [NSNumber numberWithInt:EDT_URATIONAL], @3), @"YCbCrCoefficients",+ TAGINF(@"0213", [NSNumber numberWithInt:EDT_USHORT], @1), @"YCbCrPositioning",+ TAGINF(@"0214", [NSNumber numberWithInt:EDT_URATIONAL], @6), @"ReferenceBlackWhite",+ TAGINF(@"8298", [NSNumber numberWithInt:EDT_URATIONAL], @0), @"Copyright",++ // offset to exif subifd, we determine this dynamically based on the size of the main exif IFD+ TAGINF(@"8769", [NSNumber numberWithInt:EDT_ULONG], @1), @"ExifOffset",*/+ nil];+++ // supported tages for exif subIFD+ SubIFDTagFormatDict = [[NSDictionary alloc] initWithObjectsAndKeys:+ //TAGINF(@"9000", [NSNumber numberWithInt:], @), @"ExifVersion",+ //TAGINF(@"9202",[NSNumber numberWithInt:EDT_URATIONAL],@1), @"ApertureValue",+ //TAGINF(@"9203",[NSNumber numberWithInt:EDT_SRATIONAL],@1), @"BrightnessValue",+ TAGINF(@"a001",[NSNumber numberWithInt:EDT_USHORT],@1), @"ColorSpace",+ TAGINF_W_APPEND(@"9004",[NSNumber numberWithInt:EDT_ASCII_STRING],@20,@"00"), @"DateTimeDigitized",+ TAGINF_W_APPEND(@"9003",[NSNumber numberWithInt:EDT_ASCII_STRING],@20,@"00"), @"DateTimeOriginal",+ TAGINF(@"a402", [NSNumber numberWithInt:EDT_USHORT], @1), @"ExposureMode",+ TAGINF(@"8822", [NSNumber numberWithInt:EDT_USHORT], @1), @"ExposureProgram",+ //TAGINF(@"829a", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"ExposureTime",+ //TAGINF(@"829d", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"FNumber",+ TAGINF(@"9209", [NSNumber numberWithInt:EDT_USHORT], @1), @"Flash",+ // FocalLengthIn35mmFilm+ TAGINF(@"a405", [NSNumber numberWithInt:EDT_USHORT], @1), @"FocalLenIn35mmFilm",+ //TAGINF(@"920a", [NSNumber numberWithInt:EDT_URATIONAL], @1), @"FocalLength",+ //TAGINF(@"8827", [NSNumber numberWithInt:EDT_USHORT], @2), @"ISOSpeedRatings",+ TAGINF(@"9207", [NSNumber numberWithInt:EDT_USHORT],@1), @"MeteringMode",+ // specific to compressed data+ TAGINF(@"a002", [NSNumber numberWithInt:EDT_ULONG],@1), @"PixelXDimension",+ TAGINF(@"a003", [NSNumber numberWithInt:EDT_ULONG],@1), @"PixelYDimension",+ // data type undefined, but this is a DSC camera, so value is always 1, treat as ushort+ TAGINF(@"a301", [NSNumber numberWithInt:EDT_USHORT],@1), @"SceneType",+ TAGINF(@"a217",[NSNumber numberWithInt:EDT_USHORT],@1), @"SensingMethod",+ //TAGINF(@"9201", [NSNumber numberWithInt:EDT_SRATIONAL], @1), @"ShutterSpeedValue",+ // specifies location of main subject in scene (x,y,wdith,height) expressed before rotation processing+ //TAGINF(@"9214", [NSNumber numberWithInt:EDT_USHORT], @4), @"SubjectArea",+ TAGINF(@"a403", [NSNumber numberWithInt:EDT_USHORT], @1), @"WhiteBalance",+ nil];+ return self;+}++- (NSData*) spliceExifBlockIntoJpeg: (NSData*) jpegdata withExifBlock: (NSString*) exifstr {++ CDVJpegHeaderWriter * exifWriter = [[CDVJpegHeaderWriter alloc] init];++ NSMutableData * exifdata = [NSMutableData dataWithCapacity: [exifstr length]/2];+ int idx;+ for (idx = 0; idx+1 < [exifstr length]; idx+=2) {+ NSRange range = NSMakeRange(idx, 2);+ NSString* hexStr = [exifstr substringWithRange:range];+ NSScanner* scanner = [NSScanner scannerWithString:hexStr];+ unsigned int intValue;+ [scanner scanHexInt:&intValue];+ [exifdata appendBytes:&intValue length:1];+ }++ NSMutableData * ddata = [NSMutableData dataWithCapacity: [jpegdata length]];+ NSMakeRange(0,4);+ int loc = 0;+ bool done = false;+ // read the jpeg data until we encounter the app1==0xFFE1 marker+ while (loc+1 < [jpegdata length]) {+ NSData * blag = [jpegdata subdataWithRange: NSMakeRange(loc,2)];+ if( [[blag description] isEqualToString : @"<ffe1>"]) {+ // read the APP1 block size bits+ NSString * the = [exifWriter hexStringFromData:[jpegdata subdataWithRange: NSMakeRange(loc+2,2)]];+ NSNumber * app1width = [exifWriter numericFromHexString:the];+ //consume the original app1 block+ [ddata appendData:exifdata];+ // advance our loc marker past app1+ loc += [app1width intValue] + 2;+ done = true;+ } else {+ if(!done) {+ [ddata appendData:blag];+ loc += 2;+ } else {+ break;+ }+ }+ }+ // copy the remaining data+ [ddata appendData:[jpegdata subdataWithRange: NSMakeRange(loc,[jpegdata length]-loc)]];+ return ddata;+}++++/**+ * Create the Exif data block as a hex string+ * jpeg uses Application Markers (APP's) as markers for application data+ * APP1 is the application marker reserved for exif data+ *+ * (NSDictionary*) datadict - with subdictionaries marked '{TIFF}' and '{EXIF}' as returned by imagePickerController with a valid+ * didFinishPickingMediaWithInfo data dict, under key @"UIImagePickerControllerMediaMetadata"+ *+ * the following constructs a hex string to Exif specifications, and is therefore brittle+ * altering the order of arguments to the string constructors, modifying field sizes or formats,+ * and any other minor change will likely prevent the exif data from being read+ */+- (NSString*) createExifAPP1 : (NSDictionary*) datadict {+ NSMutableString * app1; // holds finalized product+ NSString * exifIFD; // exif information file directory+ NSString * subExifIFD; // subexif information file directory++ // FFE1 is the hex APP1 marker code, and will allow client apps to read the data+ NSString * app1marker = @"ffe1";+ // SSSS size, to be determined+ // EXIF ascii characters followed by 2bytes of zeros+ NSString * exifmarker = @"457869660000";+ // Tiff header: 4d4d is motorolla byte align (big endian), 002a is hex for 42+ NSString * tiffheader = @"4d4d002a";+ //first IFD offset from the Tiff header to IFD0. Since we are writing it, we know it's address 0x08+ NSString * ifd0offset = @"00000008";+ // current offset to next data area+ int currentDataOffset = 0;++ //data labeled as TIFF in UIImagePickerControllerMediaMetaData is part of the EXIF IFD0 portion of APP1+ exifIFD = [self createExifIFDFromDict: [datadict objectForKey:@"{TIFF}"] withFormatDict: IFD0TagFormatDict isIFD0:YES currentDataOffset:¤tDataOffset];++ //data labeled as EXIF in UIImagePickerControllerMediaMetaData is part of the EXIF Sub IFD portion of APP1+ subExifIFD = [self createExifIFDFromDict: [datadict objectForKey:@"{Exif}"] withFormatDict: SubIFDTagFormatDict isIFD0:NO currentDataOffset:¤tDataOffset];+ /*+ NSLog(@"SUB EXIF IFD %@ WITH SIZE: %d",exifIFD,[exifIFD length]);++ NSLog(@"SUB EXIF IFD %@ WITH SIZE: %d",subExifIFD,[subExifIFD length]);+ */+ // construct the complete app1 data block+ app1 = [[NSMutableString alloc] initWithFormat: @"%@%04x%@%@%@%@%@",+ app1marker,+ (unsigned int)(16 + ([exifIFD length]/2) + ([subExifIFD length]/2)) /*16+[exifIFD length]/2*/,+ exifmarker,+ tiffheader,+ ifd0offset,+ exifIFD,+ subExifIFD];++ return app1;+}++// returns hex string representing a valid exif information file directory constructed from the datadict and formatdict+- (NSString*) createExifIFDFromDict : (NSDictionary*) datadict+ withFormatDict : (NSDictionary*) formatdict+ isIFD0 : (BOOL) ifd0flag+ currentDataOffset : (int*) dataoffset {+ NSArray * datakeys = [datadict allKeys]; // all known data keys+ NSArray * knownkeys = [formatdict allKeys]; // only keys in knowkeys are considered for entry in this IFD+ NSMutableArray * ifdblock = [[NSMutableArray alloc] initWithCapacity: [datadict count]]; // all ifd entries+ NSMutableArray * ifddatablock = [[NSMutableArray alloc] initWithCapacity: [datadict count]]; // data block entries+ // ifd0flag = NO; // ifd0 requires a special flag and has offset to next ifd appended to end++ // iterate through known provided data keys+ for (int i = 0; i < [datakeys count]; i++) {+ NSString * key = [datakeys objectAtIndex:i];+ // don't muck about with unknown keys+ if ([knownkeys indexOfObject: key] != NSNotFound) {+ // create new IFD entry+ NSString * entry = [self createIFDElement: key+ withFormat: [formatdict objectForKey:key]+ withElementData: [datadict objectForKey:key]];+ // create the IFD entry's data block+ NSString * data = [self createIFDElementDataWithFormat: [formatdict objectForKey:key]+ withData: [datadict objectForKey:key]];+ if (entry) {+ [ifdblock addObject:entry];+ if(!data) {+ [ifdblock addObject:@""];+ } else {+ [ifddatablock addObject:data];+ }+ }+ }+ }++ NSMutableString * exifstr = [[NSMutableString alloc] initWithCapacity: [ifdblock count] * 24];+ NSMutableString * dbstr = [[NSMutableString alloc] initWithCapacity: 100];++ int addr=*dataoffset; // current offset/address in datablock+ if (ifd0flag) {+ // calculate offset to datablock based on ifd file entry count+ addr += 14+(12*([ifddatablock count]+1)); // +1 for tag 0x8769, exifsubifd offset+ } else {+ // current offset + numSubIFDs (2-bytes) + 12*numSubIFDs + endMarker (4-bytes)+ addr += 2+(12*[ifddatablock count])+4;+ }++ for (int i = 0; i < [ifdblock count]; i++) {+ NSString * entry = [ifdblock objectAtIndex:i];+ NSString * data = [ifddatablock objectAtIndex:i];++ // check if the data fits into 4 bytes+ if( [data length] <= 8) {+ // concatenate the entry and the (4byte) data entry into the final IFD entry and append to exif ifd string+ [exifstr appendFormat : @"%@%@", entry, data];+ } else {+ [exifstr appendFormat : @"%@%08x", entry, addr];+ [dbstr appendFormat: @"%@", data];+ addr+= [data length] / 2;+ /*+ NSLog(@"=====data-length[%i]=======",[data length]);+ NSLog(@"addr-offset[%i]",addr);+ NSLog(@"entry[%@]",entry);+ NSLog(@"data[%@]",data);+ */+ }+ }++ // calculate IFD0 terminal offset tags, currently ExifSubIFD+ unsigned int entrycount = (unsigned int)[ifdblock count];+ if (ifd0flag) {+ // 18 accounts for 8769's width + offset to next ifd, 8 accounts for start of header+ NSNumber * offset = [NSNumber numberWithUnsignedInteger:[exifstr length] / 2 + [dbstr length] / 2 + 18+8];++ [self appendExifOffsetTagTo: exifstr+ withOffset : offset];+ entrycount++;+ }+ *dataoffset = addr;+ return [[NSString alloc] initWithFormat: @"%04x%@%@%@",+ entrycount,+ exifstr,+ @"00000000", // offset to next IFD, 0 since there is none+ dbstr]; // lastly, the datablock+}++// Creates an exif formatted exif information file directory entry+- (NSString*) createIFDElement: (NSString*) elementName withFormat: (NSArray*) formtemplate withElementData: (NSString*) data {+ //NSArray * fielddata = [formatdict objectForKey: elementName];// format data of desired field+ if (formtemplate) {+ // format string @"%@%@%@%@", tag number, data format, components, value+ NSNumber * dataformat = [formtemplate objectAtIndex:1];+ NSNumber * components = [formtemplate objectAtIndex:2];+ if([components intValue] == 0) {+ components = [NSNumber numberWithUnsignedInteger:[data length] * DataTypeToWidth[[dataformat intValue]-1]];+ }++ return [[NSString alloc] initWithFormat: @"%@%@%08x",+ [formtemplate objectAtIndex:0], // the field code+ [self formatNumberWithLeadingZeroes: dataformat withPlaces: @4], // the data type code+ [components intValue]]; // number of components+ }+ return NULL;+}++/**+ * appends exif IFD0 tag 8769 "ExifOffset" to the string provided+ * (NSMutableString*) str - string you wish to append the 8769 tag to: APP1 or IFD0 hex data string+ * // TAGINF(@"8769", [NSNumber numberWithInt:EDT_ULONG], @1), @"ExifOffset",+ */+- (void) appendExifOffsetTagTo: (NSMutableString*) str withOffset : (NSNumber*) offset {+ NSArray * format = TAGINF(@"8769", [NSNumber numberWithInt:EDT_ULONG], @1);++ NSString * entry = [self createIFDElement: @"ExifOffset"+ withFormat: format+ withElementData: [offset stringValue]];++ NSString * data = [self createIFDElementDataWithFormat: format+ withData: [offset stringValue]];+ [str appendFormat:@"%@%@", entry, data];+}++// formats the Information File Directory Data to exif format+- (NSString*) createIFDElementDataWithFormat: (NSArray*) dataformat withData: (NSString*) data {+ NSMutableString * datastr = nil;+ NSNumber * tmp = nil;+ NSNumber * formatcode = [dataformat objectAtIndex:1];+ NSUInteger formatItemsCount = [dataformat count];+ NSNumber * num = @0;+ NSNumber * denom = @0;++ switch ([formatcode intValue]) {+ case EDT_UBYTE:+ break;+ case EDT_ASCII_STRING:+ datastr = [[NSMutableString alloc] init];+ for (int i = 0; i < [data length]; i++) {+ [datastr appendFormat:@"%02x",[data characterAtIndex:i]];+ }+ if (formatItemsCount > 3) {+ // We have additional data to append.+ // currently used by Date format to append final 0x00 but can be used by other data types as well in the future+ [datastr appendString:[dataformat objectAtIndex:3]];+ }+ if ([datastr length] < 8) {+ NSString * format = [NSString stringWithFormat:@"%%0%dd", (int)(8 - [datastr length])];+ [datastr appendFormat:format,0];+ }+ return datastr;+ case EDT_USHORT:+ return [[NSString alloc] initWithFormat : @"%@%@",+ [self formattedHexStringFromDecimalNumber: [NSNumber numberWithInt: [data intValue]] withPlaces: @4],+ @"0000"];+ case EDT_ULONG:+ tmp = [NSNumber numberWithUnsignedLong:[data intValue]];+ return [NSString stringWithFormat : @"%@",+ [self formattedHexStringFromDecimalNumber: tmp withPlaces: @8]];+ case EDT_URATIONAL:+ return [self decimalToUnsignedRational: [NSNumber numberWithDouble:[data doubleValue]]+ withResultNumerator: &num+ withResultDenominator: &denom];+ case EDT_SBYTE:++ break;+ case EDT_UNDEFINED:+ break; // 8 bits+ case EDT_SSHORT:+ break;+ case EDT_SLONG:+ break; // 32bit signed integer (2's complement)+ case EDT_SRATIONAL:+ break; // 2 SLONGS, first long is numerator, second is denominator+ case EDT_SINGLEFLOAT:+ break;+ case EDT_DOUBLEFLOAT:+ break;+ }+ return datastr;+}++//======================================================================================================================+// Utility Methods+//======================================================================================================================++// creates a formatted little endian hex string from a number and width specifier+- (NSString*) formattedHexStringFromDecimalNumber: (NSNumber*) numb withPlaces: (NSNumber*) width {+ NSMutableString * str = [[NSMutableString alloc] initWithCapacity:[width intValue]];+ NSString * formatstr = [[NSString alloc] initWithFormat: @"%%%@%dx", @"0", [width intValue]];+ [str appendFormat:formatstr, [numb intValue]];+ return str;+}++// format number as string with leading 0's+- (NSString*) formatNumberWithLeadingZeroes: (NSNumber *) numb withPlaces: (NSNumber *) places {+ NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];+ NSString *formatstr = [@"" stringByPaddingToLength:[places unsignedIntegerValue] withString:@"0" startingAtIndex:0];+ [formatter setPositiveFormat:formatstr];+ return [formatter stringFromNumber:numb];+}++// approximate a decimal with a rational by method of continued fraction+// can be collasped into decimalToUnsignedRational after testing+- (void) decimalToRational: (NSNumber *) numb+ withResultNumerator: (NSNumber**) numerator+ withResultDenominator: (NSNumber**) denominator {+ NSMutableArray * fractionlist = [[NSMutableArray alloc] initWithCapacity:8];++ [self continuedFraction: [numb doubleValue]+ withFractionList: fractionlist+ withHorizon: 8];++ // simplify complex fraction represented by partial fraction list+ [self expandContinuedFraction: fractionlist+ withResultNumerator: numerator+ withResultDenominator: denominator];++}++// approximate a decimal with an unsigned rational by method of continued fraction+- (NSString*) decimalToUnsignedRational: (NSNumber *) numb+ withResultNumerator: (NSNumber**) numerator+ withResultDenominator: (NSNumber**) denominator {+ NSMutableArray * fractionlist = [[NSMutableArray alloc] initWithCapacity:8];++ // generate partial fraction list+ [self continuedFraction: [numb doubleValue]+ withFractionList: fractionlist+ withHorizon: 8];++ // simplify complex fraction represented by partial fraction list+ [self expandContinuedFraction: fractionlist+ withResultNumerator: numerator+ withResultDenominator: denominator];++ return [self formatFractionList: fractionlist];+}++// recursive implementation of decimal approximation by continued fraction+- (void) continuedFraction: (double) val+ withFractionList: (NSMutableArray*) fractionlist+ withHorizon: (int) horizon {+ int whole;+ double remainder;+ // 1. split term+ [self splitDouble: val withIntComponent: &whole withFloatRemainder: &remainder];+ [fractionlist addObject: [NSNumber numberWithInt:whole]];++ // 2. calculate reciprocal of remainder+ if (!remainder) return; // early exit, exact fraction found, avoids recip/0+ double recip = 1 / remainder;++ // 3. exit condition+ if ([fractionlist count] > horizon) {+ return;+ }++ // 4. recurse+ [self continuedFraction:recip withFractionList: fractionlist withHorizon: horizon];++}++// expand continued fraction list, creating a single level rational approximation+-(void) expandContinuedFraction: (NSArray*) fractionlist+ withResultNumerator: (NSNumber**) numerator+ withResultDenominator: (NSNumber**) denominator {+ NSUInteger i = 0;+ int den = 0;+ int num = 0;+ if ([fractionlist count] == 1) {+ *numerator = [NSNumber numberWithInt:[[fractionlist objectAtIndex:0] intValue]];+ *denominator = @1;+ return;+ }++ //begin at the end of the list+ i = [fractionlist count] - 1;+ num = 1;+ den = [[fractionlist objectAtIndex:i] intValue];++ while (i > 0) {+ int t = [[fractionlist objectAtIndex: i-1] intValue];+ num = t * den + num;+ if (i==1) {+ break;+ } else {+ t = num;+ num = den;+ den = t;+ }+ i--;+ }+ // set result parameters values+ *numerator = [NSNumber numberWithInt: num];+ *denominator = [NSNumber numberWithInt: den];+}++// formats expanded fraction list to string matching exif specification+- (NSString*) formatFractionList: (NSArray *) fractionlist {+ NSMutableString * str = [[NSMutableString alloc] initWithCapacity:16];++ if ([fractionlist count] == 1){+ [str appendFormat: @"%08x00000001", [[fractionlist objectAtIndex:0] intValue]];+ }+ return str;+}++// format rational as+- (NSString*) formatRationalWithNumerator: (NSNumber*) numerator withDenominator: (NSNumber*) denominator asSigned: (Boolean) signedFlag {+ NSMutableString * str = [[NSMutableString alloc] initWithCapacity:16];+ if (signedFlag) {+ long num = [numerator longValue];+ long den = [denominator longValue];+ [str appendFormat: @"%08lx%08lx", num >= 0 ? num : ~ABS(num) + 1, num >= 0 ? den : ~ABS(den) + 1];+ } else {+ [str appendFormat: @"%08lx%08lx", [numerator unsignedLongValue], [denominator unsignedLongValue]];+ }+ return str;+}++// split a floating point number into two integer values representing the left and right side of the decimal+- (void) splitDouble: (double) val withIntComponent: (int*) rightside withFloatRemainder: (double*) leftside {+ *rightside = val; // convert numb to int representation, which truncates the decimal portion+ *leftside = val - *rightside;+}+++//+- (NSString*) hexStringFromData : (NSData*) data {+ //overflow detection+ const unsigned char *dataBuffer = [data bytes];+ return [[NSString alloc] initWithFormat: @"%02x%02x",+ (unsigned char)dataBuffer[0],+ (unsigned char)dataBuffer[1]];+}++// convert a hex string to a number+- (NSNumber*) numericFromHexString : (NSString *) hexstring {+ NSScanner * scan = NULL;+ unsigned int numbuf= 0;++ scan = [NSScanner scannerWithString:hexstring];+ [scan scanHexInt:&numbuf];+ return [NSNumber numberWithInt:numbuf];+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/UIImage+CropScaleOrientation.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/UIImage+CropScaleOrientation.hnew file mode 100644index 000000000..31bc42ff0--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/UIImage+CropScaleOrientation.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 <UIKit/UIKit.h>++@interface UIImage (CropScaleOrientation)++- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;+- (UIImage*)imageCorrectedForCaptureOrientation;+- (UIImage*)imageCorrectedForCaptureOrientation:(UIImageOrientation)imageOrientation;+- (UIImage*)imageByScalingNotCroppingForSize:(CGSize)targetSize;++@end\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/UIImage+CropScaleOrientation.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/UIImage+CropScaleOrientation.mnew file mode 100644index 000000000..a66a5d88d--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-camera/UIImage+CropScaleOrientation.m@@ -0,0 +1,175 @@+/*+ 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 "UIImage+CropScaleOrientation.h"++@implementation UIImage (CropScaleOrientation)++- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize+{+ UIImage* sourceImage = self;+ UIImage* newImage = nil;+ CGSize imageSize = sourceImage.size;+ CGFloat width = imageSize.width;+ CGFloat height = imageSize.height;+ CGFloat targetWidth = targetSize.width;+ CGFloat targetHeight = targetSize.height;+ CGFloat scaleFactor = 0.0;+ CGFloat scaledWidth = targetWidth;+ CGFloat scaledHeight = targetHeight;+ CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);++ if (CGSizeEqualToSize(imageSize, targetSize) == NO) {+ CGFloat widthFactor = targetWidth / width;+ CGFloat heightFactor = targetHeight / height;++ if (widthFactor > heightFactor) {+ scaleFactor = widthFactor; // scale to fit height+ } else {+ scaleFactor = heightFactor; // scale to fit width+ }+ scaledWidth = width * scaleFactor;+ scaledHeight = height * scaleFactor;++ // center the image+ if (widthFactor > heightFactor) {+ thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;+ } else if (widthFactor < heightFactor) {+ thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;+ }+ }++ UIGraphicsBeginImageContext(targetSize); // this will crop++ CGRect thumbnailRect = CGRectZero;+ thumbnailRect.origin = thumbnailPoint;+ thumbnailRect.size.width = scaledWidth;+ thumbnailRect.size.height = scaledHeight;++ [sourceImage drawInRect:thumbnailRect];++ newImage = UIGraphicsGetImageFromCurrentImageContext();+ if (newImage == nil) {+ NSLog(@"could not scale image");+ }++ // pop the context to get back to the default+ UIGraphicsEndImageContext();+ return newImage;+}++- (UIImage*)imageCorrectedForCaptureOrientation:(UIImageOrientation)imageOrientation+{+ float rotation_radians = 0;+ bool perpendicular = false;++ switch (imageOrientation) {+ case UIImageOrientationUp :+ rotation_radians = 0.0;+ break;++ case UIImageOrientationDown:+ rotation_radians = M_PI; // don't be scared of radians, if you're reading this, you're good at math+ break;++ case UIImageOrientationRight:+ rotation_radians = M_PI_2;+ perpendicular = true;+ break;++ case UIImageOrientationLeft:+ rotation_radians = -M_PI_2;+ perpendicular = true;+ break;++ default:+ break;+ }++ UIGraphicsBeginImageContext(CGSizeMake(self.size.width, self.size.height));+ CGContextRef context = UIGraphicsGetCurrentContext();++ // Rotate around the center point+ CGContextTranslateCTM(context, self.size.width / 2, self.size.height / 2);+ CGContextRotateCTM(context, rotation_radians);++ CGContextScaleCTM(context, 1.0, -1.0);+ float width = perpendicular ? self.size.height : self.size.width;+ float height = perpendicular ? self.size.width : self.size.height;+ CGContextDrawImage(context, CGRectMake(-width / 2, -height / 2, width, height), [self CGImage]);++ // Move the origin back since the rotation might've change it (if its 90 degrees)+ if (perpendicular) {+ CGContextTranslateCTM(context, -self.size.height / 2, -self.size.width / 2);+ }++ UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();+ UIGraphicsEndImageContext();+ return newImage;+}++- (UIImage*)imageCorrectedForCaptureOrientation+{+ return [self imageCorrectedForCaptureOrientation:[self imageOrientation]];+}++- (UIImage*)imageByScalingNotCroppingForSize:(CGSize)targetSize+{+ UIImage* sourceImage = self;+ UIImage* newImage = nil;+ CGSize imageSize = sourceImage.size;+ CGFloat width = imageSize.width;+ CGFloat height = imageSize.height;+ CGFloat targetWidth = targetSize.width;+ CGFloat targetHeight = targetSize.height;+ CGFloat scaleFactor = 0.0;+ CGSize scaledSize = targetSize;++ if (CGSizeEqualToSize(imageSize, targetSize) == NO) {+ CGFloat widthFactor = targetWidth / width;+ CGFloat heightFactor = targetHeight / height;++ // opposite comparison to imageByScalingAndCroppingForSize in order to contain the image within the given bounds+ if (widthFactor > heightFactor) {+ scaleFactor = heightFactor; // scale to fit height+ } else {+ scaleFactor = widthFactor; // scale to fit width+ }+ scaledSize = CGSizeMake(MIN(width * scaleFactor, targetWidth), MIN(height * scaleFactor, targetHeight));+ }++ // If the pixels are floats, it causes a white line in iOS8 and probably other versions too+ scaledSize.width = (int)scaledSize.width;+ scaledSize.height = (int)scaledSize.height;++ UIGraphicsBeginImageContext(scaledSize); // this will resize++ [sourceImage drawInRect:CGRectMake(0, 0, scaledSize.width, scaledSize.height)];++ newImage = UIGraphicsGetImageFromCurrentImageContext();+ if (newImage == nil) {+ NSLog(@"could not scale image");+ }++ // pop the context to get back to the default+ UIGraphicsEndImageContext();+ return newImage;+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-device/CDVDevice.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-device/CDVDevice.hnew file mode 100644index 000000000..a146d8829--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-device/CDVDevice.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.+ */++#import <UIKit/UIKit.h>+#import <Cordova/CDVPlugin.h>++@interface CDVDevice : CDVPlugin+{}+++ (NSString*)cordovaVersion;++- (void)getDeviceInfo:(CDVInvokedUrlCommand*)command;++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-device/CDVDevice.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-device/CDVDevice.mnew file mode 100644index 000000000..de535332f--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-device/CDVDevice.m@@ -0,0 +1,115 @@+/*+ 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 <sys/types.h>+#include <sys/sysctl.h>+#include "TargetConditionals.h"++#import <Cordova/CDV.h>+#import "CDVDevice.h"++@implementation UIDevice (ModelVersion)++- (NSString*)modelVersion+{+#if TARGET_IPHONE_SIMULATOR+ NSString* platform = NSProcessInfo.processInfo.environment[@"SIMULATOR_MODEL_IDENTIFIER"];+#else+ size_t size;++ sysctlbyname("hw.machine", NULL, &size, NULL, 0);+ char* machine = malloc(size);+ sysctlbyname("hw.machine", machine, &size, NULL, 0);+ NSString* platform = [NSString stringWithUTF8String:machine];+ free(machine);+#endif+ return platform;+}++@end++@interface CDVDevice () {}+@end++@implementation CDVDevice++- (NSString*)uniqueAppInstanceIdentifier:(UIDevice*)device+{+ NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];+ static NSString* UUID_KEY = @"CDVUUID";++ // Check user defaults first to maintain backwards compaitibility with previous versions+ // which didn't user identifierForVendor+ NSString* app_uuid = [userDefaults stringForKey:UUID_KEY];+ if (app_uuid == nil) {+ if ([device respondsToSelector:@selector(identifierForVendor)]) {+ app_uuid = [[device identifierForVendor] UUIDString];+ } else {+ CFUUIDRef uuid = CFUUIDCreate(NULL);+ app_uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid);+ CFRelease(uuid);+ }++ [userDefaults setObject:app_uuid forKey:UUID_KEY];+ [userDefaults synchronize];+ }++ return app_uuid;+}++- (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+{+ UIDevice* device = [UIDevice currentDevice];++ return @{+ @"manufacturer": @"Apple",+ @"model": [device modelVersion],+ @"platform": @"iOS",+ @"version": [device systemVersion],+ @"uuid": [self uniqueAppInstanceIdentifier:device],+ @"cordova": [[self class] cordovaVersion],+ @"isVirtual": @([self isVirtual])+ };+}+++ (NSString*)cordovaVersion+{+ return CDV_VERSION;+}++- (BOOL)isVirtual+{+ #if TARGET_OS_SIMULATOR+ return true;+ #elif TARGET_IPHONE_SIMULATOR+ return true;+ #else+ return false;+ #endif+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file-opener2/FileOpener2.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file-opener2/FileOpener2.hnew file mode 100644index 000000000..f3014d07c--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file-opener2/FileOpener2.h@@ -0,0 +1,35 @@+/*+The MIT License (MIT)++Copyright (c) 2013 pwlin - [email protected]++Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+*/++#import <Cordova/CDV.h>++@interface FileOpener2 : CDVPlugin <UIDocumentInteractionControllerDelegate> {+ NSString *localFile;+}++@property(nonatomic, strong) UIDocumentInteractionController *controller;+@property(nonatomic, strong) CDVViewController *cdvViewController;++- (void) open: (CDVInvokedUrlCommand*)command;++@end\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file-opener2/FileOpener2.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file-opener2/FileOpener2.mnew file mode 100644index 000000000..716170543--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file-opener2/FileOpener2.m@@ -0,0 +1,137 @@+/*+The MIT License (MIT)++Copyright (c) 2013 pwlin - [email protected]++Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+*/+#import "FileOpener2.h"+#import <Cordova/CDV.h>++#import <QuartzCore/QuartzCore.h>+#import <MobileCoreServices/MobileCoreServices.h>++@implementation FileOpener2+@synthesize controller = docController;++- (void) open: (CDVInvokedUrlCommand*)command {++ NSString *path = [command.arguments objectAtIndex:0];+ NSString *contentType = [command.arguments objectAtIndex:1];+ BOOL showPreview = YES;++ if ([command.arguments count] >= 3) {+ showPreview = [[command.arguments objectAtIndex:2] boolValue];+ }++ CDVViewController* cont = (CDVViewController*)[super viewController];+ self.cdvViewController = cont;+ NSString *uti = nil;++ if([contentType length] == 0){+ NSArray *dotParts = [path componentsSeparatedByString:@"."];+ NSString *fileExt = [dotParts lastObject];++ uti = (__bridge NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExt, NULL);+ } else {+ uti = (__bridge NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)contentType, NULL);+ }++ dispatch_async(dispatch_get_main_queue(), ^{+ NSURL *fileURL = NULL;+ NSString *decodedPath = [path stringByRemovingPercentEncoding];+ if ([path isEqualToString:decodedPath]) {+ NSLog(@"Path parameter not encoded. Building file URL encoding it...");+ fileURL = [NSURL fileURLWithPath:[path stringByReplacingOccurrencesOfString:@"file://" withString:@""]];;+ } else {+ NSLog(@"Path parameter already encoded. Building file URL without encoding it...");+ fileURL = [NSURL URLWithString:path];+ }++ localFile = fileURL.path;++ NSLog(@"looking for file at %@", fileURL);+ NSFileManager *fm = [NSFileManager defaultManager];+ if(![fm fileExistsAtPath:localFile]) {+ NSDictionary *jsonObj = @{@"status" : @"9",+ @"message" : @"File does not exist"};+ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:jsonObj];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ return;+ }++ docController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];+ docController.delegate = self;+ docController.UTI = uti;++ CDVPluginResult* pluginResult = nil;++ //Opens the file preview+ CGRect rect;+ if ([command.arguments count] >= 4) {+ NSArray *positionValues = [command.arguments objectAtIndex:3];++ if (![positionValues isEqual:[NSNull null]] && [positionValues count] >= 2) {+ rect = CGRectMake(0, 0, [[positionValues objectAtIndex:0] floatValue], [[positionValues objectAtIndex:1] floatValue]);+ } else {+ rect = CGRectMake(0, 0, 0, 0);+ }+ } else {+ rect = CGRectMake(0, 0, cont.view.bounds.size.width, cont.view.bounds.size.height);+ }++ BOOL wasOpened = NO;++ if (showPreview) {+ wasOpened = [docController presentPreviewAnimated: NO];+ } else {+ CDVViewController* cont = self.cdvViewController;+ wasOpened = [docController presentOpenInMenuFromRect:rect inView:cont.view animated:YES];+ }++ if(wasOpened) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @""];+ //NSLog(@"Success");+ } else {+ NSDictionary *jsonObj = [ [NSDictionary alloc]+ initWithObjectsAndKeys :+ @"9", @"status",+ @"Could not handle UTI", @"message",+ nil+ ];+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:jsonObj];+ }+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ });+}++@end++@implementation FileOpener2 (UIDocumentInteractionControllerDelegate)+ - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {+ UIViewController *presentingViewController = self.viewController;+ if (presentingViewController.view.window != [UIApplication sharedApplication].keyWindow){+ presentingViewController = [UIApplication sharedApplication].keyWindow.rootViewController;+ }++ while (presentingViewController.presentedViewController != nil && ![presentingViewController.presentedViewController isBeingDismissed]){+ presentingViewController = presentingViewController.presentedViewController;+ }+ return presentingViewController;+ }+@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVAssetLibraryFilesystem.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVAssetLibraryFilesystem.hnew file mode 100644index 000000000..e09e2250e--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVAssetLibraryFilesystem.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.+ */++#import "CDVFile.h"++extern NSString* const kCDVAssetsLibraryPrefix;+extern NSString* const kCDVAssetsLibraryScheme;++@interface CDVAssetLibraryFilesystem : NSObject<CDVFileSystem> {+}++- (id) initWithName:(NSString *)name;++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVAssetLibraryFilesystem.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVAssetLibraryFilesystem.mnew file mode 100644index 000000000..8486b7be1--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVAssetLibraryFilesystem.m@@ -0,0 +1,253 @@+/*+ 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 "CDVFile.h"+#import "CDVAssetLibraryFilesystem.h"+#import <Cordova/CDV.h>+#import <AssetsLibrary/ALAsset.h>+#import <AssetsLibrary/ALAssetRepresentation.h>+#import <AssetsLibrary/ALAssetsLibrary.h>+#import <MobileCoreServices/MobileCoreServices.h>++NSString* const kCDVAssetsLibraryPrefix = @"assets-library://";+NSString* const kCDVAssetsLibraryScheme = @"assets-library";++@implementation CDVAssetLibraryFilesystem+@synthesize name=_name, urlTransformer;+++/*+ The CDVAssetLibraryFilesystem works with resources which are identified+ by iOS as+ asset-library://<path>+ and represents them internally as URLs of the form+ cdvfile://localhost/assets-library/<path>+ */++- (NSURL *)assetLibraryURLForLocalURL:(CDVFilesystemURL *)url+{+ if ([url.url.scheme isEqualToString:kCDVFilesystemURLPrefix]) {+ NSString *path = [[url.url absoluteString] substringFromIndex:[@"cdvfile://localhost/assets-library" length]];+ return [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@", path]];+ }+ return url.url;+}++- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url+{+ NSDictionary* entry = [self makeEntryForLocalURL:url];+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];+}++- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {+ return [self makeEntryForPath:url.fullPath isDirectory:NO];+}++- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir+{+ NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];+ NSString* lastPart = [fullPath lastPathComponent];+ if (isDir && ![fullPath hasSuffix:@"/"]) {+ fullPath = [fullPath stringByAppendingString:@"/"];+ }+ [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];+ [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];+ [dirEntry setObject:fullPath forKey:@"fullPath"];+ [dirEntry setObject:lastPart forKey:@"name"];+ [dirEntry setObject:self.name forKey: @"filesystemName"];++ NSURL* nativeURL = [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@",fullPath]];+ if (self.urlTransformer) {+ nativeURL = self.urlTransformer(nativeURL);+ }+ dirEntry[@"nativeURL"] = [nativeURL absoluteString];++ return dirEntry;+}++/* helper function to get the mimeType from the file extension+ * IN:+ * NSString* fullPath - filename (may include path)+ * OUT:+ * NSString* the mime type as type/subtype. nil if not able to determine+ */++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath+{+ NSString* mimeType = nil;++ if (fullPath) {+ CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);+ if (typeId) {+ mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);+ if (!mimeType) {+ // special case for m4a+ if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {+ mimeType = @"audio/mp4";+ } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {+ mimeType = @"audio/wav";+ } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {+ mimeType = @"text/css";+ }+ }+ CFRelease(typeId);+ }+ }+ return mimeType;+}++- (id)initWithName:(NSString *)name+{+ if (self) {+ self.name = name;+ }+ return self;+}++- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options+{+ // return unsupported result for assets-library URLs+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"getFile not supported for assets-library URLs."];+}++- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI+{+ // we don't (yet?) support getting the parent of an asset+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_READABLE_ERR];+}++- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options+{+ // setMetadata doesn't make sense for asset library files+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];+}++- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI+{+ // return error for assets-library URLs+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];+}++- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI+{+ // return error for assets-library URLs+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"removeRecursively not supported for assets-library URLs."];+}++- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI+{+ // return unsupported result for assets-library URLs+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"readEntries not supported for assets-library URLs."];+}++- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos+{+ // assets-library files can't be truncated+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];+}++- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend+{+ // text can't be written into assets-library files+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];+}++- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback+{+ // Copying to an assets library file is not doable, since we can't write it.+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];+ callback(result);+}++- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url+{+ NSString *path = nil;+ if ([[url.url scheme] isEqualToString:kCDVAssetsLibraryScheme]) {+ path = [url.url path];+ } else {+ path = url.fullPath;+ }+ if ([path hasSuffix:@"/"]) {+ path = [path substringToIndex:([path length]-1)];+ }+ return path;+}++- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback+{+ ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {+ if (asset) {+ // We have the asset! Get the data and send it off.+ ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];+ NSUInteger size = (end > start) ? (end - start) : [assetRepresentation size];+ Byte* buffer = (Byte*)malloc(size);+ NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:start length:size error:nil];+ NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];+ NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType);++ callback(data, MIMEType, NO_ERROR);+ } else {+ callback(nil, nil, NOT_FOUND_ERR);+ }+ };++ ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {+ // Retrieving the asset failed for some reason. Send the appropriate error.+ NSLog(@"Error: %@", error);+ callback(nil, nil, SECURITY_ERR);+ };++ ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];+ [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];+}++- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback+{+ // In this case, we need to use an asynchronous method to retrieve the file.+ // Because of this, we can't just assign to `result` and send it at the end of the method.+ // Instead, we return after calling the asynchronous method and send `result` in each of the blocks.+ ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {+ if (asset) {+ // We have the asset! Populate the dictionary and send it off.+ NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];+ ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];+ [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:[assetRepresentation size]] forKey:@"size"];+ [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];+ NSString* filename = [assetRepresentation filename];+ [fileInfo setObject:filename forKey:@"name"];+ [fileInfo setObject:[CDVAssetLibraryFilesystem getMimeTypeFromPath:filename] forKey:@"type"];+ NSDate* creationDate = [asset valueForProperty:ALAssetPropertyDate];+ NSNumber* msDate = [NSNumber numberWithDouble:[creationDate timeIntervalSince1970] * 1000];+ [fileInfo setObject:msDate forKey:@"lastModifiedDate"];++ callback([CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]);+ } else {+ // We couldn't find the asset. Send the appropriate error.+ callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]);+ }+ };+ ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {+ // Retrieving the asset failed for some reason. Send the appropriate error.+ callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]]);+ };++ ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];+ [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];+ return;+}+@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVFile.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVFile.hnew file mode 100644index 000000000..987c66b5c--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVFile.h@@ -0,0 +1,157 @@+/*+ 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>++extern NSString* const kCDVAssetsLibraryPrefix;+extern NSString* const kCDVFilesystemURLPrefix;++enum CDVFileError {+ NO_ERROR = 0,+ NOT_FOUND_ERR = 1,+ SECURITY_ERR = 2,+ ABORT_ERR = 3,+ NOT_READABLE_ERR = 4,+ ENCODING_ERR = 5,+ NO_MODIFICATION_ALLOWED_ERR = 6,+ INVALID_STATE_ERR = 7,+ SYNTAX_ERR = 8,+ INVALID_MODIFICATION_ERR = 9,+ QUOTA_EXCEEDED_ERR = 10,+ TYPE_MISMATCH_ERR = 11,+ PATH_EXISTS_ERR = 12+};+typedef int CDVFileError;++@interface CDVFilesystemURL : NSObject {+ NSURL *_url;+ NSString *_fileSystemName;+ NSString *_fullPath;+}++- (id) initWithString:(NSString*)strURL;+- (id) initWithURL:(NSURL*)URL;++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL;++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL;++- (NSString *)absoluteURL;++@property (atomic) NSURL *url;+@property (atomic) NSString *fileSystemName;+@property (atomic) NSString *fullPath;++@end++@interface CDVFilesystemURLProtocol : NSURLProtocol+@end++@protocol CDVFileSystem+- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url;+- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options;+- (CDVPluginResult *)getParentForURL:(CDVFilesystemURL *)localURI;+- (CDVPluginResult *)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options;+- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI;+- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI;+- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI;+- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos;+- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend;+- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback;+- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback;+- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback;++- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url;+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir;++@property (nonatomic,strong) NSString *name;+@property (nonatomic, copy) NSURL*(^urlTransformer)(NSURL*);++@optional+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURI;+- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path;++@end++@interface CDVFile : CDVPlugin {+ NSString* rootDocsPath;+ NSString* appDocsPath;+ NSString* appLibraryPath;+ NSString* appTempPath;++ NSMutableArray* fileSystems_;+ BOOL userHasAllowed;+}++- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath;+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir;+- (NSDictionary *)makeEntryForURL:(NSURL *)URL;+- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath;++- (NSObject<CDVFileSystem> *)filesystemForURL:(CDVFilesystemURL *)localURL;++/* Native Registration API */+- (void)registerFilesystem:(NSObject<CDVFileSystem> *)fs;+- (NSObject<CDVFileSystem> *)fileSystemByName:(NSString *)fsName;++/* Exec API */+- (void)requestFileSystem:(CDVInvokedUrlCommand*)command;+- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command;+- (void)getDirectory:(CDVInvokedUrlCommand*)command;+- (void)getFile:(CDVInvokedUrlCommand*)command;+- (void)getParent:(CDVInvokedUrlCommand*)command;+- (void)removeRecursively:(CDVInvokedUrlCommand*)command;+- (void)remove:(CDVInvokedUrlCommand*)command;+- (void)copyTo:(CDVInvokedUrlCommand*)command;+- (void)moveTo:(CDVInvokedUrlCommand*)command;+- (void)getFileMetadata:(CDVInvokedUrlCommand*)command;+- (void)readEntries:(CDVInvokedUrlCommand*)command;+- (void)readAsText:(CDVInvokedUrlCommand*)command;+- (void)readAsDataURL:(CDVInvokedUrlCommand*)command;+- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command;+- (void)write:(CDVInvokedUrlCommand*)command;+- (void)testFileExists:(CDVInvokedUrlCommand*)command;+- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command;+- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command;+- (void)truncate:(CDVInvokedUrlCommand*)command;+- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy;++/* Compatibilty with older File API */+- (NSString*)getMimeTypeFromPath:(NSString*)fullPath;+- (NSDictionary *)getDirectoryEntry:(NSString *)target isDirectory:(BOOL)bDirRequest;++/* Conversion between filesystem paths and URLs */+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)URL;++/* Internal methods for testing */+- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command;++@property (nonatomic, strong) NSString* rootDocsPath;+@property (nonatomic, strong) NSString* appDocsPath;+@property (nonatomic, strong) NSString* appLibraryPath;+@property (nonatomic, strong) NSString* appTempPath;+@property (nonatomic, strong) NSString* persistentPath;+@property (nonatomic, strong) NSString* temporaryPath;+@property (nonatomic, strong) NSMutableArray* fileSystems;++@property BOOL userHasAllowed;++@end++#define kW3FileTemporary @"temporary"+#define kW3FilePersistent @"persistent"diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVFile.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVFile.mnew file mode 100644index 000000000..59e7d6407--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVFile.m@@ -0,0 +1,1119 @@+/*+ 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 <Cordova/CDV.h>+#import "CDVFile.h"+#import "CDVLocalFilesystem.h"+#import "CDVAssetLibraryFilesystem.h"+#import <objc/message.h>++static NSString* toBase64(NSData* data) {+ SEL s1 = NSSelectorFromString(@"cdv_base64EncodedString");+ SEL s2 = NSSelectorFromString(@"base64EncodedString");+ SEL s3 = NSSelectorFromString(@"base64EncodedStringWithOptions:");++ if ([data respondsToSelector:s1]) {+ NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s1];+ return func(data, s1);+ } else if ([data respondsToSelector:s2]) {+ NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s2];+ return func(data, s2);+ } else if ([data respondsToSelector:s3]) {+ NSString* (*func)(id, SEL, NSUInteger) = (void *)[data methodForSelector:s3];+ return func(data, s3, 0);+ } else {+ return nil;+ }+}++CDVFile *filePlugin = nil;++extern NSString * const NSURLIsExcludedFromBackupKey __attribute__((weak_import));++#ifndef __IPHONE_5_1+ NSString* const NSURLIsExcludedFromBackupKey = @"NSURLIsExcludedFromBackupKey";+#endif++NSString* const kCDVFilesystemURLPrefix = @"cdvfile";++@implementation CDVFilesystemURL+@synthesize url=_url;+@synthesize fileSystemName=_fileSystemName;+@synthesize fullPath=_fullPath;++- (id) initWithString:(NSString *)strURL+{+ if ( self = [super init] ) {+ NSURL *decodedURL = [NSURL URLWithString:strURL];+ return [self initWithURL:decodedURL];+ }+ return nil;+}++-(id) initWithURL:(NSURL *)URL+{+ if ( self = [super init] ) {+ self.url = URL;+ self.fileSystemName = [self filesystemNameForLocalURI:URL];+ self.fullPath = [self fullPathForLocalURI:URL];+ }+ return self;+}++/*+ * IN+ * NSString localURI+ * OUT+ * NSString FileSystem Name for this URI, or nil if it is not recognized.+ */+- (NSString *)filesystemNameForLocalURI:(NSURL *)uri+{+ if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) {+ NSArray *pathComponents = [uri pathComponents];+ if (pathComponents != nil && pathComponents.count > 1) {+ return [pathComponents objectAtIndex:1];+ }+ } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) {+ return @"assets-library";+ }+ return nil;+}++/*+ * IN+ * NSString localURI+ * OUT+ * NSString fullPath component suitable for an Entry object.+ * The incoming URI should be properly escaped. The returned fullPath is unescaped.+ */+- (NSString *)fullPathForLocalURI:(NSURL *)uri+{+ if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) {+ NSString *path = [uri path];+ if ([uri query]) {+ path = [NSString stringWithFormat:@"%@?%@", path, [uri query]];+ }+ NSRange slashRange = [path rangeOfString:@"/" options:0 range:NSMakeRange(1, path.length-1)];+ if (slashRange.location == NSNotFound) {+ return @"";+ }+ return [path substringFromIndex:slashRange.location];+ } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) {+ return [[uri absoluteString] substringFromIndex:[kCDVAssetsLibraryScheme length]+2];+ }+ return nil;+}+++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL+{+ return [[CDVFilesystemURL alloc] initWithString:strURL];+}+++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL+{+ return [[CDVFilesystemURL alloc] initWithURL:URL];+}++- (NSString *)absoluteURL+{+ return [NSString stringWithFormat:@"cdvfile://localhost/%@%@", self.fileSystemName, self.fullPath];+}++@end++@implementation CDVFilesystemURLProtocol+++ (BOOL)canInitWithRequest:(NSURLRequest*)request+{+ NSURL* url = [request URL];+ return [[url scheme] isEqualToString:kCDVFilesystemURLPrefix];+}+++ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request+{+ return request;+}+++ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB+{+ return [[[requestA URL] resourceSpecifier] isEqualToString:[[requestB URL] resourceSpecifier]];+}++- (void)startLoading+{+ CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithURL:[[self request] URL]];+ NSObject<CDVFileSystem> *fs = [filePlugin filesystemForURL:url];+ __weak CDVFilesystemURLProtocol* weakSelf = self;++ [fs readFileAtURL:url start:0 end:-1 callback:^void(NSData *data, NSString *mimetype, CDVFileError error) {+ NSMutableDictionary* responseHeaders = [[NSMutableDictionary alloc] init];+ responseHeaders[@"Cache-Control"] = @"no-cache";++ if (!error) {+ responseHeaders[@"Content-Type"] = mimetype;+ NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:200 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders];+ [[weakSelf client] URLProtocol:weakSelf didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];+ [[weakSelf client] URLProtocol:weakSelf didLoadData:data];+ [[weakSelf client] URLProtocolDidFinishLoading:weakSelf];+ } else {+ NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:404 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders];+ [[weakSelf client] URLProtocol:weakSelf didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];+ [[weakSelf client] URLProtocolDidFinishLoading:weakSelf];+ }+ }];+}++- (void)stopLoading+{}++- (NSCachedURLResponse *)connection:(NSURLConnection *)connection+ willCacheResponse:(NSCachedURLResponse*)cachedResponse {+ return nil;+}++@end+++@implementation CDVFile++@synthesize rootDocsPath, appDocsPath, appLibraryPath, appTempPath, userHasAllowed, fileSystems=fileSystems_;++- (void)registerFilesystem:(NSObject<CDVFileSystem> *)fs {+ __weak CDVFile* weakSelf = self;+ SEL sel = NSSelectorFromString(@"urlTransformer");+ // for backwards compatibility - we check if this property is there+ // we create a wrapper block because the urlTransformer property+ // on the commandDelegate might be set dynamically at a future time+ // (and not dependent on plugin loading order)+ if ([self.commandDelegate respondsToSelector:sel]) {+ fs.urlTransformer = ^NSURL*(NSURL* urlToTransform) {+ // grab the block from the commandDelegate+ NSURL* (^urlTransformer)(NSURL*) = ((id(*)(id, SEL))objc_msgSend)(weakSelf.commandDelegate, sel);+ // if block is not null, we call it+ if (urlTransformer) {+ return urlTransformer(urlToTransform);+ } else { // else we return the same url+ return urlToTransform;+ }+ };+ }+ [fileSystems_ addObject:fs];+}++- (NSObject<CDVFileSystem> *)fileSystemByName:(NSString *)fsName+{+ if (self.fileSystems != nil) {+ for (NSObject<CDVFileSystem> *fs in self.fileSystems) {+ if ([fs.name isEqualToString:fsName]) {+ return fs;+ }+ }+ }+ return nil;+}++- (NSObject<CDVFileSystem> *)filesystemForURL:(CDVFilesystemURL *)localURL {+ if (localURL.fileSystemName == nil) return nil;+ @try {+ return [self fileSystemByName:localURL.fileSystemName];+ }+ @catch (NSException *e) {+ return nil;+ }+}++- (NSArray *)getExtraFileSystemsPreference:(UIViewController *)vc+{+ NSString *filesystemsStr = nil;+ if([self.viewController isKindOfClass:[CDVViewController class]]) {+ CDVViewController *vc = (CDVViewController *)self.viewController;+ NSDictionary *settings = [vc settings];+ filesystemsStr = [settings[@"iosextrafilesystems"] lowercaseString];+ }+ if (!filesystemsStr) {+ filesystemsStr = @"library,library-nosync,documents,documents-nosync,cache,bundle,root";+ }+ return [filesystemsStr componentsSeparatedByString:@","];+}++- (void)makeNonSyncable:(NSString*)path {+ [[NSFileManager defaultManager] createDirectoryAtPath:path+ withIntermediateDirectories:YES+ attributes:nil+ error:nil];+ NSURL* url = [NSURL fileURLWithPath:path];+ [url setResourceValue: [NSNumber numberWithBool: YES]+ forKey: NSURLIsExcludedFromBackupKey error:nil];++}++- (void)registerExtraFileSystems:(NSArray *)filesystems fromAvailableSet:(NSDictionary *)availableFileSystems+{+ NSMutableSet *installedFilesystems = [[NSMutableSet alloc] initWithCapacity:7];++ /* Build non-syncable directories as necessary */+ for (NSString *nonSyncFS in @[@"library-nosync", @"documents-nosync"]) {+ if ([filesystems containsObject:nonSyncFS]) {+ [self makeNonSyncable:availableFileSystems[nonSyncFS]];+ }+ }++ /* Register filesystems in order */+ for (NSString *fsName in filesystems) {+ if (![installedFilesystems containsObject:fsName]) {+ NSString *fsRoot = availableFileSystems[fsName];+ if (fsRoot) {+ [filePlugin registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:fsName root:fsRoot]];+ [installedFilesystems addObject:fsName];+ } else {+ NSLog(@"Unrecognized extra filesystem identifier: %@", fsName);+ }+ }+ }+}++- (NSDictionary *)getAvailableFileSystems+{+ NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];+ NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];+ return @{+ @"library": libPath,+ @"library-nosync": [libPath stringByAppendingPathComponent:@"NoCloud"],+ @"documents": docPath,+ @"documents-nosync": [docPath stringByAppendingPathComponent:@"NoCloud"],+ @"cache": [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0],+ @"bundle": [[NSBundle mainBundle] bundlePath],+ @"root": @"/"+ };+}++- (void)pluginInitialize+{+ filePlugin = self;+ [NSURLProtocol registerClass:[CDVFilesystemURLProtocol class]];++ fileSystems_ = [[NSMutableArray alloc] initWithCapacity:3];++ // Get the Library directory path+ NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);+ self.appLibraryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"files"];++ // Get the Temporary directory path+ self.appTempPath = [NSTemporaryDirectory()stringByStandardizingPath]; // remove trailing slash from NSTemporaryDirectory()++ // Get the Documents directory path+ paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);+ self.rootDocsPath = [paths objectAtIndex:0];+ self.appDocsPath = [self.rootDocsPath stringByAppendingPathComponent:@"files"];+++ NSString *location = nil;+ if([self.viewController isKindOfClass:[CDVViewController class]]) {+ CDVViewController *vc = (CDVViewController *)self.viewController;+ NSMutableDictionary *settings = vc.settings;+ location = [[settings objectForKey:@"iospersistentfilelocation"] lowercaseString];+ }+ if (location == nil) {+ // Compatibilty by default (if the config preference is not set, or+ // if we're not embedded in a CDVViewController somehow.)+ location = @"compatibility";+ }++ NSError *error;+ if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appTempPath+ withIntermediateDirectories:YES+ attributes:nil+ error:&error]) {+ [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"temporary" root:self.appTempPath]];+ } else {+ NSLog(@"Unable to create temporary directory: %@", error);+ }+ if ([location isEqualToString:@"library"]) {+ if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appLibraryPath+ withIntermediateDirectories:YES+ attributes:nil+ error:&error]) {+ [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.appLibraryPath]];+ } else {+ NSLog(@"Unable to create library directory: %@", error);+ }+ } else if ([location isEqualToString:@"compatibility"]) {+ /*+ * Fall-back to compatibility mode -- this is the logic implemented in+ * earlier versions of this plugin, and should be maintained here so+ * that apps which were originally deployed with older versions of the+ * plugin can continue to provide access to files stored under those+ * versions.+ */+ [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.rootDocsPath]];+ } else {+ NSAssert(false,+ @"File plugin configuration error: Please set iosPersistentFileLocation in config.xml to one of \"library\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");+ }+ [self registerFilesystem:[[CDVAssetLibraryFilesystem alloc] initWithName:@"assets-library"]];++ [self registerExtraFileSystems:[self getExtraFileSystemsPreference:self.viewController]+ fromAvailableSet:[self getAvailableFileSystems]];++}++- (CDVFilesystemURL *)fileSystemURLforArg:(NSString *)urlArg+{+ CDVFilesystemURL* ret = nil;+ if ([urlArg hasPrefix:@"file://"]) {+ /* This looks like a file url. Get the path, and see if any handlers recognize it. */+ NSURL *fileURL = [NSURL URLWithString:urlArg];+ NSURL *resolvedFileURL = [fileURL URLByResolvingSymlinksInPath];+ NSString *path = [resolvedFileURL path];+ ret = [self fileSystemURLforLocalPath:path];+ } else {+ ret = [CDVFilesystemURL fileSystemURLWithString:urlArg];+ }+ return ret;+}++- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath+{+ CDVFilesystemURL *localURL = nil;+ NSUInteger shortestFullPath = 0;++ // Try all installed filesystems, in order. Return the most match url.+ for (id object in self.fileSystems) {+ if ([object respondsToSelector:@selector(URLforFilesystemPath:)]) {+ CDVFilesystemURL *url = [object URLforFilesystemPath:localPath];+ if (url){+ // A shorter fullPath would imply that the filesystem is a better match for the local path+ if (!localURL || ([[url fullPath] length] < shortestFullPath)) {+ localURL = url;+ shortestFullPath = [[url fullPath] length];+ }+ }+ }+ }+ return localURL;+}++- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath+{+ NSFileManager* fMgr = [[NSFileManager alloc] init];++ NSError* __autoreleasing pError = nil;++ NSDictionary* pDict = [fMgr attributesOfFileSystemForPath:appPath error:&pError];+ NSNumber* pNumAvail = (NSNumber*)[pDict objectForKey:NSFileSystemFreeSize];++ return pNumAvail;+}++/* Request the File System info+ *+ * IN:+ * arguments[0] - type (number as string)+ * TEMPORARY = 0, PERSISTENT = 1;+ * arguments[1] - size+ *+ * OUT:+ * Dictionary representing FileSystem object+ * name - the human readable directory name+ * root = DirectoryEntry object+ * bool isDirectory+ * bool isFile+ * string name+ * string fullPath+ * fileSystem = FileSystem object - !! ignored because creates circular reference !!+ */++- (void)requestFileSystem:(CDVInvokedUrlCommand*)command+{+ // arguments+ NSString* strType = [command argumentAtIndex:0];+ unsigned long long size = [[command argumentAtIndex:1] longLongValue];++ int type = [strType intValue];+ CDVPluginResult* result = nil;++ if (type >= self.fileSystems.count) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR];+ NSLog(@"No filesystem of type requested");+ } else {+ NSString* fullPath = @"/";+ // check for avail space for size request+ NSNumber* pNumAvail = [self checkFreeDiskSpace:self.rootDocsPath];+ // NSLog(@"Free space: %@", [NSString stringWithFormat:@"%qu", [ pNumAvail unsignedLongLongValue ]]);+ if (pNumAvail && ([pNumAvail unsignedLongLongValue] < size)) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:QUOTA_EXCEEDED_ERR];+ } else {+ NSObject<CDVFileSystem> *rootFs = [self.fileSystems objectAtIndex:type];+ if (rootFs == nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR];+ NSLog(@"No filesystem of type requested");+ } else {+ NSMutableDictionary* fileSystem = [NSMutableDictionary dictionaryWithCapacity:2];+ [fileSystem setObject:rootFs.name forKey:@"name"];+ NSDictionary* dirEntry = [self makeEntryForPath:fullPath fileSystemName:rootFs.name isDirectory:YES];+ [fileSystem setObject:dirEntry forKey:@"root"];+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileSystem];+ }+ }+ }+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}+++- (void)requestAllFileSystems:(CDVInvokedUrlCommand*)command+{+ NSMutableArray* ret = [[NSMutableArray alloc] init];+ for (NSObject<CDVFileSystem>* root in fileSystems_) {+ [ret addObject:[self makeEntryForPath:@"/" fileSystemName:root.name isDirectory:YES]];+ }+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:ret];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++- (void)requestAllPaths:(CDVInvokedUrlCommand*)command+{+ NSString* libPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];+ NSString* libPathSync = [libPath stringByAppendingPathComponent:@"Cloud"];+ NSString* libPathNoSync = [libPath stringByAppendingPathComponent:@"NoCloud"];+ NSString* docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];+ NSString* storagePath = [libPath stringByDeletingLastPathComponent];+ NSString* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];++ // Create the directories if necessary.+ [[NSFileManager defaultManager] createDirectoryAtPath:libPathSync withIntermediateDirectories:YES attributes:nil error:nil];+ [[NSFileManager defaultManager] createDirectoryAtPath:libPathNoSync withIntermediateDirectories:YES attributes:nil error:nil];+ // Mark NoSync as non-iCloud.+ [[NSURL fileURLWithPath:libPathNoSync] setResourceValue: [NSNumber numberWithBool: YES]+ forKey: NSURLIsExcludedFromBackupKey error:nil];++ NSDictionary* ret = @{+ @"applicationDirectory": [[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]] absoluteString],+ @"applicationStorageDirectory": [[NSURL fileURLWithPath:storagePath] absoluteString],+ @"dataDirectory": [[NSURL fileURLWithPath:libPathNoSync] absoluteString],+ @"syncedDataDirectory": [[NSURL fileURLWithPath:libPathSync] absoluteString],+ @"documentsDirectory": [[NSURL fileURLWithPath:docPath] absoluteString],+ @"cacheDirectory": [[NSURL fileURLWithPath:cachePath] absoluteString],+ @"tempDirectory": [[NSURL fileURLWithPath:NSTemporaryDirectory()] absoluteString]+ };++ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:ret];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++/* Creates and returns a dictionary representing an Entry Object+ *+ * IN:+ * NSString* fullPath of the entry+ * int fsType - FileSystem type+ * BOOL isDirectory - YES if this is a directory, NO if is a file+ * OUT:+ * NSDictionary* Entry object+ * bool as NSNumber isDirectory+ * bool as NSNumber isFile+ * NSString* name - last part of path+ * NSString* fullPath+ * NSString* filesystemName - FileSystem name -- actual filesystem will be created on the JS side if necessary, to avoid+ * creating circular reference (FileSystem contains DirectoryEntry which contains FileSystem.....!!)+ */+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir+{+ NSObject<CDVFileSystem> *fs = [self fileSystemByName:fsName];+ return [fs makeEntryForPath:fullPath isDirectory:isDir];+}++- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)localURL+{+ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURL];+ return [fs makeEntryForLocalURL:localURL];+}++- (NSDictionary *)makeEntryForURL:(NSURL *)URL+{+ CDVFilesystemURL* fsURL = [self fileSystemURLforArg:[URL absoluteString]];+ return [self makeEntryForLocalURL:fsURL];+}++/*+ * Given a URI determine the File System information associated with it and return an appropriate W3C entry object+ * IN+ * NSString* localURI: Should be an escaped local filesystem URI+ * OUT+ * Entry object+ * bool isDirectory+ * bool isFile+ * string name+ * string fullPath+ * fileSystem = FileSystem object - !! ignored because creates circular reference FileSystem contains DirectoryEntry which contains FileSystem.....!!+ */+- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command+{+ // arguments+ NSString* localURIstr = [command argumentAtIndex:0];+ CDVPluginResult* result;++ localURIstr = [self encodePath:localURIstr]; //encode path before resolving+ CDVFilesystemURL* inputURI = [self fileSystemURLforArg:localURIstr];++ if (inputURI == nil || inputURI.fileSystemName == nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR];+ } else {+ NSObject<CDVFileSystem> *fs = [self filesystemForURL:inputURI];+ if (fs == nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR];+ } else {+ result = [fs entryForLocalURI:inputURI];+ }+ }+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++//encode path with percent escapes+-(NSString *)encodePath:(NSString *)path+{+ NSString *decodedPath = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //decode incase it's already encoded to avoid encoding twice+ return [decodedPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];+}+++/* Part of DirectoryEntry interface, creates or returns the specified directory+ * IN:+ * NSString* localURI - local filesystem URI for this directory+ * NSString* path - directory to be created/returned; may be full path or relative path+ * NSDictionary* - Flags object+ * boolean as NSNumber create -+ * if create is true and directory does not exist, create dir and return directory entry+ * if create is true and exclusive is true and directory does exist, return error+ * if create is false and directory does not exist, return error+ * if create is false and the path represents a file, return error+ * boolean as NSNumber exclusive - used in conjunction with create+ * if exclusive is true and create is true - specifies failure if directory already exists+ *+ *+ */+- (void)getDirectory:(CDVInvokedUrlCommand*)command+{+ NSMutableArray* arguments = [NSMutableArray arrayWithArray:command.arguments];+ NSMutableDictionary* options = nil;++ if ([arguments count] >= 3) {+ options = [command argumentAtIndex:2 withDefault:nil];+ }+ // add getDir to options and call getFile()+ if (options != nil) {+ options = [NSMutableDictionary dictionaryWithDictionary:options];+ } else {+ options = [NSMutableDictionary dictionaryWithCapacity:1];+ }+ [options setObject:[NSNumber numberWithInt:1] forKey:@"getDir"];+ if ([arguments count] >= 3) {+ [arguments replaceObjectAtIndex:2 withObject:options];+ } else {+ [arguments addObject:options];+ }+ CDVInvokedUrlCommand* subCommand =+ [[CDVInvokedUrlCommand alloc] initWithArguments:arguments+ callbackId:command.callbackId+ className:command.className+ methodName:command.methodName];++ [self getFile:subCommand];+}++/* Part of DirectoryEntry interface, creates or returns the specified file+ * IN:+ * NSString* baseURI - local filesytem URI for the base directory to search+ * NSString* requestedPath - file to be created/returned; may be absolute path or relative path+ * NSDictionary* options - Flags object+ * boolean as NSNumber create -+ * if create is true and file does not exist, create file and return File entry+ * if create is true and exclusive is true and file does exist, return error+ * if create is false and file does not exist, return error+ * if create is false and the path represents a directory, return error+ * boolean as NSNumber exclusive - used in conjunction with create+ * if exclusive is true and create is true - specifies failure if file already exists+ */+- (void)getFile:(CDVInvokedUrlCommand*)command+{+ NSString* baseURIstr = [command argumentAtIndex:0];+ CDVFilesystemURL* baseURI = [self fileSystemURLforArg:baseURIstr];+ NSString* requestedPath = [command argumentAtIndex:1];+ NSDictionary* options = [command argumentAtIndex:2 withDefault:nil];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:baseURI];+ CDVPluginResult* result = [fs getFileForURL:baseURI requestedPath:requestedPath options:options];+++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++/*+ * Look up the parent Entry containing this Entry.+ * If this Entry is the root of its filesystem, its parent is itself.+ * IN:+ * NSArray* arguments+ * 0 - NSString* localURI+ * NSMutableDictionary* options+ * empty+ */+- (void)getParent:(CDVInvokedUrlCommand*)command+{+ // arguments are URL encoded+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+ CDVPluginResult* result = [fs getParentForURL:localURI];++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++/*+ * set MetaData of entry+ * Currently we only support "com.apple.MobileBackup" (boolean)+ */+- (void)setMetadata:(CDVInvokedUrlCommand*)command+{+ // arguments+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ NSDictionary* options = [command argumentAtIndex:1 withDefault:nil];+ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+ CDVPluginResult* result = [fs setMetadataForURL:localURI withObject:options];++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++/* removes the directory or file entry+ * IN:+ * NSArray* arguments+ * 0 - NSString* localURI+ *+ * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir+ * returns INVALID_MODIFICATION_ERR if is non-empty dir or asset library file+ * returns NOT_FOUND_ERR if file or dir is not found+*/+- (void)remove:(CDVInvokedUrlCommand*)command+{+ // arguments+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ CDVPluginResult* result = nil;++ if ([localURI.fullPath isEqualToString:@""]) {+ // error if try to remove top level (documents or tmp) dir+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];+ } else {+ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+ result = [fs removeFileAtURL:localURI];+ }+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++/* recursively removes the directory+ * IN:+ * NSArray* arguments+ * 0 - NSString* localURI+ *+ * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir+ * returns NOT_FOUND_ERR if file or dir is not found+ */+- (void)removeRecursively:(CDVInvokedUrlCommand*)command+{+ // arguments+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ CDVPluginResult* result = nil;++ if ([localURI.fullPath isEqualToString:@""]) {+ // error if try to remove top level (documents or tmp) dir+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];+ } else {+ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+ result = [fs recursiveRemoveFileAtURL:localURI];+ }+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++- (void)copyTo:(CDVInvokedUrlCommand*)command+{+ [self doCopyMove:command isCopy:YES];+}++- (void)moveTo:(CDVInvokedUrlCommand*)command+{+ [self doCopyMove:command isCopy:NO];+}++/* Copy/move a file or directory to a new location+ * IN:+ * NSArray* arguments+ * 0 - NSString* URL of entry to copy+ * 1 - NSString* URL of the directory into which to copy/move the entry+ * 2 - Optionally, the new name of the entry, defaults to the current name+ * BOOL - bCopy YES if copy, NO if move+ */+- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy+{+ NSArray* arguments = command.arguments;++ // arguments+ NSString* srcURLstr = [command argumentAtIndex:0];+ NSString* destURLstr = [command argumentAtIndex:1];++ CDVPluginResult *result;++ if (!srcURLstr || !destURLstr) {+ // either no source or no destination provided+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ return;+ }++ CDVFilesystemURL* srcURL = [self fileSystemURLforArg:srcURLstr];+ CDVFilesystemURL* destURL = [self fileSystemURLforArg:destURLstr];++ NSObject<CDVFileSystem> *srcFs = [self filesystemForURL:srcURL];+ NSObject<CDVFileSystem> *destFs = [self filesystemForURL:destURL];++ // optional argument; use last component from srcFullPath if new name not provided+ NSString* newName = ([arguments count] > 2) ? [command argumentAtIndex:2] : [srcURL.url lastPathComponent];+ if ([newName rangeOfString:@":"].location != NSNotFound) {+ // invalid chars in new name+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ return;+ }++ __weak CDVFile* weakSelf = self;+ [self.commandDelegate runInBackground:^ {+ [destFs copyFileToURL:destURL withName:newName fromFileSystem:srcFs atURL:srcURL copy:bCopy callback:^(CDVPluginResult* result) {+ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+ }];++}++- (void)getFileMetadata:(CDVInvokedUrlCommand*)command+{+ // arguments+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+ __weak CDVFile* weakSelf = self;+ [fs getFileMetadataForURL:localURI callback:^(CDVPluginResult* result) {+ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+}++- (void)readEntries:(CDVInvokedUrlCommand*)command+{+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+ CDVPluginResult *result = [fs readEntriesAtURL:localURI];++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++/* read and return file data+ * IN:+ * NSArray* arguments+ * 0 - NSString* fullPath+ * 1 - NSString* encoding+ * 2 - NSString* start+ * 3 - NSString* end+ */+- (void)readAsText:(CDVInvokedUrlCommand*)command+{+ // arguments+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ NSString* encoding = [command argumentAtIndex:1];+ NSInteger start = [[command argumentAtIndex:2] integerValue];+ NSInteger end = [[command argumentAtIndex:3] integerValue];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];++ if (fs == nil) {+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ return;+ }++ // TODO: implement+ if ([@"UTF-8" caseInsensitiveCompare : encoding] != NSOrderedSame) {+ NSLog(@"Only UTF-8 encodings are currently supported by readAsText");+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ return;+ }++ __weak CDVFile* weakSelf = self;++ [self.commandDelegate runInBackground:^ {+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {+ CDVPluginResult* result = nil;+ if (data != nil) {+ NSString* str = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSUTF8StringEncoding freeWhenDone:NO];+ // Check that UTF8 conversion did not fail.+ if (str != nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:str];+ result.associatedObject = data;+ } else {+ errorCode = ENCODING_ERR;+ }+ }+ if (result == nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];+ }++ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+ }];+}++/* Read content of text file and return as base64 encoded data url.+ * IN:+ * NSArray* arguments+ * 0 - NSString* fullPath+ * 1 - NSString* start+ * 2 - NSString* end+ *+ * Determines the mime type from the file extension, returns ENCODING_ERR if mimetype can not be determined.+ */++- (void)readAsDataURL:(CDVInvokedUrlCommand*)command+{+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ NSInteger start = [[command argumentAtIndex:1] integerValue];+ NSInteger end = [[command argumentAtIndex:2] integerValue];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];++ __weak CDVFile* weakSelf = self;+ [self.commandDelegate runInBackground:^ {+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {+ CDVPluginResult* result = nil;+ if (data != nil) {+ NSString* b64Str = toBase64(data);+ NSString* output = [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, b64Str];+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:output];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];+ }++ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+ }];+}++/* Read content of text file and return as an arraybuffer+ * IN:+ * NSArray* arguments+ * 0 - NSString* fullPath+ * 1 - NSString* start+ * 2 - NSString* end+ */++- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command+{+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ NSInteger start = [[command argumentAtIndex:1] integerValue];+ NSInteger end = [[command argumentAtIndex:2] integerValue];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];++ __weak CDVFile* weakSelf = self;++ [self.commandDelegate runInBackground:^ {+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {+ CDVPluginResult* result = nil;+ if (data != nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArrayBuffer:data];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];+ }++ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+ }];+}++- (void)readAsBinaryString:(CDVInvokedUrlCommand*)command+{+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ NSInteger start = [[command argumentAtIndex:1] integerValue];+ NSInteger end = [[command argumentAtIndex:2] integerValue];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];++ __weak CDVFile* weakSelf = self;++ [self.commandDelegate runInBackground:^ {+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {+ CDVPluginResult* result = nil;+ if (data != nil) {+ NSString* payload = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSASCIIStringEncoding freeWhenDone:NO];+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload];+ result.associatedObject = data;+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];+ }++ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+ }];+}+++- (void)truncate:(CDVInvokedUrlCommand*)command+{+ // arguments+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ unsigned long long pos = (unsigned long long)[[command argumentAtIndex:1] longLongValue];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+ CDVPluginResult *result = [fs truncateFileAtURL:localURI atPosition:pos];++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++/* write+ * IN:+ * NSArray* arguments+ * 0 - NSString* localURI of file to write to+ * 1 - NSString* or NSData* data to write+ * 2 - NSNumber* position to begin writing+ */+- (void)write:(CDVInvokedUrlCommand*)command+{+ __weak CDVFile* weakSelf = self;++ [self.commandDelegate runInBackground:^ {+ NSString* callbackId = command.callbackId;++ // arguments+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];+ id argData = [command argumentAtIndex:1];+ unsigned long long pos = (unsigned long long)[[command argumentAtIndex:2] longLongValue];++ NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];+++ [fs truncateFileAtURL:localURI atPosition:pos];+ CDVPluginResult *result;+ if ([argData isKindOfClass:[NSString class]]) {+ NSData *encData = [argData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];+ result = [fs writeToFileAtURL:localURI withData:encData append:YES];+ } else if ([argData isKindOfClass:[NSData class]]) {+ result = [fs writeToFileAtURL:localURI withData:argData append:YES];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid parameter type"];+ }+ [weakSelf.commandDelegate sendPluginResult:result callbackId:callbackId];+ }];+}++#pragma mark Methods for converting between URLs and paths++- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURL+{+ for (NSObject<CDVFileSystem> *fs in self.fileSystems) {+ if ([fs.name isEqualToString:localURL.fileSystemName]) {+ if ([fs respondsToSelector:@selector(filesystemPathForURL:)]) {+ return [fs filesystemPathForURL:localURL];+ }+ }+ }+ return nil;+}++#pragma mark Undocumented Filesystem API++- (void)testFileExists:(CDVInvokedUrlCommand*)command+{+ // arguments+ NSString* argPath = [command argumentAtIndex:0];++ // Get the file manager+ NSFileManager* fMgr = [NSFileManager defaultManager];+ NSString* appFile = argPath; // [ self getFullPath: argPath];++ BOOL bExists = [fMgr fileExistsAtPath:appFile];+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(bExists ? 1 : 0)];++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command+{+ // arguments+ NSString* argPath = [command argumentAtIndex:0];++ // Get the file manager+ NSFileManager* fMgr = [[NSFileManager alloc] init];+ NSString* appFile = argPath; // [self getFullPath: argPath];+ BOOL bIsDir = NO;+ BOOL bExists = [fMgr fileExistsAtPath:appFile isDirectory:&bIsDir];++ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:((bExists && bIsDir) ? 1 : 0)];++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++// Returns number of bytes available via callback+- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command+{+ // no arguments++ NSNumber* pNumAvail = [self checkFreeDiskSpace:self.rootDocsPath];++ NSString* strFreeSpace = [NSString stringWithFormat:@"%qu", [pNumAvail unsignedLongLongValue]];+ // NSLog(@"Free space is %@", strFreeSpace );++ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:strFreeSpace];++ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++#pragma mark Compatibility with older File API++- (NSString*)getMimeTypeFromPath:(NSString*)fullPath+{+ return [CDVLocalFilesystem getMimeTypeFromPath:fullPath];+}++- (NSDictionary *)getDirectoryEntry:(NSString *)localPath isDirectory:(BOOL)bDirRequest+{+ CDVFilesystemURL *localURL = [self fileSystemURLforLocalPath:localPath];+ return [self makeEntryForPath:localURL.fullPath fileSystemName:localURL.fileSystemName isDirectory:bDirRequest];+}++#pragma mark Internal methods for testing+// Internal methods for testing: Get the on-disk location of a local filesystem url.+// [Currently used for testing file-transfer]++- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command+{+ CDVFilesystemURL* localURL = [self fileSystemURLforArg:command.arguments[0]];++ NSString* fsPath = [self filesystemPathForURL:localURL];+ CDVPluginResult* result;+ if (fsPath) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:fsPath];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot resolve URL to a file"];+ }+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVLocalFilesystem.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVLocalFilesystem.hnew file mode 100644index 000000000..a0186c853--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVLocalFilesystem.h@@ -0,0 +1,32 @@+/*+ 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 "CDVFile.h"++@interface CDVLocalFilesystem : NSObject<CDVFileSystem> {+ NSString *_name;+ NSString *_fsRoot;+}++- (id) initWithName:(NSString *)name root:(NSString *)fsRoot;++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath;++@property (nonatomic,strong) NSString *fsRoot;++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVLocalFilesystem.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVLocalFilesystem.mnew file mode 100644index 000000000..c340ce0cc--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-file/CDVLocalFilesystem.m@@ -0,0 +1,750 @@+/*+ 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 "CDVFile.h"+#import "CDVLocalFilesystem.h"+#import <Cordova/CDV.h>+#import <MobileCoreServices/MobileCoreServices.h>+#import <sys/xattr.h>++@implementation CDVLocalFilesystem+@synthesize name=_name, fsRoot=_fsRoot, urlTransformer;++- (id) initWithName:(NSString *)name root:(NSString *)fsRoot+{+ if (self) {+ self.name = name;+ self.fsRoot = fsRoot;+ }+ return self;+}++/*+ * IN+ * NSString localURI+ * OUT+ * CDVPluginResult result containing a file or directoryEntry for the localURI, or an error if the+ * URI represents a non-existent path, or is unrecognized or otherwise malformed.+ */+- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url+{+ CDVPluginResult* result = nil;+ NSDictionary* entry = [self makeEntryForLocalURL:url];+ if (entry) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];+ } else {+ // return NOT_FOUND_ERR+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];+ }+ return result;+}+- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {+ NSString *path = [self filesystemPathForURL:url];+ NSFileManager* fileMgr = [[NSFileManager alloc] init];+ BOOL isDir = NO;+ // see if exists and is file or dir+ BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&isDir];+ if (bExists) {+ return [self makeEntryForPath:url.fullPath isDirectory:isDir];+ } else {+ return nil;+ }+}+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir+{+ NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];+ NSString* lastPart = [[self stripQueryParametersFromPath:fullPath] lastPathComponent];+ if (isDir && ![fullPath hasSuffix:@"/"]) {+ fullPath = [fullPath stringByAppendingString:@"/"];+ }+ [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];+ [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];+ [dirEntry setObject:fullPath forKey:@"fullPath"];+ [dirEntry setObject:lastPart forKey:@"name"];+ [dirEntry setObject:self.name forKey: @"filesystemName"];++ NSURL* nativeURL = [NSURL fileURLWithPath:[self filesystemPathForFullPath:fullPath]];+ if (self.urlTransformer) {+ nativeURL = self.urlTransformer(nativeURL);+ }++ dirEntry[@"nativeURL"] = [nativeURL absoluteString];++ return dirEntry;+}++- (NSString *)stripQueryParametersFromPath:(NSString *)fullPath+{+ NSRange questionMark = [fullPath rangeOfString:@"?"];+ if (questionMark.location != NSNotFound) {+ return [fullPath substringWithRange:NSMakeRange(0,questionMark.location)];+ }+ return fullPath;+}++- (NSString *)filesystemPathForFullPath:(NSString *)fullPath+{+ NSString *path = nil;+ NSString *strippedFullPath = [self stripQueryParametersFromPath:fullPath];+ path = [NSString stringWithFormat:@"%@%@", self.fsRoot, strippedFullPath];+ if ([path length] > 1 && [path hasSuffix:@"/"]) {+ path = [path substringToIndex:([path length]-1)];+ }+ return path;+}+/*+ * IN+ * NSString localURI+ * OUT+ * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible+ * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,+ * or if the URL is malformed.+ * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).+ */+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url+{+ return [self filesystemPathForFullPath:url.fullPath];+}++- (CDVFilesystemURL *)URLforFullPath:(NSString *)fullPath+{+ if (fullPath) {+ NSString* escapedPath = [fullPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];+ if ([fullPath hasPrefix:@"/"]) {+ return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];+ }+ return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@/%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];+ }+ return nil;+}++- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path+{+ return [self URLforFullPath:[self fullPathForFileSystemPath:path]];++}++- (NSString *)normalizePath:(NSString *)rawPath+{+ // If this is an absolute path, the first path component will be '/'. Skip it if that's the case+ BOOL isAbsolutePath = [rawPath hasPrefix:@"/"];+ if (isAbsolutePath) {+ rawPath = [rawPath substringFromIndex:1];+ }+ NSMutableArray *components = [NSMutableArray arrayWithArray:[rawPath pathComponents]];+ for (int index = 0; index < [components count]; ++index) {+ if ([[components objectAtIndex:index] isEqualToString:@".."]) {+ [components removeObjectAtIndex:index];+ if (index > 0) {+ [components removeObjectAtIndex:index-1];+ --index;+ }+ }+ }++ if (isAbsolutePath) {+ return [NSString stringWithFormat:@"/%@", [components componentsJoinedByString:@"/"]];+ } else {+ return [components componentsJoinedByString:@"/"];+ }+++}++- (BOOL)valueForKeyIsNumber:(NSDictionary*)dict key:(NSString*)key+{+ BOOL bNumber = NO;+ NSObject* value = dict[key];+ if (value) {+ bNumber = [value isKindOfClass:[NSNumber class]];+ }+ return bNumber;+}++- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options+{+ CDVPluginResult* result = nil;+ BOOL bDirRequest = NO;+ BOOL create = NO;+ BOOL exclusive = NO;+ int errorCode = 0; // !!! risky - no error code currently defined for 0++ if ([self valueForKeyIsNumber:options key:@"create"]) {+ create = [(NSNumber*)[options valueForKey:@"create"] boolValue];+ }+ if ([self valueForKeyIsNumber:options key:@"exclusive"]) {+ exclusive = [(NSNumber*)[options valueForKey:@"exclusive"] boolValue];+ }+ if ([self valueForKeyIsNumber:options key:@"getDir"]) {+ // this will not exist for calls directly to getFile but will have been set by getDirectory before calling this method+ bDirRequest = [(NSNumber*)[options valueForKey:@"getDir"] boolValue];+ }+ // see if the requested path has invalid characters - should we be checking for more than just ":"?+ if ([requestedPath rangeOfString:@":"].location != NSNotFound) {+ errorCode = ENCODING_ERR;+ } else {+ // Build new fullPath for the requested resource.+ // We concatenate the two paths together, and then scan the resulting string to remove+ // parent ("..") references. Any parent references at the beginning of the string are+ // silently removed.+ NSString *combinedPath = [baseURI.fullPath stringByAppendingPathComponent:requestedPath];+ combinedPath = [self normalizePath:combinedPath];+ CDVFilesystemURL* requestedURL = [self URLforFullPath:combinedPath];++ NSFileManager* fileMgr = [[NSFileManager alloc] init];+ BOOL bIsDir;+ BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:requestedURL] isDirectory:&bIsDir];+ if (bExists && (create == NO) && (bIsDir == !bDirRequest)) {+ // path exists and is not of requested type - return TYPE_MISMATCH_ERR+ errorCode = TYPE_MISMATCH_ERR;+ } else if (!bExists && (create == NO)) {+ // path does not exist and create is false - return NOT_FOUND_ERR+ errorCode = NOT_FOUND_ERR;+ } else if (bExists && (create == YES) && (exclusive == YES)) {+ // file/dir already exists and exclusive and create are both true - return PATH_EXISTS_ERR+ errorCode = PATH_EXISTS_ERR;+ } else {+ // if bExists and create == YES - just return data+ // if bExists and create == NO - just return data+ // if !bExists and create == YES - create and return data+ BOOL bSuccess = YES;+ NSError __autoreleasing* pError = nil;+ if (!bExists && (create == YES)) {+ if (bDirRequest) {+ // create the dir+ bSuccess = [fileMgr createDirectoryAtPath:[self filesystemPathForURL:requestedURL] withIntermediateDirectories:NO attributes:nil error:&pError];+ } else {+ // create the empty file+ bSuccess = [fileMgr createFileAtPath:[self filesystemPathForURL:requestedURL] contents:nil attributes:nil];+ }+ }+ if (!bSuccess) {+ errorCode = ABORT_ERR;+ if (pError) {+ NSLog(@"error creating directory: %@", [pError localizedDescription]);+ }+ } else {+ // NSLog(@"newly created file/dir (%@) exists: %d", reqFullPath, [fileMgr fileExistsAtPath:reqFullPath]);+ // file existed or was created+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:requestedURL.fullPath isDirectory:bDirRequest]];+ }+ } // are all possible conditions met?+ }++ if (errorCode > 0) {+ // create error callback+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];+ }+ return result;++}++- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI+{+ CDVPluginResult* result = nil;+ CDVFilesystemURL *newURI = nil;+ if ([localURI.fullPath isEqualToString:@""]) {+ // return self+ newURI = localURI;+ } else {+ newURI = [CDVFilesystemURL fileSystemURLWithURL:[localURI.url URLByDeletingLastPathComponent]]; /* TODO: UGLY - FIX */+ }+ NSFileManager* fileMgr = [[NSFileManager alloc] init];+ BOOL bIsDir;+ BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:newURI] isDirectory:&bIsDir];+ if (bExists) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:newURI.fullPath isDirectory:bIsDir]];+ } else {+ // invalid path or file does not exist+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];+ }+ return result;+}++- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options+{+ BOOL ok = NO;++ NSString* filePath = [self filesystemPathForURL:localURI];+ // we only care about this iCloud key for now.+ // set to 1/true to skip backup, set to 0/false to back it up (effectively removing the attribute)+ NSString* iCloudBackupExtendedAttributeKey = @"com.apple.MobileBackup";+ id iCloudBackupExtendedAttributeValue = [options objectForKey:iCloudBackupExtendedAttributeKey];++ if ((iCloudBackupExtendedAttributeValue != nil) && [iCloudBackupExtendedAttributeValue isKindOfClass:[NSNumber class]]) {+ if (IsAtLeastiOSVersion(@"5.1")) {+ NSURL* url = [NSURL fileURLWithPath:filePath];+ NSError* __autoreleasing error = nil;++ ok = [url setResourceValue:[NSNumber numberWithBool:[iCloudBackupExtendedAttributeValue boolValue]] forKey:NSURLIsExcludedFromBackupKey error:&error];+ } else { // below 5.1 (deprecated - only really supported in 5.01)+ u_int8_t value = [iCloudBackupExtendedAttributeValue intValue];+ if (value == 0) { // remove the attribute (allow backup, the default)+ ok = (removexattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], 0) == 0);+ } else { // set the attribute (skip backup)+ ok = (setxattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], &value, sizeof(value), 0, 0) == 0);+ }+ }+ }++ if (ok) {+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else {+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];+ }+}++/* remove the file or directory (recursively)+ * IN:+ * NSString* fullPath - the full path to the file or directory to be removed+ * NSString* callbackId+ * called from remove and removeRecursively - check all pubic api specific error conditions (dir not empty, etc) before calling+ */++- (CDVPluginResult*)doRemove:(NSString*)fullPath+{+ CDVPluginResult* result = nil;+ BOOL bSuccess = NO;+ NSError* __autoreleasing pError = nil;+ NSFileManager* fileMgr = [[NSFileManager alloc] init];++ @try {+ bSuccess = [fileMgr removeItemAtPath:fullPath error:&pError];+ if (bSuccess) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else {+ // see if we can give a useful error+ CDVFileError errorCode = ABORT_ERR;+ NSLog(@"error removing filesystem entry at %@: %@", fullPath, [pError localizedDescription]);+ if ([pError code] == NSFileNoSuchFileError) {+ errorCode = NOT_FOUND_ERR;+ } else if ([pError code] == NSFileWriteNoPermissionError) {+ errorCode = NO_MODIFICATION_ALLOWED_ERR;+ }++ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];+ }+ } @catch(NSException* e) { // NSInvalidArgumentException if path is . or ..+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:SYNTAX_ERR];+ }++ return result;+}++- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI+{+ NSString *fileSystemPath = [self filesystemPathForURL:localURI];++ NSFileManager* fileMgr = [[NSFileManager alloc] init];+ BOOL bIsDir = NO;+ BOOL bExists = [fileMgr fileExistsAtPath:fileSystemPath isDirectory:&bIsDir];+ if (!bExists) {+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];+ }+ if (bIsDir && ([[fileMgr contentsOfDirectoryAtPath:fileSystemPath error:nil] count] != 0)) {+ // dir is not empty+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];+ }+ return [self doRemove:fileSystemPath];+}++- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI+{+ NSString *fileSystemPath = [self filesystemPathForURL:localURI];+ return [self doRemove:fileSystemPath];+}++/*+ * IN+ * NSString localURI+ * OUT+ * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible+ * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,+ * or if the URL is malformed.+ * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).+ */+- (NSString *)fullPathForFileSystemPath:(NSString *)fsPath+{+ if ([fsPath hasPrefix:self.fsRoot]) {+ return [fsPath substringFromIndex:[self.fsRoot length]];+ }+ return nil;+}+++- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI+{+ NSFileManager* fileMgr = [[NSFileManager alloc] init];+ NSError* __autoreleasing error = nil;+ NSString *fileSystemPath = [self filesystemPathForURL:localURI];++ NSArray* contents = [fileMgr contentsOfDirectoryAtPath:fileSystemPath error:&error];++ if (contents) {+ NSMutableArray* entries = [NSMutableArray arrayWithCapacity:1];+ if ([contents count] > 0) {+ // create an Entry (as JSON) for each file/dir+ for (NSString* name in contents) {+ // see if is dir or file+ NSString* entryPath = [fileSystemPath stringByAppendingPathComponent:name];+ BOOL bIsDir = NO;+ [fileMgr fileExistsAtPath:entryPath isDirectory:&bIsDir];+ NSDictionary* entryDict = [self makeEntryForPath:[self fullPathForFileSystemPath:entryPath] isDirectory:bIsDir];+ [entries addObject:entryDict];+ }+ }+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:entries];+ } else {+ // assume not found but could check error for more specific error conditions+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];+ }+}++- (unsigned long long)truncateFile:(NSString*)filePath atPosition:(unsigned long long)pos+{+ unsigned long long newPos = 0UL;++ NSFileHandle* file = [NSFileHandle fileHandleForWritingAtPath:filePath];++ if (file) {+ [file truncateFileAtOffset:(unsigned long long)pos];+ newPos = [file offsetInFile];+ [file synchronizeFile];+ [file closeFile];+ }+ return newPos;+}++- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos+{+ unsigned long long newPos = [self truncateFile:[self filesystemPathForURL:localURI] atPosition:pos];+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)newPos];+}++- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend+{+ NSString *filePath = [self filesystemPathForURL:localURL];++ CDVPluginResult* result = nil;+ CDVFileError errCode = INVALID_MODIFICATION_ERR;+ int bytesWritten = 0;++ if (filePath) {+ NSOutputStream* fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:shouldAppend];+ if (fileStream) {+ NSUInteger len = [encData length];+ if (len == 0) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:(double)len];+ } else {+ [fileStream open];++ bytesWritten = (int)[fileStream write:[encData bytes] maxLength:len];++ [fileStream close];+ if (bytesWritten > 0) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:bytesWritten];+ // } else {+ // can probably get more detailed error info via [fileStream streamError]+ // errCode already set to INVALID_MODIFICATION_ERR;+ // bytesWritten = 0; // may be set to -1 on error+ }+ }+ } // else fileStream not created return INVALID_MODIFICATION_ERR+ } else {+ // invalid filePath+ errCode = NOT_FOUND_ERR;+ }+ if (!result) {+ // was an error+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errCode];+ }+ return result;+}++/**+ * Helper function to check to see if the user attempted to copy an entry into its parent without changing its name,+ * or attempted to copy a directory into a directory that it contains directly or indirectly.+ *+ * IN:+ * NSString* srcDir+ * NSString* destinationDir+ * OUT:+ * YES copy/ move is allows+ * NO move is onto itself+ */+- (BOOL)canCopyMoveSrc:(NSString*)src ToDestination:(NSString*)dest+{+ // This weird test is to determine if we are copying or moving a directory into itself.+ // Copy /Documents/myDir to /Documents/myDir-backup is okay but+ // Copy /Documents/myDir to /Documents/myDir/backup not okay+ BOOL copyOK = YES;+ NSRange range = [dest rangeOfString:src];++ if (range.location != NSNotFound) {+ NSRange testRange = {range.length - 1, ([dest length] - range.length)};+ NSRange resultRange = [dest rangeOfString:@"/" options:0 range:testRange];+ if (resultRange.location != NSNotFound) {+ copyOK = NO;+ }+ }+ return copyOK;+}++- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback+{+ NSFileManager *fileMgr = [[NSFileManager alloc] init];+ NSString *destRootPath = [self filesystemPathForURL:destURL];+ BOOL bDestIsDir = NO;+ BOOL bDestExists = [fileMgr fileExistsAtPath:destRootPath isDirectory:&bDestIsDir];++ NSString *newFileSystemPath = [destRootPath stringByAppendingPathComponent:newName];+ NSString *newFullPath = [self fullPathForFileSystemPath:newFileSystemPath];++ BOOL bNewIsDir = NO;+ BOOL bNewExists = [fileMgr fileExistsAtPath:newFileSystemPath isDirectory:&bNewIsDir];++ CDVPluginResult *result = nil;+ int errCode = 0;++ if (!bDestExists) {+ // the destination root does not exist+ errCode = NOT_FOUND_ERR;+ }++ else if ([srcFs isKindOfClass:[CDVLocalFilesystem class]]) {+ /* Same FS, we can shortcut with NSFileManager operations */+ NSString *srcFullPath = [srcFs filesystemPathForURL:srcURL];++ BOOL bSrcIsDir = NO;+ BOOL bSrcExists = [fileMgr fileExistsAtPath:srcFullPath isDirectory:&bSrcIsDir];++ if (!bSrcExists) {+ // the source does not exist+ errCode = NOT_FOUND_ERR;+ } else if ([newFileSystemPath isEqualToString:srcFullPath]) {+ // source and destination can not be the same+ errCode = INVALID_MODIFICATION_ERR;+ } else if (bSrcIsDir && (bNewExists && !bNewIsDir)) {+ // can't copy/move dir to file+ errCode = INVALID_MODIFICATION_ERR;+ } else { // no errors yet+ NSError* __autoreleasing error = nil;+ BOOL bSuccess = NO;+ if (bCopy) {+ if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {+ // can't copy dir into self+ errCode = INVALID_MODIFICATION_ERR;+ } else if (bNewExists) {+ // the full destination should NOT already exist if a copy+ errCode = PATH_EXISTS_ERR;+ } else {+ bSuccess = [fileMgr copyItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];+ }+ } else { // move+ // iOS requires that destination must not exist before calling moveTo+ // is W3C INVALID_MODIFICATION_ERR error if destination dir exists and has contents+ //+ if (!bSrcIsDir && (bNewExists && bNewIsDir)) {+ // can't move a file to directory+ errCode = INVALID_MODIFICATION_ERR;+ } else if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {+ // can't move a dir into itself+ errCode = INVALID_MODIFICATION_ERR;+ } else if (bNewExists) {+ if (bNewIsDir && ([[fileMgr contentsOfDirectoryAtPath:newFileSystemPath error:NULL] count] != 0)) {+ // can't move dir to a dir that is not empty+ errCode = INVALID_MODIFICATION_ERR;+ newFileSystemPath = nil; // so we won't try to move+ } else {+ // remove destination so can perform the moveItemAtPath+ bSuccess = [fileMgr removeItemAtPath:newFileSystemPath error:NULL];+ if (!bSuccess) {+ errCode = INVALID_MODIFICATION_ERR; // is this the correct error?+ newFileSystemPath = nil;+ }+ }+ } else if (bNewIsDir && [newFileSystemPath hasPrefix:srcFullPath]) {+ // can't move a directory inside itself or to any child at any depth;+ errCode = INVALID_MODIFICATION_ERR;+ newFileSystemPath = nil;+ }++ if (newFileSystemPath != nil) {+ bSuccess = [fileMgr moveItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];+ }+ }+ if (bSuccess) {+ // should verify it is there and of the correct type???+ NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:bSrcIsDir];+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];+ } else {+ if (error) {+ if (([error code] == NSFileReadUnknownError) || ([error code] == NSFileReadTooLargeError)) {+ errCode = NOT_READABLE_ERR;+ } else if ([error code] == NSFileWriteOutOfSpaceError) {+ errCode = QUOTA_EXCEEDED_ERR;+ } else if ([error code] == NSFileWriteNoPermissionError) {+ errCode = NO_MODIFICATION_ALLOWED_ERR;+ }+ }+ }+ }+ } else {+ // Need to copy the hard way+ [srcFs readFileAtURL:srcURL start:0 end:-1 callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {+ CDVPluginResult* result = nil;+ if (data != nil) {+ BOOL bSuccess = [data writeToFile:newFileSystemPath atomically:YES];+ if (bSuccess) {+ // should verify it is there and of the correct type???+ NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:NO];+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ABORT_ERR];+ }+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];+ }+ callback(result);+ }];+ return; // Async IO; return without callback.+ }+ if (result == nil) {+ if (!errCode) {+ errCode = INVALID_MODIFICATION_ERR; // Catch-all default+ }+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errCode];+ }+ callback(result);+}++/* helper function to get the mimeType from the file extension+ * IN:+ * NSString* fullPath - filename (may include path)+ * OUT:+ * NSString* the mime type as type/subtype. nil if not able to determine+ */++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath+{+ NSString* mimeType = nil;++ if (fullPath) {+ CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);+ if (typeId) {+ mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);+ if (!mimeType) {+ // special case for m4a+ if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {+ mimeType = @"audio/mp4";+ } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {+ mimeType = @"audio/wav";+ } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {+ mimeType = @"text/css";+ }+ }+ CFRelease(typeId);+ }+ }+ return mimeType;+}++- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback+{+ NSString *path = [self filesystemPathForURL:localURL];++ NSString* mimeType = [CDVLocalFilesystem getMimeTypeFromPath:path];+ if (mimeType == nil) {+ mimeType = @"*/*";+ }+ NSFileHandle* file = [NSFileHandle fileHandleForReadingAtPath:path];+ if (start > 0) {+ [file seekToFileOffset:start];+ }++ NSData* readData;+ if (end < 0) {+ readData = [file readDataToEndOfFile];+ } else {+ readData = [file readDataOfLength:(end - start)];+ }+ [file closeFile];++ callback(readData, mimeType, readData != nil ? NO_ERROR : NOT_FOUND_ERR);+}++- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback+{+ NSString *path = [self filesystemPathForURL:localURL];+ CDVPluginResult *result;+ NSFileManager* fileMgr = [[NSFileManager alloc] init];++ NSError* __autoreleasing error = nil;+ NSDictionary* fileAttrs = [fileMgr attributesOfItemAtPath:path error:&error];++ if (fileAttrs) {++ // create dictionary of file info+ NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];++ [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];+ [fileInfo setObject:[self mimeTypeForFileAtPath: path] forKey:@"type"];+ [fileInfo setObject:[path lastPathComponent] forKey:@"name"];++ // Ensure that directories (and other non-regular files) report size of 0+ unsigned long long size = ([fileAttrs fileType] == NSFileTypeRegular ? [fileAttrs fileSize] : 0);+ [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:size] forKey:@"size"];++ NSDate* modDate = [fileAttrs fileModificationDate];+ if (modDate) {+ [fileInfo setObject:[NSNumber numberWithDouble:[modDate timeIntervalSince1970] * 1000] forKey:@"lastModifiedDate"];+ }++ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo];++ } else {+ // didn't get fileAttribs+ CDVFileError errorCode = ABORT_ERR;+ NSLog(@"error getting metadata: %@", [error localizedDescription]);+ if ([error code] == NSFileNoSuchFileError || [error code] == NSFileReadNoSuchFileError) {+ errorCode = NOT_FOUND_ERR;+ }+ // log [NSNumber numberWithDouble: theMessage] objCtype to see what it returns+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errorCode];+ }++ callback(result);+}++// fix errors that base on Alexsander Akers from http://stackoverflow.com/a/5998683/2613194+- (NSString*) mimeTypeForFileAtPath: (NSString *) path {+ if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {+ return nil;+ }++ CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);+ CFStringRef mimeType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);+ CFRelease(UTI);++ if (!mimeType) {+ return @"application/octet-stream";+ }+ return (__bridge NSString *)mimeType;+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Resources/appbeep.wav b/cordova/platforms/ios/TagSpaces Beta/Resources/appbeep.wavnew file mode 100644index 000000000..24a13d40eBinary files /dev/null and b/cordova/platforms/ios/TagSpaces Beta/Resources/appbeep.wav differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Scripts/copy-www-build-step.sh b/cordova/platforms/ios/TagSpaces Beta/Scripts/copy-www-build-step.shnew file mode 100755index 000000000..ba0a1b47d--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Scripts/copy-www-build-step.sh@@ -0,0 +1,63 @@+#!/bin/sh+#+# 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.+#+#+# This script copies the www directory into the Xcode project.+#+# This script should not be called directly.+# It is called as a build step from Xcode.++SRC_DIR="www"+DST_DIR="$BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME"+DST_DIR_WWW="$DST_DIR/www"+COPY_HIDDEN=+ORIG_IFS=$IFS+IFS=$(echo -en "\n\b")++if [[ -z "$BUILT_PRODUCTS_DIR" ]]; then+ echo "The script is meant to be run as an Xcode build step and relies on env variables set by Xcode."+ exit 1+fi++if [[ ! -e "$SRC_DIR" ]]; then+ echo "error: Path does not exist: $SRC_DIR"+ exit 2+fi++rm -rf "$DST_DIR_WWW"++# Copy www dir recursively+CODE=+if [[ -n $COPY_HIDDEN ]]; then+ rsync -Lra "$SRC_DIR" "$DST_DIR"+ CODE=$?+else+ rsync -Lra --exclude="- .*" "$SRC_DIR" "$DST_DIR"+ CODE=$?+fi++if [ $CODE -ne 0 ]; then+ echo "error: Error occurred on copying www. Code $CODE"+ exit 3+fi++# Copy the config.xml file.+cp -f "${PROJECT_FILE_PATH%.xcodeproj}/config.xml" "$DST_DIR"++IFS=$ORIG_IFSdiff --git a/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Info.plist b/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Info.plistnew file mode 100644index 000000000..476adf9c5--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Info.plist@@ -0,0 +1,56 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en_US</string>+ <key>CFBundleDisplayName</key>+ <string>TagSpaces Beta</string>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIdentifier</key>+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>$(PRODUCT_NAME)</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0.0</string>+ <key>CFBundleSignature</key>+ <string>????</string>+ <key>CFBundleVersion</key>+ <string>1.0.0</string>+ <key>LSRequiresIPhoneOS</key>+ <true/>+ <key>NSMainNibFile</key>+ <string/>+ <key>NSMainNibFile~ipad</key>+ <string/>+ <key>UIRequiresFullScreen</key>+ <true/>+ <key>UISupportedInterfaceOrientations</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationLandscapeRight</string>+ </array>+ <key>UISupportedInterfaceOrientations~ipad</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationPortraitUpsideDown</string>+ <string>UIInterfaceOrientationLandscapeRight</string>+ </array>+ <key>NSAppTransportSecurity</key>+ <dict>+ <key>NSAllowsArbitraryLoads</key>+ <true/>+ </dict>+ <key>UIBackgroundModes</key>+ <array>+ <string>audio</string>+ </array>+</dict>+</plist>\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Prefix.pch b/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Prefix.pchnew file mode 100644index 000000000..7a3e03beb--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Prefix.pch@@ -0,0 +1,26 @@+/*+ 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.+ */+//+// Prefix header for all source files of the 'TagSpaces Beta' target in the 'TagSpaces Beta' project+//++#ifdef __OBJC__+ #import <Foundation/Foundation.h>+ #import <UIKit/UIKit.h>+#endifdiff --git a/cordova/platforms/ios/TagSpaces Beta/config.xml b/cordova/platforms/ios/TagSpaces Beta/config.xmlnew file mode 100755index 000000000..23ca76da5--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/config.xml@@ -0,0 +1,73 @@+<?xml version='1.0' encoding='utf-8'?>+<widget id="org.tagspaces.mobile" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">+ <feature name="LocalStorage">+ <param name="ios-package" value="CDVLocalStorage" />+ </feature>+ <feature name="Console">+ <param name="ios-package" value="CDVLogger" />+ <param name="onload" value="true" />+ </feature>+ <feature name="HandleOpenUrl">+ <param name="ios-package" value="CDVHandleOpenURL" />+ <param name="onload" value="true" />+ </feature>+ <feature name="IntentAndNavigationFilter">+ <param name="ios-package" value="CDVIntentAndNavigationFilter" />+ <param name="onload" value="true" />+ </feature>+ <feature name="GestureHandler">+ <param name="ios-package" value="CDVGestureHandler" />+ <param name="onload" value="true" />+ </feature>+ <feature name="Device">+ <param name="ios-package" value="CDVDevice" />+ </feature>+ <feature name="BackgroundMode">+ <param name="ios-package" onload="true" value="APPBackgroundMode" />+ <param name="onload" value="true" />+ </feature>+ <feature name="Camera">+ <param name="ios-package" value="CDVCamera" />+ </feature>+ <feature name="File">+ <param name="ios-package" value="CDVFile" />+ <param name="onload" value="true" />+ </feature>+ <feature name="FileOpener2">+ <param name="ios-package" value="FileOpener2" />+ </feature>+ <name>TagSpaces Beta</name>+ <description>+ Offline file organizer and browser with tagging support.+ </description>+ <author email="[email protected]" href="https://tagspaces.org">+ TagSpaces UG (haftungsbeschraenkt)+ </author>+ <content src="index.html" />+ <access origin="*" />+ <allow-intent href="http://*/*" />+ <allow-intent href="https://*/*" />+ <allow-intent href="tel:*" />+ <allow-intent href="sms:*" />+ <allow-intent href="mailto:*" />+ <allow-intent href="geo:*" />+ <allow-intent href="itms:*" />+ <allow-intent href="itms-apps:*" />+ <preference name="AllowInlineMediaPlayback" value="false" />+ <preference name="BackupWebStorage" value="cloud" />+ <preference name="DisallowOverscroll" value="false" />+ <preference name="EnableViewportScale" value="false" />+ <preference name="KeyboardDisplayRequiresUserAction" value="true" />+ <preference name="MediaPlaybackRequiresUserAction" value="false" />+ <preference name="SuppressesIncrementalRendering" value="false" />+ <preference name="SuppressesLongPressGesture" value="false" />+ <preference name="Suppresses3DTouchGesture" value="false" />+ <preference name="GapBetweenPages" value="0" />+ <preference name="PageLength" value="0" />+ <preference name="PaginationBreakingMode" value="page" />+ <preference name="PaginationMode" value="unpaginated" />+ <preference name="CameraUsesGeolocation" value="false" />+ <preference name="AndroidPersistentFileLocation" value="Compatibility" />+ <preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />+ <preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />+</widget>diff --git a/cordova/platforms/ios/TagSpaces Beta/main.m b/cordova/platforms/ios/TagSpaces Beta/main.mnew file mode 100644index 000000000..bf40fbbf3--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/main.m@@ -0,0 +1,35 @@+/*+ 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.+ */+//+// main.m+// TagSpaces Beta+//+// Created by ___FULLUSERNAME___ on ___DATE___.+// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.+//++#import <UIKit/UIKit.h>++int main(int argc, char* argv[])+{+ @autoreleasepool {+ int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");+ return retVal;+ }+}diff --git a/cordova/platforms/ios/cordova/Api.js b/cordova/platforms/ios/cordova/Api.jsnew file mode 100755index 000000000..e45b7822c--- /dev/null+++ b/cordova/platforms/ios/cordova/Api.js@@ -0,0 +1,715 @@+/**+ 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.+*/++/* jslint node: true */++var fs = require('fs');+var path = require('path');+var unorm = require('unorm');+var projectFile = require('./lib/projectFile');+var check_reqs = require('./lib/check_reqs');+var CordovaError = require('cordova-common').CordovaError;+var CordovaLogger = require('cordova-common').CordovaLogger;+var events = require('cordova-common').events;+var PluginManager = require('cordova-common').PluginManager;+var Q = require('q');+var util = require('util');+var xcode = require('xcode');+var ConfigParser = require('cordova-common').ConfigParser;++function setupEvents (externalEventEmitter) {+ if (externalEventEmitter) {+ // This will make the platform internal events visible outside+ events.forwardEventsTo(externalEventEmitter);+ } else {+ // There is no logger if external emitter is not present,+ // so attach a console logger+ CordovaLogger.get().subscribe(events);+ }+}++/**+ * Creates a new PlatformApi instance.+ *+ * @param {String} [platform] Platform name, used for backward compatibility+ * w/ PlatformPoly (CordovaLib).+ * @param {String} [platformRootDir] Platform root location, used for backward+ * compatibility w/ PlatformPoly (CordovaLib).+ * @param {EventEmitter} [events] An EventEmitter instance that will be used for+ * logging purposes. If no EventEmitter provided, all events will be logged to+ * console+ */+function Api (platform, platformRootDir, events) {+ // 'platform' property is required as per PlatformApi spec+ this.platform = platform || 'ios';+ this.root = platformRootDir || path.resolve(__dirname, '..');++ setupEvents(events);++ var xcodeProjDir;+ var xcodeCordovaProj;++ try {++ var xcodeProjDir_array = fs.readdirSync(this.root).filter(function (e) { return e.match(/\.xcodeproj$/i); });+ if (xcodeProjDir_array.length > 1) {+ for (var x = 0; x < xcodeProjDir_array.length; x++) {+ if (xcodeProjDir_array[x].substring(0, 2) === '._') {+ xcodeProjDir_array.splice(x, 1);+ }+ }+ }+ xcodeProjDir = xcodeProjDir_array[0];++ if (!xcodeProjDir) {+ throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');+ }++ var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep) + 1, xcodeProjDir.indexOf('.xcodeproj'));+ xcodeCordovaProj = path.join(this.root, cordovaProjName);+ } catch (e) {+ throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');+ }++ this.locations = {+ root: this.root,+ www: path.join(this.root, 'www'),+ platformWww: path.join(this.root, 'platform_www'),+ configXml: path.join(xcodeCordovaProj, 'config.xml'),+ defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'),+ pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'),+ xcodeProjDir: path.join(this.root, xcodeProjDir),+ xcodeCordovaProj: xcodeCordovaProj+ };+}++/**+ * Creates platform in a specified directory.+ *+ * @param {String} destination Destination directory, where install platform to+ * @param {ConfigParser} [config] ConfigParser instance, used to retrieve+ * project creation options, such as package id and project name.+ * @param {Object} [options] An options object. The most common options are:+ * @param {String} [options.customTemplate] A path to custom template, that+ * should override the default one from platform.+ * @param {Boolean} [options.link] Flag that indicates that platform's+ * sources will be linked to installed platform instead of copying.+ * @param {EventEmitter} [events] An EventEmitter instance that will be used for+ * logging purposes. If no EventEmitter provided, all events will be logged to+ * console+ *+ * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi+ * instance or rejected with CordovaError.+ */+Api.createPlatform = function (destination, config, options, events) {+ setupEvents(events);++ // CB-6992 it is necessary to normalize characters+ // because node and shell scripts handles unicode symbols differently+ // We need to normalize the name to NFD form since iOS uses NFD unicode form+ var name = unorm.nfd(config.name());+ var result;+ try {+ result = require('../../../lib/create')+ .createProject(destination, config.getAttribute('ios-CFBundleIdentifier') || config.packageName(), name, options, config)+ .then(function () {+ // after platform is created we return Api instance based on new Api.js location+ // This is required to correctly resolve paths in the future api calls+ var PlatformApi = require(path.resolve(destination, 'cordova/Api'));+ return new PlatformApi('ios', destination, events);+ });+ } catch (e) {+ events.emit('error', 'createPlatform is not callable from the iOS project API.');+ throw e;+ }+ return result;+};++/**+ * Updates already installed platform.+ *+ * @param {String} destination Destination directory, where platform installed+ * @param {Object} [options] An options object. The most common options are:+ * @param {String} [options.customTemplate] A path to custom template, that+ * should override the default one from platform.+ * @param {Boolean} [options.link] Flag that indicates that platform's+ * sources will be linked to installed platform instead of copying.+ * @param {EventEmitter} [events] An EventEmitter instance that will be used for+ * logging purposes. If no EventEmitter provided, all events will be logged to+ * console+ *+ * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi+ * instance or rejected with CordovaError.+ */+Api.updatePlatform = function (destination, options, events) {+ setupEvents(events);++ var result;+ try {+ result = require('../../../lib/create')+ .updateProject(destination, options)+ .then(function () {+ var PlatformApi = require(path.resolve(destination, 'cordova/Api'));+ return new PlatformApi('ios', destination, events);+ });+ } catch (e) {+ events.emit('error', 'updatePlatform is not callable from the iOS project API, you will need to do this manually.');+ throw e;+ }+ return result;+};++/**+ * Gets a CordovaPlatform object, that represents the platform structure.+ *+ * @return {CordovaPlatform} A structure that contains the description of+ * platform's file structure and other properties of platform.+ */+Api.prototype.getPlatformInfo = function () {+ var result = {};+ result.locations = this.locations;+ result.root = this.root;+ result.name = this.platform;+ result.version = require('./version');+ result.projectConfig = new ConfigParser(this.locations.configXml);++ return result;+};++/**+ * Updates installed platform with provided www assets and new app+ * configuration. This method is required for CLI workflow and will be called+ * each time before build, so the changes, made to app configuration and www+ * code, will be applied to platform.+ *+ * @param {CordovaProject} cordovaProject A CordovaProject instance, that defines a+ * project structure and configuration, that should be applied to platform+ * (contains project's www location and ConfigParser instance for project's+ * config).+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError instance.+ */+Api.prototype.prepare = function (cordovaProject) {+ cordovaProject.projectConfig = new ConfigParser(cordovaProject.locations.rootConfigXml || cordovaProject.projectConfig.path);++ return require('./lib/prepare').prepare.call(this, cordovaProject);+};++/**+ * Installs a new plugin into platform. It doesn't resolves plugin dependencies.+ *+ * @param {PluginInfo} plugin A PluginInfo instance that represents plugin+ * that will be installed.+ * @param {Object} installOptions An options object. Possible options below:+ * @param {Boolean} installOptions.link: Flag that specifies that plugin+ * sources will be symlinked to app's directory instead of copying (if+ * possible).+ * @param {Object} installOptions.variables An object that represents+ * variables that will be used to install plugin. See more details on plugin+ * variables in documentation:+ * https://cordova.apache.org/docs/en/4.0.0/plugin_ref_spec.md.html+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError instance.+ */+Api.prototype.addPlugin = function (plugin, installOptions) {++ var xcodeproj = projectFile.parse(this.locations);+ var self = this;++ installOptions = installOptions || {};+ installOptions.variables = installOptions.variables || {};+ // Add PACKAGE_NAME variable into vars+ if (!installOptions.variables.PACKAGE_NAME) {+ installOptions.variables.PACKAGE_NAME = xcodeproj.getPackageName();+ }++ return PluginManager.get(self.platform, self.locations, xcodeproj)+ .addPlugin(plugin, installOptions)+ .then(function () {+ if (plugin != null) {+ var headerTags = plugin.getHeaderFiles(self.platform);+ var bridgingHeaders = headerTags.filter(function (obj) {+ return (obj.type === 'BridgingHeader');+ });+ if (bridgingHeaders.length > 0) {+ var project_dir = self.locations.root;+ var project_name = self.locations.xcodeCordovaProj.split('/').pop();+ var BridgingHeader = require('./lib/BridgingHeader').BridgingHeader;+ var bridgingHeaderFile = new BridgingHeader(path.join(project_dir, project_name, 'Bridging-Header.h'));+ events.emit('verbose', 'Adding Bridging-Headers since the plugin contained <header-file> with type="BridgingHeader"');+ bridgingHeaders.forEach(function (obj) {+ var bridgingHeaderPath = path.basename(obj.src);+ bridgingHeaderFile.addHeader(plugin.id, bridgingHeaderPath);+ });+ bridgingHeaderFile.write();+ }+ }+ })+ .then(function () {+ if (plugin != null) {+ var podSpecs = plugin.getPodSpecs ? plugin.getPodSpecs(self.platform) : [];+ var frameworkTags = plugin.getFrameworks(self.platform);+ var frameworkPods = frameworkTags.filter(function (obj) {+ return (obj.type === 'podspec');+ });+ return self.addPodSpecs(plugin, podSpecs, frameworkPods);+ }+ })+ // CB-11022 return non-falsy value to indicate+ // that there is no need to run prepare after+ .thenResolve(true);+};++/**+ * Removes an installed plugin from platform.+ *+ * Since method accepts PluginInfo instance as input parameter instead of plugin+ * id, caller shoud take care of managing/storing PluginInfo instances for+ * future uninstalls.+ *+ * @param {PluginInfo} plugin A PluginInfo instance that represents plugin+ * that will be installed.+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError instance.+ */+Api.prototype.removePlugin = function (plugin, uninstallOptions) {+ var xcodeproj = projectFile.parse(this.locations);+ var self = this;++ return PluginManager.get(self.platform, self.locations, xcodeproj)+ .removePlugin(plugin, uninstallOptions)+ .then(function () {+ if (plugin != null) {+ var headerTags = plugin.getHeaderFiles(self.platform);+ var bridgingHeaders = headerTags.filter(function (obj) {+ return (obj.type === 'BridgingHeader');+ });+ if (bridgingHeaders.length > 0) {+ var project_dir = self.locations.root;+ var project_name = self.locations.xcodeCordovaProj.split('/').pop();+ var BridgingHeader = require('./lib/BridgingHeader').BridgingHeader;+ var bridgingHeaderFile = new BridgingHeader(path.join(project_dir, project_name, 'Bridging-Header.h'));+ events.emit('verbose', 'Removing Bridging-Headers since the plugin contained <header-file> with type="BridgingHeader"');+ bridgingHeaders.forEach(function (obj) {+ var bridgingHeaderPath = path.basename(obj.src);+ bridgingHeaderFile.removeHeader(plugin.id, bridgingHeaderPath);+ });+ bridgingHeaderFile.write();+ }+ }+ })+ .then(function () {+ if (plugin != null) {+ var podSpecs = plugin.getPodSpecs ? plugin.getPodSpecs(self.platform) : [];+ var frameworkTags = plugin.getFrameworks(self.platform);+ var frameworkPods = frameworkTags.filter(function (obj) {+ return (obj.type === 'podspec');+ });+ return self.removePodSpecs(plugin, podSpecs, frameworkPods);+ }+ })+ // CB-11022 return non-falsy value to indicate+ // that there is no need to run prepare after+ .thenResolve(true);+};++/**+ * adding CocoaPods libraries+ *+ * @param {PluginInfo} plugin A PluginInfo instance that represents plugin+ * that will be installed.+ * @param {Object} podSpecs: the return value of plugin.getPodSpecs(self.platform)+ * @param {Object} frameworkPods: framework tags object with type === 'podspec'+ * @return {Promise} Return a promise+ */++Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods) {+ var self = this;++ var project_dir = self.locations.root;+ var project_name = self.locations.xcodeCordovaProj.split('/').pop();+ var minDeploymentTarget = self.getPlatformInfo().projectConfig.getPreference('deployment-target', 'ios');++ var Podfile = require('./lib/Podfile').Podfile;+ var PodsJson = require('./lib/PodsJson').PodsJson;+ var podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));+ var podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name, minDeploymentTarget);++ if (podSpecs.length) {+ events.emit('verbose', 'Adding pods since the plugin contained <podspecs>');+ podSpecs.forEach(function (obj) {+ // declarations+ Object.keys(obj.declarations).forEach(function (key) {+ if (obj.declarations[key] === 'true') {+ var declaration = Podfile.proofDeclaration(key);+ var podJson = {+ declaration: declaration+ };+ var val = podsjsonFile.getDeclaration(declaration);+ if (val) {+ podsjsonFile.incrementDeclaration(declaration);+ } else {+ podJson.count = 1;+ podsjsonFile.setJsonDeclaration(declaration, podJson);+ podfileFile.addDeclaration(podJson.declaration);+ }+ }+ });+ // sources+ Object.keys(obj.sources).forEach(function (key) {+ var podJson = {+ source: obj.sources[key].source+ };+ var val = podsjsonFile.getSource(key);+ if (val) {+ podsjsonFile.incrementSource(key);+ } else {+ podJson.count = 1;+ podsjsonFile.setJsonSource(key, podJson);+ podfileFile.addSource(podJson.source);+ }+ });+ // libraries+ Object.keys(obj.libraries).forEach(function (key) {+ var podJson = Object.assign({}, obj.libraries[key]);+ var val = podsjsonFile.getLibrary(key);+ if (val) {+ events.emit('warn', plugin.id + ' depends on ' + podJson.name + ', which may conflict with another plugin. ' + podJson.name + '@' + val.spec + ' is already installed and was not overwritten.');+ podsjsonFile.incrementLibrary(key);+ } else {+ podJson.count = 1;+ podsjsonFile.setJsonLibrary(key, podJson);+ podfileFile.addSpec(podJson.name, podJson);+ }+ });++ });+ }++ if (frameworkPods.length) {+ events.emit('warn', '"framework" tag with type "podspec" is deprecated and will be removed. Please use the "podspec" tag.');+ events.emit('verbose', 'Adding pods since the plugin contained <framework>(s) with type="podspec"');+ frameworkPods.forEach(function (obj) {+ var podJson = {+ name: obj.src,+ type: obj.type,+ spec: obj.spec+ };++ var val = podsjsonFile.getLibrary(podJson.name);+ if (val) { // found+ if (podJson.spec !== val.spec) { // exists, different spec, print warning+ events.emit('warn', plugin.id + ' depends on ' + podJson.name + '@' + podJson.spec + ', which conflicts with another plugin. ' + podJson.name + '@' + val.spec + ' is already installed and was not overwritten.');+ }+ // increment count, but don't add in Podfile because it already exists+ podsjsonFile.incrementLibrary(podJson.name);+ } else { // not found, write new+ podJson.count = 1;+ podsjsonFile.setJsonLibrary(podJson.name, podJson);+ // add to Podfile+ podfileFile.addSpec(podJson.name, podJson.spec);+ }+ });+ }++ if (podSpecs.length > 0 || frameworkPods.length > 0) {+ // now that all the pods have been processed, write to pods.json+ podsjsonFile.write();++ // only write and pod install if the Podfile changed+ if (podfileFile.isDirty()) {+ podfileFile.write();+ events.emit('verbose', 'Running `pod install` (to install plugins)');+ projectFile.purgeProjectFileCache(self.locations.root);++ return podfileFile.install(check_reqs.check_cocoapods)+ .then(function () {+ return self.setSwiftVersionForCocoaPodsLibraries(podsjsonFile);+ });+ } else {+ events.emit('verbose', 'Podfile unchanged, skipping `pod install`');+ }+ }+ return Q.when();+};++/**+ * removing CocoaPods libraries+ *+ * @param {PluginInfo} plugin A PluginInfo instance that represents plugin+ * that will be installed.+ * @param {Object} podSpecs: the return value of plugin.getPodSpecs(self.platform)+ * @param {Object} frameworkPods: framework tags object with type === 'podspec'+ * @return {Promise} Return a promise+ */++Api.prototype.removePodSpecs = function (plugin, podSpecs, frameworkPods) {+ var self = this;++ var project_dir = self.locations.root;+ var project_name = self.locations.xcodeCordovaProj.split('/').pop();++ var Podfile = require('./lib/Podfile').Podfile;+ var PodsJson = require('./lib/PodsJson').PodsJson;+ var podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));+ var podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name);++ if (podSpecs.length) {+ events.emit('verbose', 'Adding pods since the plugin contained <podspecs>');+ podSpecs.forEach(function (obj) {+ // declarations+ Object.keys(obj.declarations).forEach(function (key) {+ if (obj.declarations[key] === 'true') {+ var declaration = Podfile.proofDeclaration(key);+ var podJson = {+ declaration: declaration+ };+ var val = podsjsonFile.getDeclaration(declaration);+ if (val) {+ podsjsonFile.decrementDeclaration(declaration);+ } else {+ var message = util.format('plugin \"%s\" declaration \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.declaration); /* eslint no-useless-escape : 0 */+ events.emit('verbose', message);+ }+ if (!val || val.count === 0) {+ podfileFile.removeDeclaration(podJson.declaration);+ }+ }+ });+ // sources+ Object.keys(obj.sources).forEach(function (key) {+ var podJson = {+ source: obj.sources[key].source+ };+ var val = podsjsonFile.getSource(key);+ if (val) {+ podsjsonFile.decrementSource(key);+ } else {+ var message = util.format('plugin \"%s\" source \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.source); /* eslint no-useless-escape : 0 */+ events.emit('verbose', message);+ }+ if (!val || val.count === 0) {+ podfileFile.removeSource(podJson.source);+ }+ });+ // libraries+ Object.keys(obj.libraries).forEach(function (key) {+ var podJson = Object.assign({}, obj.libraries[key]);+ var val = podsjsonFile.getLibrary(key);+ if (val) {+ podsjsonFile.decrementLibrary(key);+ } else {+ var message = util.format('plugin \"%s\" podspec \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.name); /* eslint no-useless-escape : 0 */+ events.emit('verbose', message);+ }+ if (!val || val.count === 0) {+ podfileFile.removeSpec(podJson.name);+ }+ });++ });+ }++ if (frameworkPods.length) {+ events.emit('warn', '"framework" tag with type "podspec" is deprecated and will be removed. Please use the "podspec" tag.');+ events.emit('verbose', 'Adding pods since the plugin contained <framework>(s) with type=\"podspec\"'); /* eslint no-useless-escape : 0 */+ frameworkPods.forEach(function (obj) {+ var podJson = {+ name: obj.src,+ type: obj.type,+ spec: obj.spec+ };++ var val = podsjsonFile.getLibrary(podJson.name);+ if (val) { // found, decrement count+ podsjsonFile.decrementLibrary(podJson.name);+ } else { // not found (perhaps a sync error)+ var message = util.format('plugin \"%s\" podspec \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.name); /* eslint no-useless-escape : 0 */+ events.emit('verbose', message);+ }++ // always remove from the Podfile+ podfileFile.removeSpec(podJson.name);+ });+ }++ if (podSpecs.length > 0 || frameworkPods.length > 0) {+ // now that all the pods have been processed, write to pods.json+ podsjsonFile.write();++ if (podfileFile.isDirty()) {+ podfileFile.write();+ events.emit('verbose', 'Running `pod install` (to uninstall pods)');++ return podfileFile.install(check_reqs.check_cocoapods)+ .then(function () {+ return self.setSwiftVersionForCocoaPodsLibraries(podsjsonFile);+ });+ } else {+ events.emit('verbose', 'Podfile unchanged, skipping `pod install`');+ }+ }+ return Q.when();+};++/**+ * set Swift Version for all CocoaPods libraries+ *+ * @param {PodsJson} podsjsonFile A PodsJson instance that represents pods.json+ */++Api.prototype.setSwiftVersionForCocoaPodsLibraries = function (podsjsonFile) {+ var self = this;+ var __dirty = false;+ return check_reqs.check_cocoapods().then(function (toolOptions) {+ if (toolOptions.ignore) {+ events.emit('verbose', '=== skip Swift Version Settings For Cocoapods Libraries');+ } else {+ var podPbxPath = path.join(self.root, 'Pods', 'Pods.xcodeproj', 'project.pbxproj');+ var podXcodeproj = xcode.project(podPbxPath);+ podXcodeproj.parseSync();+ var podTargets = podXcodeproj.pbxNativeTargetSection();+ var podConfigurationList = podXcodeproj.pbxXCConfigurationList();+ var podConfigs = podXcodeproj.pbxXCBuildConfigurationSection();++ var libraries = podsjsonFile.getLibraries();+ Object.keys(libraries).forEach(function (key) {+ var podJson = libraries[key];+ var name = podJson.name;+ var swiftVersion = podJson['swift-version'];+ if (swiftVersion) {+ __dirty = true;+ Object.keys(podTargets).filter(function (targetKey) {+ return podTargets[targetKey].productName === name;+ }).map(function (targetKey) {+ return podTargets[targetKey].buildConfigurationList;+ }).map(function (buildConfigurationListId) {+ return podConfigurationList[buildConfigurationListId];+ }).map(function (buildConfigurationList) {+ return buildConfigurationList.buildConfigurations;+ }).reduce(function (acc, buildConfigurations) {+ return acc.concat(buildConfigurations);+ }, []).map(function (buildConfiguration) {+ return buildConfiguration.value;+ }).forEach(function (buildId) {+ __dirty = true;+ podConfigs[buildId].buildSettings['SWIFT_VERSION'] = swiftVersion;+ });+ }+ });+ if (__dirty) {+ fs.writeFileSync(podPbxPath, podXcodeproj.writeSync(), 'utf-8');+ }+ }+ });+};++/**+ * Builds an application package for current platform.+ *+ * @param {Object} buildOptions A build options. This object's structure is+ * highly depends on platform's specific. The most common options are:+ * @param {Boolean} buildOptions.debug Indicates that packages should be+ * built with debug configuration. This is set to true by default unless the+ * 'release' option is not specified.+ * @param {Boolean} buildOptions.release Indicates that packages should be+ * built with release configuration. If not set to true, debug configuration+ * will be used.+ * @param {Boolean} buildOptions.device Specifies that built app is intended+ * to run on device+ * @param {Boolean} buildOptions.emulator: Specifies that built app is+ * intended to run on emulator+ * @param {String} buildOptions.target Specifies the device id that will be+ * used to run built application.+ * @param {Boolean} buildOptions.nobuild Indicates that this should be a+ * dry-run call, so no build artifacts will be produced.+ * @param {String[]} buildOptions.archs Specifies chip architectures which+ * app packages should be built for. List of valid architectures is depends on+ * platform.+ * @param {String} buildOptions.buildConfig The path to build configuration+ * file. The format of this file is depends on platform.+ * @param {String[]} buildOptions.argv Raw array of command-line arguments,+ * passed to `build` command. The purpose of this property is to pass a+ * platform-specific arguments, and eventually let platform define own+ * arguments processing logic.+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError instance.+ */+Api.prototype.build = function (buildOptions) {+ var self = this;+ return check_reqs.run()+ .then(function () {+ return require('./lib/build').run.call(self, buildOptions);+ });+};++/**+ * Builds an application package for current platform and runs it on+ * specified/default device. If no 'device'/'emulator'/'target' options are+ * specified, then tries to run app on default device if connected, otherwise+ * runs the app on emulator.+ *+ * @param {Object} runOptions An options object. The structure is the same+ * as for build options.+ *+ * @return {Promise} A promise either fulfilled if package was built and ran+ * successfully, or rejected with CordovaError.+ */+Api.prototype.run = function (runOptions) {+ var self = this;+ return check_reqs.run()+ .then(function () {+ return require('./lib/run').run.call(self, runOptions);+ });+};++/**+ * Cleans out the build artifacts from platform's directory.+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError.+ */+Api.prototype.clean = function (cleanOptions) {+ var self = this;+ return check_reqs.run()+ .then(function () {+ return require('./lib/clean').run.call(self, cleanOptions);+ })+ .then(function () {+ return require('./lib/prepare').clean.call(self, cleanOptions);+ });+};++/**+ * Performs a requirements check for current platform. Each platform defines its+ * own set of requirements, which should be resolved before platform can be+ * built successfully.+ *+ * @return {Promise<Requirement[]>} Promise, resolved with set of Requirement+ * objects for current platform.+ */+Api.prototype.requirements = function () {+ return check_reqs.check_all();+};++module.exports = Api;diff --git a/cordova/platforms/ios/cordova/apple_ios_version b/cordova/platforms/ios/cordova/apple_ios_versionnew file mode 100755index 000000000..754dd3910--- /dev/null+++ b/cordova/platforms/ios/cordova/apple_ios_version@@ -0,0 +1,27 @@+#!/usr/bin/env node++/*+ 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 versions = require('./lib/versions.js');++versions.get_apple_ios_version().done(null, function (err) {+ console.log(err);+ process.exit(2);+});diff --git a/cordova/platforms/ios/cordova/apple_osx_version b/cordova/platforms/ios/cordova/apple_osx_versionnew file mode 100755index 000000000..5b4a8b853--- /dev/null+++ b/cordova/platforms/ios/cordova/apple_osx_version@@ -0,0 +1,27 @@+#!/usr/bin/env node++/*+ 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 versions = require('./lib/versions.js');++versions.get_apple_osx_version().done(null, function (err) {+ console.log(err);+ process.exit(2);+});diff --git a/cordova/platforms/ios/cordova/apple_xcode_version b/cordova/platforms/ios/cordova/apple_xcode_versionnew file mode 100755index 000000000..296332910--- /dev/null+++ b/cordova/platforms/ios/cordova/apple_xcode_version@@ -0,0 +1,29 @@+#!/usr/bin/env node++/*+ 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 versions = require('./lib/versions.js');++versions.get_apple_xcode_version().done(function (version) {+ console.log(version);+}, function (err) {+ console.error(err);+ process.exit(2);+});diff --git a/cordova/platforms/ios/cordova/build b/cordova/platforms/ios/cordova/buildnew file mode 100755index 000000000..e795d13dd--- /dev/null+++ b/cordova/platforms/ios/cordova/build@@ -0,0 +1,63 @@+#!/usr/bin/env node++/*+ 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 args = process.argv;+var Api = require('./Api');+var nopt = require('nopt');++// Support basic help commands+if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {+ require('./lib/build').help();+ process.exit(0);+}++// Parse arguments+var buildOpts = nopt({+ 'verbose': Boolean,+ 'silent': Boolean,+ 'archs': String,+ 'debug': Boolean,+ 'release': Boolean,+ 'device': Boolean,+ 'emulator': Boolean,+ 'codeSignIdentity': String,+ 'codeSignResourceRules': String,+ 'provisioningProfile': String,+ 'automaticProvisioning': Boolean,+ 'developmentTeam': String,+ 'packageType': String,+ 'buildConfig': String,+ 'buildFlag': [String, Array],+ 'noSign': Boolean+}, { '-r': '--release', 'd': '--verbose' }, args);++// Make buildOptions compatible with PlatformApi build method spec+buildOpts.argv = buildOpts.argv.remain;++require('./loggingHelper').adjustLoggerLevel(buildOpts);++new Api().build(buildOpts).done(function () {+ console.log('** BUILD SUCCEEDED **');+}, function (err) {+ var errorMessage = (err && err.stack) ? err.stack : err;+ console.error(errorMessage);+ process.exit(2);+});diff --git a/cordova/platforms/ios/cordova/build-debug.xcconfig b/cordova/platforms/ios/cordova/build-debug.xcconfignew file mode 100755index 000000000..7e7985bb5--- /dev/null+++ b/cordova/platforms/ios/cordova/build-debug.xcconfig@@ -0,0 +1,32 @@+//+// 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.+//++//+// XCode Build settings for "Debug" Build Configuration.+//++#include "build.xcconfig"++GCC_PREPROCESSOR_DEFINITIONS = $(inherited) DEBUG=1++#include "build-extras.xcconfig"++// (CB-11792)+// @COCOAPODS_SILENCE_WARNINGS@ //+#include "../pods-debug.xcconfig"diff --git a/cordova/platforms/ios/cordova/build-extras.xcconfig b/cordova/platforms/ios/cordova/build-extras.xcconfignew file mode 100755index 000000000..e69de29bbdiff --git a/cordova/platforms/ios/cordova/build-release.xcconfig b/cordova/platforms/ios/cordova/build-release.xcconfignew file mode 100755index 000000000..70b0f0730--- /dev/null+++ b/cordova/platforms/ios/cordova/build-release.xcconfig@@ -0,0 +1,33 @@+//+// 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.+//++//+// XCode Build settings for "Release" Build Configuration.+//++#include "build.xcconfig"++CODE_SIGN_IDENTITY = iPhone Distribution+CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution++#include "build-extras.xcconfig"++// (CB-11792)+// @COCOAPODS_SILENCE_WARNINGS@ //+#include "../pods-release.xcconfig"diff --git a/cordova/platforms/ios/cordova/build.bat b/cordova/platforms/ios/cordova/build.batnew file mode 100755index 000000000..2f97fcb47--- /dev/null+++ b/cordova/platforms/ios/cordova/build.bat@@ -0,0 +1,19 @@+:: 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++@ECHO OFF+ECHO WARN: The 'build' command is not available for cordova-ios on windows machines.>&2diff --git a/cordova/platforms/ios/cordova/build.xcconfig b/cordova/platforms/ios/cordova/build.xcconfignew file mode 100755index 000000000..3c8b9307d--- /dev/null+++ b/cordova/platforms/ios/cordova/build.xcconfig@@ -0,0 +1,45 @@+//+// 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.+//++//+// XCode build settings shared by all Build Configurations.+// Settings are overridden by configuration-level .xcconfig file (build-release/build-debug).+//++HEADER_SEARCH_PATHS = "$(TARGET_BUILD_DIR)/usr/local/lib/include" "$(OBJROOT)/UninstalledProducts/include" "$(OBJROOT)/UninstalledProducts/$(PLATFORM_NAME)/include" "$(BUILT_PRODUCTS_DIR)"+OTHER_LDFLAGS = -ObjC++// Type of signing identity used for codesigning, resolves to first match of given type.+// "iPhone Developer": Development builds (default, local only; iOS Development certificate) or "iPhone Distribution": Distribution builds (Adhoc/In-House/AppStore; iOS Distribution certificate)+CODE_SIGN_IDENTITY = iPhone Developer+CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Developer++// (CB-9721) Set ENABLE_BITCODE to NO in build.xcconfig+ENABLE_BITCODE = NO++// (CB-9719) Set CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES to YES in build.xcconfig+CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES++// (CB-10072)+SWIFT_OBJC_BRIDGING_HEADER = $(PROJECT_DIR)/$(PROJECT_NAME)/Bridging-Header.h++// (CB-11854)+CODE_SIGN_ENTITLEMENTS = $(PROJECT_DIR)/$(PROJECT_NAME)/Entitlements-$(CONFIGURATION).plist++GCC_PREPROCESSOR_DEFINITIONS = $(inherited) WK_WEB_VIEW_ONLY=$(WK_WEB_VIEW_ONLY)diff --git a/cordova/platforms/ios/cordova/check_reqs b/cordova/platforms/ios/cordova/check_reqsnew file mode 100755index 000000000..8f1d5ca5c--- /dev/null+++ b/cordova/platforms/ios/cordova/check_reqs@@ -0,0 +1,32 @@+#!/usr/bin/env node++/*+ 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 check_reqs = require('./lib/check_reqs');++// check for help flag+if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) > -1) {+ console.log('Usage: check_reqs or node check_reqs');+} else {+ check_reqs.run().done(null, function (err) {+ console.error('Failed to check requirements due to ' + err);+ process.exit(2);+ });+}diff --git a/cordova/platforms/ios/cordova/check_reqs.bat b/cordova/platforms/ios/cordova/check_reqs.batnew file mode 100755index 000000000..683914b88--- /dev/null+++ b/cordova/platforms/ios/cordova/check_reqs.bat@@ -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+@ECHO OFF+SET script_path="%~dp0check_reqs"+IF EXIST %script_path% (+ node "%script_path%" %*+) ELSE (+ ECHO.+ ECHO ERROR: Could not find 'check_reqs' script in 'bin' folder, aborting...>&2+ EXIT /B 1+)\ No newline at end of filediff --git a/cordova/platforms/ios/cordova/clean b/cordova/platforms/ios/cordova/cleannew file mode 100755index 000000000..ccd4a56d5--- /dev/null+++ b/cordova/platforms/ios/cordova/clean@@ -0,0 +1,49 @@+#!/usr/bin/env node++/*+ 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 Api = require('./Api');+var nopt = require('nopt');++if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {+ console.log('Cleans the project directory.');+ process.exit(0);+}++// Do some basic argument parsing+var opts = nopt({+ 'verbose': Boolean,+ 'silent': Boolean+}, { 'd': '--verbose' });++// Make buildOptions compatible with PlatformApi clean method spec+opts.argv = opts.argv.original;++// Skip cleaning prepared files when not invoking via cordova CLI.+opts.noPrepare = true;++require('./loggingHelper').adjustLoggerLevel(opts);++new Api().clean(opts).done(function () {+ console.log('** CLEAN SUCCEEDED **');+}, function (err) {+ console.error(err);+ process.exit(2);+});diff --git a/cordova/platforms/ios/cordova/clean.bat b/cordova/platforms/ios/cordova/clean.batnew file mode 100755index 000000000..583072870--- /dev/null+++ b/cordova/platforms/ios/cordova/clean.bat@@ -0,0 +1,19 @@+:: 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++@ECHO OFF+ECHO WARN: The 'clean' command is not available for cordova-ios on windows machines.>&2diff --git a/cordova/platforms/ios/cordova/defaults.xml b/cordova/platforms/ios/cordova/defaults.xmlnew file mode 100755index 000000000..77a0a0b30--- /dev/null+++ b/cordova/platforms/ios/cordova/defaults.xml@@ -0,0 +1,59 @@+<?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.+-->+<widget xmlns = "http://www.w3.org/ns/widgets"+ id = "io.cordova.helloCordova"+ version = "2.0.0">++ <!-- Preferences for iOS -->+ <preference name="AllowInlineMediaPlayback" value="false" />+ <preference name="BackupWebStorage" value="cloud" />+ <preference name="DisallowOverscroll" value="false" />+ <preference name="EnableViewportScale" value="false" />+ <preference name="KeyboardDisplayRequiresUserAction" value="true" />+ <preference name="MediaPlaybackRequiresUserAction" value="false" />+ <preference name="SuppressesIncrementalRendering" value="false" />+ <preference name="SuppressesLongPressGesture" value="false" />+ <preference name="Suppresses3DTouchGesture" value="false" />+ <preference name="GapBetweenPages" value="0" />+ <preference name="PageLength" value="0" />+ <preference name="PaginationBreakingMode" value="page" /> <!-- page, column -->+ <preference name="PaginationMode" value="unpaginated" /> <!-- unpaginated, leftToRight, topToBottom, bottomToTop, rightToLeft -->++ <feature name="LocalStorage">+ <param name="ios-package" value="CDVLocalStorage"/>+ </feature>+ <feature name="Console">+ <param name="ios-package" value="CDVLogger"/>+ <param name="onload" value="true"/>+ </feature>+ <feature name="HandleOpenUrl">+ <param name="ios-package" value="CDVHandleOpenURL"/>+ <param name="onload" value="true"/>+ </feature>+ <feature name="IntentAndNavigationFilter">+ <param name="ios-package" value="CDVIntentAndNavigationFilter"/>+ <param name="onload" value="true"/>+ </feature>+ <feature name="GestureHandler">+ <param name="ios-package" value="CDVGestureHandler"/>+ <param name="onload" value="true"/>+ </feature>++</widget>diff --git a/cordova/platforms/ios/cordova/lib/BridgingHeader.js b/cordova/platforms/ios/cordova/lib/BridgingHeader.jsnew file mode 100755index 000000000..319d3feb8--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/BridgingHeader.js@@ -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.+*/+'use strict';++var fs = require('fs');+var CordovaError = require('cordova-common').CordovaError;++function BridgingHeader (bridgingHeaderPath) {+ this.path = bridgingHeaderPath;+ this.bridgingHeaders = null;+ if (!fs.existsSync(this.path)) {+ throw new CordovaError('BridgingHeader.h is not found.');+ }+ this.bridgingHeaders = this.__parseForBridgingHeader(fs.readFileSync(this.path, 'utf8'));+}++BridgingHeader.prototype.addHeader = function (plugin_id, header_path) {+ this.bridgingHeaders.push({ type: 'code', code: '#import "' + header_path + '"\n' });+};++BridgingHeader.prototype.removeHeader = function (plugin_id, header_path) {+ this.bridgingHeaders = this.bridgingHeaders.filter(function (line) {+ if (this.found) {+ return true;+ }+ if (line.type === 'code') {+ var re = new RegExp('#import\\s+"' + preg_quote(header_path) + '"(\\s*|\\s.+)(\\n|$)');+ if (re.test(line.code)) {+ this.found = true;+ return false;+ }+ }+ return true;+ }, { found: false });+};++BridgingHeader.prototype.write = function () {+ var text = this.__stringifyForBridgingHeader(this.bridgingHeaders);+ fs.writeFileSync(this.path, text, 'utf8');+};++BridgingHeader.prototype.__stringifyForBridgingHeader = function (bridgingHeaders) {+ return bridgingHeaders.map(function (obj) {+ return obj.code;+ }).join('');+};++BridgingHeader.prototype.__parseForBridgingHeader = function (text) {+ var i = 0;+ var list = [];+ var type = 'code';+ var start = 0;+ while (i < text.length) {+ switch (type) {+ case 'comment':+ if (i + 1 < text.length && text[i] === '*' && text[i + 1] === '/') {+ i += 2;+ list.push({ type: type, code: text.slice(start, i) });+ type = 'code';+ start = i;+ } else {+ i += 1;+ }+ break;+ case 'line-comment':+ if (i < text.length && text[i] === '\n') {+ i += 1;+ list.push({ type: type, code: text.slice(start, i) });+ type = 'code';+ start = i;+ } else {+ i += 1;+ }+ break;+ case 'code':+ default:+ if (i + 1 < text.length && text[i] === '/' && text[i + 1] === '*') { // comment+ if (start < i) {+ list.push({ type: type, code: text.slice(start, i) });+ }+ type = 'comment';+ start = i;+ } else if (i + 1 < text.length && text[i] === '/' && text[i + 1] === '/') { // line comment+ if (start < i) {+ list.push({ type: type, code: text.slice(start, i) });+ }+ type = 'line-comment';+ start = i;+ } else if (i < text.length && text[i] === '\n') {+ i += 1;+ list.push({ type: type, code: text.slice(start, i) });+ start = i;+ } else {+ i += 1;+ }+ break;+ }+ }+ if (start < i) {+ list.push({ type: type, code: text.slice(start, i) });+ }+ return list;+};++function preg_quote (str, delimiter) {+ return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');+}++module.exports.BridgingHeader = BridgingHeader;diff --git a/cordova/platforms/ios/cordova/lib/Podfile.js b/cordova/platforms/ios/cordova/lib/Podfile.jsnew file mode 100755index 000000000..7106ff663--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/Podfile.js@@ -0,0 +1,424 @@+/*+ 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.+*/+'use strict';++var fs = require('fs');+var path = require('path');+var util = require('util');+var events = require('cordova-common').events;+var Q = require('q');+var superspawn = require('cordova-common').superspawn;+var CordovaError = require('cordova-common').CordovaError;++Podfile.FILENAME = 'Podfile';+Podfile.declarationRegexpMap = {+ 'use_frameworks!': 'use[-_]frameworks!?',+ 'inhibit_all_warnings!': 'inhibit[-_]all[-_]warnings!?'+};++function Podfile (podFilePath, projectName, minDeploymentTarget) {+ this.declarationToken = '##INSERT_DECLARATION##';+ this.sourceToken = '##INSERT_SOURCE##';+ this.podToken = '##INSERT_POD##';++ this.path = podFilePath;+ this.projectName = projectName;+ this.minDeploymentTarget = minDeploymentTarget || '10.0';+ this.contents = null;+ this.sources = null;+ this.declarations = null;+ this.pods = null;+ this.__dirty = false;++ // check whether it is named Podfile+ var filename = this.path.split(path.sep).pop();+ if (filename !== Podfile.FILENAME) {+ throw new CordovaError(util.format('Podfile: The file at %s is not `%s`.', this.path, Podfile.FILENAME));+ }++ if (!projectName) {+ throw new CordovaError('Podfile: The projectName was not specified in the constructor.');+ }++ if (!fs.existsSync(this.path)) {+ events.emit('verbose', util.format('Podfile: The file at %s does not exist.', this.path));+ events.emit('verbose', 'Creating new Podfile in platforms/ios');+ this.clear();+ this.write();+ } else {+ events.emit('verbose', 'Podfile found in platforms/ios');+ // parse for pods+ var fileText = fs.readFileSync(this.path, 'utf8');+ this.declarations = this.__parseForDeclarations(fileText);+ this.sources = this.__parseForSources(fileText);+ this.pods = this.__parseForPods(fileText);+ }+}++Podfile.prototype.__parseForDeclarations = function (text) {+ // split by \n+ var arr = text.split('\n');++ // getting lines between "platform :ios, '10.0'"" and "target 'HelloCordova'" do+ var declarationsPreRE = new RegExp('platform :ios,\\s+\'[^\']+\'');+ var declarationsPostRE = new RegExp('target\\s+\'[^\']+\'\\s+do');+ var declarationRE = new RegExp('^\\s*[^#]');++ return arr.reduce(function (acc, line) {+ switch (acc.state) {+ case 0:+ if (declarationsPreRE.exec(line)) {+ acc.state = 1; // Start to read+ }+ break;+ case 1:+ if (declarationsPostRE.exec(line)) {+ acc.state = 2; // Finish to read+ } else {+ acc.lines.push(line);+ }+ break;+ case 2:+ default:+ // do nothing;+ }+ return acc;+ }, { state: 0, lines: [] })+ .lines+ .filter(function (line) {+ return declarationRE.exec(line);+ })+ .reduce(function (obj, line) {+ obj[line] = line;+ return obj;+ }, {});+};++Podfile.prototype.__parseForSources = function (text) {+ // split by \n+ var arr = text.split('\n');++ var sourceRE = new RegExp('source \'(.*)\'');+ return arr.filter(function (line) {+ var m = sourceRE.exec(line);++ return (m !== null);+ })+ .reduce(function (obj, line) {+ var m = sourceRE.exec(line);+ if (m !== null) {+ var source = m[1];+ obj[source] = source;+ }+ return obj;+ }, {});+};++Podfile.prototype.__parseForPods = function (text) {+ // split by \n+ var arr = text.split('\n');++ // aim is to match (space insignificant around the comma, comma optional):+ // pod 'Foobar', '1.2'+ // pod 'Foobar', 'abc 123 1.2'+ // pod 'PonyDebugger', :configurations => ['Debug', 'Beta']+ // var podRE = new RegExp('pod \'([^\']*)\'\\s*,?\\s*(.*)');+ var podRE = new RegExp('pod \'([^\']*)\'\\s*(?:,\\s*\'([^\']*)\'\\s*)?,?\\s*(.*)');++ // only grab lines that don't have the pod spec'+ return arr.filter(function (line) {+ var m = podRE.exec(line);++ return (m !== null);+ })+ .reduce(function (obj, line) {+ var m = podRE.exec(line);++ if (m !== null) {+ var podspec = {+ name: m[1]+ };+ if (m[2]) {+ podspec.spec = m[2];+ }+ if (m[3]) {+ podspec.options = m[3];+ }+ obj[m[1]] = podspec; // i.e pod 'Foo', '1.2' ==> { 'Foo' : '1.2'}+ }++ return obj;+ }, {});+};++Podfile.prototype.escapeSingleQuotes = function (string) {+ return string.replace('\'', '\\\'');+};++Podfile.prototype.getTemplate = function () {+ // Escaping possible ' in the project name+ var projectName = this.escapeSingleQuotes(this.projectName);+ return util.format(+ '# DO NOT MODIFY -- auto-generated by Apache Cordova\n' ++ '%s\n' ++ 'platform :ios, \'%s\'\n' ++ '%s\n' ++ 'target \'%s\' do\n' ++ '\tproject \'%s.xcodeproj\'\n' ++ '%s\n' ++ 'end\n',+ this.sourceToken, this.minDeploymentTarget, this.declarationToken, projectName, projectName, this.podToken);+};++Podfile.prototype.addSpec = function (name, spec) {+ name = name || '';+ // optional+ spec = spec; /* eslint no-self-assign : 0 */++ if (!name.length) { // blank names are not allowed+ throw new CordovaError('Podfile addSpec: name is not specified.');+ }++ if (typeof spec === 'string') {+ if (spec.startsWith(':')) {+ spec = { name: name, options: spec };+ } else {+ spec = { name: name, spec: spec };+ }+ }++ this.pods[name] = spec;+ this.__dirty = true;++ events.emit('verbose', util.format('Added pod line for `%s`', name));+};++Podfile.prototype.removeSpec = function (name) {+ if (this.existsSpec(name)) {+ delete this.pods[name];+ this.__dirty = true;+ }++ events.emit('verbose', util.format('Removed pod line for `%s`', name));+};++Podfile.prototype.getSpec = function (name) {+ return this.pods[name];+};++Podfile.prototype.existsSpec = function (name) {+ return (name in this.pods);+};++Podfile.prototype.addSource = function (src) {+ this.sources[src] = src;+ this.__dirty = true;++ events.emit('verbose', util.format('Added source line for `%s`', src));+};++Podfile.prototype.removeSource = function (src) {+ if (this.existsSource(src)) {+ delete this.sources[src];+ this.__dirty = true;+ }++ events.emit('verbose', util.format('Removed source line for `%s`', src));+};++Podfile.prototype.existsSource = function (src) {+ return (src in this.sources);+};++Podfile.prototype.addDeclaration = function (declaration) {+ this.declarations[declaration] = declaration;+ this.__dirty = true;++ events.emit('verbose', util.format('Added declaration line for `%s`', declaration));+};++Podfile.prototype.removeDeclaration = function (declaration) {+ if (this.existsDeclaration(declaration)) {+ delete this.declarations[declaration];+ this.__dirty = true;+ }++ events.emit('verbose', util.format('Removed source line for `%s`', declaration));+};++Podfile.proofDeclaration = function (declaration) {+ var list = Object.keys(Podfile.declarationRegexpMap).filter(function (key) {+ var regexp = new RegExp(Podfile.declarationRegexpMap[key]);+ return regexp.test(declaration);+ });+ if (list.length > 0) {+ return list[0];+ }+ return declaration;+};++Podfile.prototype.existsDeclaration = function (declaration) {+ return (declaration in this.declarations);+};++Podfile.prototype.clear = function () {+ this.sources = {};+ this.declarations = {};+ this.pods = {};+ this.__dirty = true;+};++Podfile.prototype.destroy = function () {+ fs.unlinkSync(this.path);+ events.emit('verbose', util.format('Deleted `%s`', this.path));+};++Podfile.prototype.write = function () {+ var text = this.getTemplate();+ var self = this;++ var podsString =+ Object.keys(this.pods).map(function (key) {+ var name = key;+ var json = self.pods[key];++ if (typeof json === 'string') { // compatibility for using framework tag.+ var spec = json;+ if (spec.length) {+ if (spec.indexOf(':') === 0) {+ // don't quote it, it's a specification (starts with ':')+ return util.format('\tpod \'%s\', %s', name, spec);+ } else {+ // quote it, it's a version+ return util.format('\tpod \'%s\', \'%s\'', name, spec);+ }+ } else {+ return util.format('\tpod \'%s\'', name);+ }+ } else {+ var list = ['\'' + name + '\''];+ if ('spec' in json && json.spec.length) {+ list.push('\'' + json.spec + '\'');+ }++ var options = ['tag', 'branch', 'commit', 'git', 'podspec'].filter(function (tag) {+ return tag in json;+ }).map(function (tag) {+ return ':' + tag + ' => \'' + json[tag] + '\'';+ });+ if ('configurations' in json) {+ options.push(':configurations => [' + json['configurations'].split(',').map(function (conf) { return '\'' + conf.trim() + '\''; }).join(',') + ']');+ }+ if ('options' in json) {+ options = [json.options];+ }+ if (options.length > 0) {+ list.push(options.join(', '));+ }+ return util.format('\tpod %s', list.join(', '));+ }+ }).join('\n');++ var sourcesString =+ Object.keys(this.sources).map(function (key) {+ var source = self.sources[key];+ return util.format('source \'%s\'', source);+ }).join('\n');++ var declarationString =+ Object.keys(this.declarations).map(function (key) {+ var declaration = self.declarations[key];+ return declaration;+ }).join('\n');++ text = text.replace(this.podToken, podsString)+ .replace(this.sourceToken, sourcesString)+ .replace(this.declarationToken, declarationString);++ fs.writeFileSync(this.path, text, 'utf8');+ this.__dirty = false;++ events.emit('verbose', 'Wrote to Podfile.');+};++Podfile.prototype.isDirty = function () {+ return this.__dirty;+};++Podfile.prototype.before_install = function (toolOptions) {+ toolOptions = toolOptions || {};++ // Template tokens in order: project name, project name, debug | release+ var template =+ '// DO NOT MODIFY -- auto-generated by Apache Cordova\n' ++ '#include "Pods/Target Support Files/Pods-%s/Pods-%s.%s.xcconfig"';++ var debugContents = util.format(template, this.projectName, this.projectName, 'debug');+ var releaseContents = util.format(template, this.projectName, this.projectName, 'release');++ var debugConfigPath = path.join(this.path, '..', 'pods-debug.xcconfig');+ var releaseConfigPath = path.join(this.path, '..', 'pods-release.xcconfig');++ fs.writeFileSync(debugConfigPath, debugContents, 'utf8');+ fs.writeFileSync(releaseConfigPath, releaseContents, 'utf8');++ return Q.resolve(toolOptions);+};++Podfile.prototype.install = function (requirementsCheckerFunction) {+ var opts = {};+ opts.cwd = path.join(this.path, '..'); // parent path of this Podfile+ opts.stdio = 'pipe';+ opts.printCommand = true;+ var first = true;+ var self = this;++ if (!requirementsCheckerFunction) {+ requirementsCheckerFunction = Q();+ }++ return requirementsCheckerFunction()+ .then(function (toolOptions) {+ return self.before_install(toolOptions);+ })+ .then(function (toolOptions) {+ if (toolOptions.ignore) {+ events.emit('verbose', '==== pod install start ====\n');+ events.emit('verbose', toolOptions.ignoreMessage);+ return Q.resolve();+ } else {+ return superspawn.spawn('pod', ['install', '--verbose'], opts)+ .progress(function (stdio) {+ if (stdio.stderr) { console.error(stdio.stderr); }+ if (stdio.stdout) {+ if (first) {+ events.emit('verbose', '==== pod install start ====\n');+ first = false;+ }+ events.emit('verbose', stdio.stdout);+ }+ });+ }+ })+ .then(function () { // done+ events.emit('verbose', '==== pod install end ====\n');+ });+};++module.exports.Podfile = Podfile;diff --git a/cordova/platforms/ios/cordova/lib/PodsJson.js b/cordova/platforms/ios/cordova/lib/PodsJson.jsnew file mode 100755index 000000000..25afbac36--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/PodsJson.js@@ -0,0 +1,209 @@+/*+ 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 fs = require('fs');+var path = require('path');+var util = require('util');+var events = require('cordova-common').events;+var CordovaError = require('cordova-common').CordovaError;++PodsJson.FILENAME = 'pods.json';+PodsJson.LIBRARY = 'libraries';+PodsJson.SOURCE = 'sources';+PodsJson.DECLARATION = 'declarations';++function PodsJson (podsJsonPath) {+ this.path = podsJsonPath;+ this.contents = null;+ this.__dirty = false;++ var filename = this.path.split(path.sep).pop();+ if (filename !== PodsJson.FILENAME) {+ throw new CordovaError(util.format('PodsJson: The file at %s is not `%s`.', this.path, PodsJson.FILENAME));+ }++ if (!fs.existsSync(this.path)) {+ events.emit('verbose', util.format('pods.json: The file at %s does not exist.', this.path));+ events.emit('verbose', 'Creating new pods.json in platforms/ios');+ this.clear();+ this.write();+ } else {+ events.emit('verbose', 'pods.json found in platforms/ios');+ // load contents+ var contents = fs.readFileSync(this.path, 'utf8');+ this.contents = JSON.parse(contents);+ }+ this.__updateFormatIfNecessary();+}++PodsJson.prototype.__isOldFormat = function () {+ if (this.contents !== null) {+ if (this.contents.declarations === undefined ||+ this.contents.sources === undefined ||+ this.contents.libraries === undefined) {+ return true;+ }+ }+ return false;+};++PodsJson.prototype.__updateFormatIfNecessary = function () {+ if (this.__isOldFormat()) {+ this.contents = {+ declarations: {},+ sources: {},+ libraries: this.contents+ };+ this.__dirty = true;+ events.emit('verbose', 'Update format of pods.json');+ }+};++PodsJson.prototype.getLibraries = function () {+ return this.contents[PodsJson.LIBRARY];+};++PodsJson.prototype.__get = function (kind, name) {+ return this.contents[kind][name];+};++PodsJson.prototype.getLibrary = function (name) {+ return this.__get(PodsJson.LIBRARY, name);+};++PodsJson.prototype.getSource = function (name) {+ return this.__get(PodsJson.SOURCE, name);+};++PodsJson.prototype.getDeclaration = function (name) {+ return this.__get(PodsJson.DECLARATION, name);+};++PodsJson.prototype.__remove = function (kind, name) {+ if (this.contents[kind][name]) {+ delete this.contents[kind][name];+ this.__dirty = true;+ events.emit('verbose', util.format('Remove from pods.json for `%s` - `%s`', name));+ }+};++PodsJson.prototype.removeLibrary = function (name) {+ this.__remove(PodsJson.LIBRARY, name);+};++PodsJson.prototype.removeSource = function (name) {+ this.__remove(PodsJson.SOURCE, name);+};++PodsJson.prototype.removeDeclaration = function (name) {+ this.__remove(PodsJson.DECLARATION, name);+};++PodsJson.prototype.clear = function () {+ this.contents = {+ declarations: {},+ sources: {},+ libraries: {}+ };+ this.__dirty = true;+};++PodsJson.prototype.destroy = function () {+ fs.unlinkSync(this.path);+ events.emit('verbose', util.format('Deleted `%s`', this.path));+};++PodsJson.prototype.write = function () {+ if (this.contents) {+ fs.writeFileSync(this.path, JSON.stringify(this.contents, null, 4));+ this.__dirty = false;+ events.emit('verbose', 'Wrote to pods.json.');+ }+};++PodsJson.prototype.__increment = function (kind, name) {+ var val = this.__get(kind, name);+ if (val) {+ val.count++;+ }+};++PodsJson.prototype.incrementLibrary = function (name) {+ this.__increment(PodsJson.LIBRARY, name);+};++PodsJson.prototype.incrementSource = function (name) {+ this.__increment(PodsJson.SOURCE, name);+};++PodsJson.prototype.incrementDeclaration = function (name) {+ this.__increment(PodsJson.DECLARATION, name);+};++PodsJson.prototype.__decrement = function (kind, name) {+ var val = this.__get(kind, name);+ if (val) {+ val.count--;+ if (val.count <= 0) {+ this.__remove(kind, name);+ }+ }+};++PodsJson.prototype.decrementLibrary = function (name) {+ this.__decrement(PodsJson.LIBRARY, name);+};++PodsJson.prototype.decrementSource = function (name) {+ this.__decrement(PodsJson.SOURCE, name);+};++PodsJson.prototype.decrementDeclaration = function (name) {+ this.__decrement(PodsJson.DECLARATION, name);+};++PodsJson.prototype.__setJson = function (kind, name, json) {+ this.contents[kind][name] = Object.assign({}, json);+ this.__dirty = true;+ events.emit('verbose', util.format('Set pods.json for `%s` - `%s`', kind, name));+};++// sample json for library+// { name: "Eureka", spec: "4.2.0", "swift-version": "4.1", count: 1 }+PodsJson.prototype.setJsonLibrary = function (name, json) {+ this.__setJson(PodsJson.LIBRARY, name, json);+};++// sample json for source+// { source: "https://github.com/brightcove/BrightcoveSpecs.git", count: 1 }+PodsJson.prototype.setJsonSource = function (name, json) {+ this.__setJson(PodsJson.SOURCE, name, json);+};++// sample json for declaration+// { declaration: ""}+PodsJson.prototype.setJsonDeclaration = function (name, json) {+ this.__setJson(PodsJson.DECLARATION, name, json);+};++PodsJson.prototype.isDirty = function () {+ return this.__dirty;+};++module.exports.PodsJson = PodsJson;diff --git a/cordova/platforms/ios/cordova/lib/build.js b/cordova/platforms/ios/cordova/lib/build.jsnew file mode 100755index 000000000..f8d301dfd--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/build.js@@ -0,0 +1,464 @@+/**+ * 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 Q = require('q');+var path = require('path');+var shell = require('shelljs');+var superspawn = require('cordova-common').superspawn;+var fs = require('fs');+var plist = require('plist');+var util = require('util');++var check_reqs = require('./check_reqs');+var projectFile = require('./projectFile');++var events = require('cordova-common').events;++// These are regular expressions to detect if the user is changing any of the built-in xcodebuildArgs+/* eslint-disable no-useless-escape */+var buildFlagMatchers = {+ 'workspace': /^\-workspace\s*(.*)/,+ 'scheme': /^\-scheme\s*(.*)/,+ 'configuration': /^\-configuration\s*(.*)/,+ 'sdk': /^\-sdk\s*(.*)/,+ 'destination': /^\-destination\s*(.*)/,+ 'archivePath': /^\-archivePath\s*(.*)/,+ 'configuration_build_dir': /^(CONFIGURATION_BUILD_DIR=.*)/,+ 'shared_precomps_dir': /^(SHARED_PRECOMPS_DIR=.*)/+};+/* eslint-enable no-useless-escape */++/**+ * Creates a project object (see projectFile.js/parseProjectFile) from+ * a project path and name+ *+ * @param {*} projectPath+ * @param {*} projectName+ */+function createProjectObject (projectPath, projectName) {+ var locations = {+ root: projectPath,+ pbxproj: path.join(projectPath, projectName + '.xcodeproj', 'project.pbxproj')+ };++ return projectFile.parse(locations);+}++/**+ * Gets the resolved bundle identifier from a project.+ * Resolves the variable set in INFO.plist, if any (simple case)+ *+ * @param {*} projectObject+ */+function getBundleIdentifier (projectObject) {+ var packageName = projectObject.getPackageName();+ var bundleIdentifier = packageName;++ var variables = packageName.match(/\$\((\w+)\)/); // match $(VARIABLE), if any+ if (variables && variables.length >= 2) {+ bundleIdentifier = projectObject.xcode.getBuildProperty(variables[1]);+ }++ return bundleIdentifier;+}++/**+ * Returns a promise that resolves to the default simulator target; the logic here+ * matches what `cordova emulate ios` does.+ *+ * The return object has two properties: `name` (the Xcode destination name),+ * `identifier` (the simctl identifier), and `simIdentifier` (essentially the cordova emulate target)+ *+ * @return {Promise}+ */+function getDefaultSimulatorTarget () {+ return require('./list-emulator-build-targets').run()+ .then(function (emulators) {+ var targetEmulator;+ if (emulators.length > 0) {+ targetEmulator = emulators[0];+ }+ emulators.forEach(function (emulator) {+ if (emulator.name.indexOf('iPhone') === 0) {+ targetEmulator = emulator;+ }+ });+ return targetEmulator;+ });+}++module.exports.run = function (buildOpts) {+ var emulatorTarget = '';+ var projectPath = path.join(__dirname, '..', '..');+ var projectName = '';++ buildOpts = buildOpts || {};++ if (buildOpts.debug && buildOpts.release) {+ return Q.reject('Cannot specify "debug" and "release" options together.');+ }++ if (buildOpts.device && buildOpts.emulator) {+ return Q.reject('Cannot specify "device" and "emulator" options together.');+ }++ if (buildOpts.buildConfig) {+ if (!fs.existsSync(buildOpts.buildConfig)) {+ return Q.reject('Build config file does not exist: ' + buildOpts.buildConfig);+ }+ events.emit('log', 'Reading build config file: ' + path.resolve(buildOpts.buildConfig));+ var contents = fs.readFileSync(buildOpts.buildConfig, 'utf-8');+ var buildConfig = JSON.parse(contents.replace(/^\ufeff/, '')); // Remove BOM+ if (buildConfig.ios) {+ var buildType = buildOpts.release ? 'release' : 'debug';+ var config = buildConfig.ios[buildType];+ if (config) {+ ['codeSignIdentity', 'codeSignResourceRules', 'provisioningProfile', 'developmentTeam', 'packageType', 'buildFlag', 'iCloudContainerEnvironment', 'automaticProvisioning'].forEach(+ function (key) {+ buildOpts[key] = buildOpts[key] || config[key];+ });+ }+ }+ }++ return require('./list-devices').run()+ .then(function (devices) {+ if (devices.length > 0 && !(buildOpts.emulator)) {+ // we also explicitly set device flag in options as we pass+ // those parameters to other api (build as an example)+ buildOpts.device = true;+ return check_reqs.check_ios_deploy();+ }+ }).then(function () {+ // CB-12287: Determine the device we should target when building for a simulator+ if (!buildOpts.device) {+ var newTarget = buildOpts.target || '';++ if (newTarget) {+ // only grab the device name, not the runtime specifier+ newTarget = newTarget.split(',')[0];+ }+ // a target was given to us, find the matching Xcode destination name+ var promise = require('./list-emulator-build-targets').targetForSimIdentifier(newTarget);+ return promise.then(function (theTarget) {+ if (!theTarget) {+ return getDefaultSimulatorTarget().then(function (defaultTarget) {+ emulatorTarget = defaultTarget.name;+ events.emit('warn', `No simulator found for "${newTarget}. Falling back to the default target.`);+ events.emit('log', `Building for "${emulatorTarget}" Simulator (${defaultTarget.identifier}, ${defaultTarget.simIdentifier}).`);+ return emulatorTarget;+ });+ } else {+ emulatorTarget = theTarget.name;+ events.emit('log', `Building for "${emulatorTarget}" Simulator (${theTarget.identifier}, ${theTarget.simIdentifier}).`);+ return emulatorTarget;+ }+ });+ }+ }).then(function () {+ return check_reqs.run();+ }).then(function () {+ return findXCodeProjectIn(projectPath);+ }).then(function (name) {+ projectName = name;+ var extraConfig = '';+ if (buildOpts.codeSignIdentity) {+ extraConfig += 'CODE_SIGN_IDENTITY = ' + buildOpts.codeSignIdentity + '\n';+ extraConfig += 'CODE_SIGN_IDENTITY[sdk=iphoneos*] = ' + buildOpts.codeSignIdentity + '\n';+ }+ if (buildOpts.codeSignResourceRules) {+ extraConfig += 'CODE_SIGN_RESOURCE_RULES_PATH = ' + buildOpts.codeSignResourceRules + '\n';+ }+ if (buildOpts.provisioningProfile) {+ extraConfig += 'PROVISIONING_PROFILE = ' + buildOpts.provisioningProfile + '\n';+ }+ if (buildOpts.developmentTeam) {+ extraConfig += 'DEVELOPMENT_TEAM = ' + buildOpts.developmentTeam + '\n';+ }++ function writeCodeSignStyle (value) {+ var project = createProjectObject(projectPath, projectName);++ events.emit('verbose', `Set CODE_SIGN_STYLE Build Property to ${value}.`);+ project.xcode.updateBuildProperty('CODE_SIGN_STYLE', value);+ events.emit('verbose', `Set ProvisioningStyle Target Attribute to ${value}.`);+ project.xcode.addTargetAttribute('ProvisioningStyle', value);++ project.write();+ }++ if (buildOpts.provisioningProfile) {+ events.emit('verbose', 'ProvisioningProfile build option set, changing project settings to Manual.');+ writeCodeSignStyle('Manual');+ } else if (buildOpts.automaticProvisioning) {+ events.emit('verbose', 'ProvisioningProfile build option NOT set, changing project settings to Automatic.');+ writeCodeSignStyle('Automatic');+ }++ return Q.nfcall(fs.writeFile, path.join(__dirname, '..', 'build-extras.xcconfig'), extraConfig, 'utf-8');+ }).then(function () {+ var configuration = buildOpts.release ? 'Release' : 'Debug';++ events.emit('log', 'Building project: ' + path.join(projectPath, projectName + '.xcworkspace'));+ events.emit('log', '\tConfiguration: ' + configuration);+ events.emit('log', '\tPlatform: ' + (buildOpts.device ? 'device' : 'emulator'));+ events.emit('log', '\tTarget: ' + emulatorTarget);++ var buildOutputDir = path.join(projectPath, 'build', (buildOpts.device ? 'device' : 'emulator'));++ // remove the build/device folder before building+ shell.rm('-rf', buildOutputDir);++ var xcodebuildArgs = getXcodeBuildArgs(projectName, projectPath, configuration, buildOpts.device, buildOpts.buildFlag, emulatorTarget, buildOpts.automaticProvisioning);+ return superspawn.spawn('xcodebuild', xcodebuildArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });++ }).then(function () {+ if (!buildOpts.device || buildOpts.noSign) {+ return;+ }++ var project = createProjectObject(projectPath, projectName);+ var bundleIdentifier = getBundleIdentifier(project);+ var exportOptions = { 'compileBitcode': false, 'method': 'development' };++ if (buildOpts.packageType) {+ exportOptions.method = buildOpts.packageType;+ }++ if (buildOpts.iCloudContainerEnvironment) {+ exportOptions.iCloudContainerEnvironment = buildOpts.iCloudContainerEnvironment;+ }++ if (buildOpts.developmentTeam) {+ exportOptions.teamID = buildOpts.developmentTeam;+ }++ if (buildOpts.provisioningProfile && bundleIdentifier) {+ exportOptions.provisioningProfiles = { [ bundleIdentifier ]: String(buildOpts.provisioningProfile) };+ exportOptions.signingStyle = 'manual';+ }++ if (buildOpts.codeSignIdentity) {+ exportOptions.signingCertificate = buildOpts.codeSignIdentity;+ }++ var exportOptionsPlist = plist.build(exportOptions);+ var exportOptionsPath = path.join(projectPath, 'exportOptions.plist');++ var buildOutputDir = path.join(projectPath, 'build', 'device');++ function checkSystemRuby () {+ var ruby_cmd = shell.which('ruby');++ if (ruby_cmd !== '/usr/bin/ruby') {+ events.emit('warn', 'Non-system Ruby in use. This may cause packaging to fail.\n' ++ 'If you use RVM, please run `rvm use system`.\n' ++ 'If you use chruby, please run `chruby system`.');+ }+ }++ function packageArchive () {+ var xcodearchiveArgs = getXcodeArchiveArgs(projectName, projectPath, buildOutputDir, exportOptionsPath, buildOpts.automaticProvisioning);+ return superspawn.spawn('xcodebuild', xcodearchiveArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });+ }++ return Q.nfcall(fs.writeFile, exportOptionsPath, exportOptionsPlist, 'utf-8')+ .then(checkSystemRuby)+ .then(packageArchive);+ });+};++/**+ * Searches for first XCode project in specified folder+ * @param {String} projectPath Path where to search project+ * @return {Promise} Promise either fulfilled with project name or rejected+ */+function findXCodeProjectIn (projectPath) {+ // 'Searching for Xcode project in ' + projectPath);+ var xcodeProjFiles = shell.ls(projectPath).filter(function (name) {+ return path.extname(name) === '.xcodeproj';+ });++ if (xcodeProjFiles.length === 0) {+ return Q.reject('No Xcode project found in ' + projectPath);+ }+ if (xcodeProjFiles.length > 1) {+ events.emit('warn', 'Found multiple .xcodeproj directories in \n' ++ projectPath + '\nUsing first one');+ }++ var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');+ return Q.resolve(projectName);+}++module.exports.findXCodeProjectIn = findXCodeProjectIn;++/**+ * Returns array of arguments for xcodebuild+ * @param {String} projectName Name of xcode project+ * @param {String} projectPath Path to project file. Will be used to set CWD for xcodebuild+ * @param {String} configuration Configuration name: debug|release+ * @param {Boolean} isDevice Flag that specify target for package (device/emulator)+ * @param {Array} buildFlags+ * @param {String} emulatorTarget Target for emulator (rather than default)+ * @param {Boolean} autoProvisioning Whether to allow Xcode to automatically update provisioning+ * @return {Array} Array of arguments that could be passed directly to spawn method+ */+function getXcodeBuildArgs (projectName, projectPath, configuration, isDevice, buildFlags, emulatorTarget, autoProvisioning) {+ var xcodebuildArgs;+ var options;+ var buildActions;+ var settings;+ var customArgs = {};+ customArgs.otherFlags = [];++ if (buildFlags) {+ if (typeof buildFlags === 'string' || buildFlags instanceof String) {+ parseBuildFlag(buildFlags, customArgs);+ } else { // buildFlags is an Array of strings+ buildFlags.forEach(function (flag) {+ parseBuildFlag(flag, customArgs);+ });+ }+ }++ if (isDevice) {+ options = [+ '-workspace', customArgs.workspace || projectName + '.xcworkspace',+ '-scheme', customArgs.scheme || projectName,+ '-configuration', customArgs.configuration || configuration,+ '-destination', customArgs.destination || 'generic/platform=iOS',+ '-archivePath', customArgs.archivePath || projectName + '.xcarchive'+ ];+ buildActions = [ 'archive' ];+ settings = [+ customArgs.configuration_build_dir || 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'),+ customArgs.shared_precomps_dir || 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')+ ];+ // Add other matched flags to otherFlags to let xcodebuild present an appropriate error.+ // This is preferable to just ignoring the flags that the user has passed in.+ if (customArgs.sdk) {+ customArgs.otherFlags = customArgs.otherFlags.concat(['-sdk', customArgs.sdk]);+ }++ if (autoProvisioning) {+ options = options.concat(['-allowProvisioningUpdates']);+ }+ } else { // emulator+ options = [+ '-workspace', customArgs.project || projectName + '.xcworkspace',+ '-scheme', customArgs.scheme || projectName,+ '-configuration', customArgs.configuration || configuration,+ '-sdk', customArgs.sdk || 'iphonesimulator',+ '-destination', customArgs.destination || 'platform=iOS Simulator,name=' + emulatorTarget+ ];+ buildActions = [ 'build' ];+ settings = [+ customArgs.configuration_build_dir || 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'),+ customArgs.shared_precomps_dir || 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')+ ];+ // Add other matched flags to otherFlags to let xcodebuild present an appropriate error.+ // This is preferable to just ignoring the flags that the user has passed in.+ if (customArgs.archivePath) {+ customArgs.otherFlags = customArgs.otherFlags.concat(['-archivePath', customArgs.archivePath]);+ }+ }+ xcodebuildArgs = options.concat(buildActions).concat(settings).concat(customArgs.otherFlags);+ return xcodebuildArgs;+}++/**+ * Returns array of arguments for xcodebuild+ * @param {String} projectName Name of xcode project+ * @param {String} projectPath Path to project file. Will be used to set CWD for xcodebuild+ * @param {String} outputPath Output directory to contain the IPA+ * @param {String} exportOptionsPath Path to the exportOptions.plist file+ * @param {Boolean} autoProvisioning Whether to allow Xcode to automatically update provisioning+ * @return {Array} Array of arguments that could be passed directly to spawn method+ */+function getXcodeArchiveArgs (projectName, projectPath, outputPath, exportOptionsPath, autoProvisioning) {+ return [+ '-exportArchive',+ '-archivePath', projectName + '.xcarchive',+ '-exportOptionsPlist', exportOptionsPath,+ '-exportPath', outputPath+ ].concat(autoProvisioning ? ['-allowProvisioningUpdates'] : []);+}++function parseBuildFlag (buildFlag, args) {+ var matched;+ for (var key in buildFlagMatchers) {+ var found = buildFlag.match(buildFlagMatchers[key]);+ if (found) {+ matched = true;+ // found[0] is the whole match, found[1] is the first match in parentheses.+ args[key] = found[1];+ events.emit('warn', util.format('Overriding xcodebuildArg: %s', buildFlag));+ }+ }++ if (!matched) {+ // If the flag starts with a '-' then it is an xcodebuild built-in option or a+ // user-defined setting. The regex makes sure that we don't split a user-defined+ // setting that is wrapped in quotes.+ /* eslint-disable no-useless-escape */+ if (buildFlag[0] === '-' && !buildFlag.match(/^.*=(\".*\")|(\'.*\')$/)) {+ args.otherFlags = args.otherFlags.concat(buildFlag.split(' '));+ events.emit('warn', util.format('Adding xcodebuildArg: %s', buildFlag.split(' ')));+ } else {+ args.otherFlags.push(buildFlag);+ events.emit('warn', util.format('Adding xcodebuildArg: %s', buildFlag));+ }+ }+}++// help/usage function+module.exports.help = function help () {+ console.log('');+ console.log('Usage: build [--debug | --release] [--archs=\"<list of architectures...>\"]');+ console.log(' [--device | --simulator] [--codeSignIdentity=\"<identity>\"]');+ console.log(' [--codeSignResourceRules=\"<resourcerules path>\"]');+ console.log(' [--developmentTeam=\"<Team ID>\"]');+ console.log(' [--provisioningProfile=\"<provisioning profile>\"]');+ console.log(' --help : Displays this dialog.');+ console.log(' --debug : Builds project in debug mode. (Default)');+ console.log(' --release : Builds project in release mode.');+ console.log(' -r : Shortcut :: builds project in release mode.');+ /* eslint-enable no-useless-escape */+ // TODO: add support for building different archs+ // console.log(" --archs : Builds project binaries for specific chip architectures (`anycpu`, `arm`, `x86`, `x64`).");+ console.log(' --device, --simulator');+ console.log(' : Specifies, what type of project to build');+ console.log(' --codeSignIdentity : Type of signing identity used for code signing.');+ console.log(' --codeSignResourceRules : Path to ResourceRules.plist.');+ console.log(' --developmentTeam : New for Xcode 8. The development team (Team ID)');+ console.log(' to use for code signing.');+ console.log(' --provisioningProfile : UUID of the profile.');+ console.log(' --device --noSign : Builds project without application signing.');+ console.log('');+ console.log('examples:');+ console.log(' build ');+ console.log(' build --debug');+ console.log(' build --release');+ console.log(' build --codeSignIdentity="iPhone Distribution" --provisioningProfile="926c2bd6-8de9-4c2f-8407-1016d2d12954"');+ // TODO: add support for building different archs+ // console.log(" build --release --archs=\"armv7\"");+ console.log('');+ process.exit(0);+};diff --git a/cordova/platforms/ios/cordova/lib/check_reqs.js b/cordova/platforms/ios/cordova/lib/check_reqs.jsnew file mode 100755index 000000000..f786fc46a--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/check_reqs.js@@ -0,0 +1,235 @@+/*+ 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.+*/++'use strict';++const Q = require('q');+const shell = require('shelljs');+const util = require('util');+const versions = require('./versions');++const SUPPORTED_OS_PLATFORMS = [ 'darwin' ];++const XCODEBUILD_MIN_VERSION = '9.0.0';+const XCODEBUILD_NOT_FOUND_MESSAGE =+ 'Please install version ' + XCODEBUILD_MIN_VERSION + ' or greater from App Store';++const IOS_DEPLOY_MIN_VERSION = '1.9.2';+const IOS_DEPLOY_NOT_FOUND_MESSAGE =+ 'Please download, build and install version ' + IOS_DEPLOY_MIN_VERSION + ' or greater' ++ ' from https://github.com/ios-control/ios-deploy into your path, or do \'npm install -g ios-deploy\'';++const COCOAPODS_MIN_VERSION = '1.0.1';+const COCOAPODS_NOT_FOUND_MESSAGE =+ 'Please install version ' + COCOAPODS_MIN_VERSION + ' or greater from https://cocoapods.org/';+const COCOAPODS_NOT_SYNCED_MESSAGE =+ 'The CocoaPods repo has not been synced yet, this will take a long time (approximately 500MB as of Sept 2016). Please run `pod setup` first to sync the repo.';+const COCOAPODS_SYNCED_MIN_SIZE = 475; // in megabytes+const COCOAPODS_SYNC_ERROR_MESSAGE =+ 'The CocoaPods repo has been created, but there appears to be a sync error. The repo size should be at least ' + COCOAPODS_SYNCED_MIN_SIZE + '. Please run `pod setup --verbose` to sync the repo.';+const COCOAPODS_REPO_NOT_FOUND_MESSAGE = 'The CocoaPods repo at ~/.cocoapods was not found.';++/**+ * Checks if xcode util is available+ * @return {Promise} Returns a promise either resolved with xcode version or rejected+ */+module.exports.run = module.exports.check_xcodebuild = function () {+ return checkTool('xcodebuild', XCODEBUILD_MIN_VERSION, XCODEBUILD_NOT_FOUND_MESSAGE);+};++/**+ * Checks if ios-deploy util is available+ * @return {Promise} Returns a promise either resolved with ios-deploy version or rejected+ */+module.exports.check_ios_deploy = function () {+ return checkTool('ios-deploy', IOS_DEPLOY_MIN_VERSION, IOS_DEPLOY_NOT_FOUND_MESSAGE);+};++module.exports.check_os = function () {+ // Build iOS apps available for OSX platform only, so we reject on others platforms+ return os_platform_is_supported() ?+ Q.resolve(process.platform) :+ Q.reject('Cordova tooling for iOS requires Apple macOS');+};++function os_platform_is_supported () {+ return (SUPPORTED_OS_PLATFORMS.indexOf(process.platform) !== -1);+}++function check_cocoapod_tool (toolChecker) {+ toolChecker = toolChecker || checkTool;+ if (os_platform_is_supported()) { // CB-12856+ return toolChecker('pod', COCOAPODS_MIN_VERSION, COCOAPODS_NOT_FOUND_MESSAGE, 'CocoaPods');+ } else {+ return Q.resolve({+ 'ignore': true,+ 'ignoreMessage': `CocoaPods check and installation ignored on ${process.platform}`+ });+ }+}++/**+ * Checks if cocoapods repo size is what is expected+ * @return {Promise} Returns a promise either resolved or rejected+ */+module.exports.check_cocoapods_repo_size = function () {+ return check_cocoapod_tool()+ .then(function (toolOptions) {+ // check size of ~/.cocoapods repo+ let commandString = util.format('du -sh %s/.cocoapods', process.env.HOME);+ let command = shell.exec(commandString, { silent: true });+ // command.output is e.g "750M path/to/.cocoapods", we just scan the number+ let size = toolOptions.ignore ? 0 : parseFloat(command.output);++ if (toolOptions.ignore || command.code === 0) { // success, parse output+ return Q.resolve(size, toolOptions);+ } else { // error, perhaps not found+ return Q.reject(util.format('%s (%s)', COCOAPODS_REPO_NOT_FOUND_MESSAGE, command.output));+ }+ })+ .then(function (repoSize, toolOptions) {+ if (toolOptions.ignore || COCOAPODS_SYNCED_MIN_SIZE <= repoSize) { // success, expected size+ return Q.resolve(toolOptions);+ } else {+ return Q.reject(COCOAPODS_SYNC_ERROR_MESSAGE);+ }+ });+};++/**+ * Checks if cocoapods is available, and whether the repo is synced (because it takes a long time to download)+ * @return {Promise} Returns a promise either resolved or rejected+ */+module.exports.check_cocoapods = function (toolChecker) {+ return check_cocoapod_tool(toolChecker)+ // check whether the cocoapods repo has been synced through `pod repo` command+ // a value of '0 repos' means it hasn't been synced+ .then(function (toolOptions) {+ if (toolOptions.ignore) return toolOptions;++ // starting with 1.8.0 cocoapods now use cdn and we dont need to sync first+ if (versions.compareVersions(toolOptions.version, '1.8.0') >= 0) {+ return toolOptions;+ }++ let code = shell.exec('pod repo | grep -e "^0 repos"', { silent: true }).code;+ let repoIsSynced = (code !== 0);++ if (repoIsSynced) {+ // return check_cocoapods_repo_size();+ // we could check the repo size above, but it takes too long.+ return toolOptions;+ } else {+ return Promise.reject(COCOAPODS_NOT_SYNCED_MESSAGE);+ }+ });+};++/**+ * Checks if specific tool is available.+ * @param {String} tool Tool name to check. Known tools are 'xcodebuild' and 'ios-deploy'+ * @param {Number} minVersion Min allowed tool version.+ * @param {String} message Message that will be used to reject promise.+ * @param {String} toolFriendlyName Friendly name of the tool, to report to the user. Optional.+ * @return {Promise} Returns a promise either resolved with tool version or rejected+ */+function checkTool (tool, minVersion, message, toolFriendlyName) {+ toolFriendlyName = toolFriendlyName || tool;++ // Check whether tool command is available at all+ let tool_command = shell.which(tool);+ if (!tool_command) {+ return Q.reject(toolFriendlyName + ' was not found. ' + (message || ''));+ }++ // check if tool version is greater than specified one+ return versions.get_tool_version(tool).then(function (version) {+ version = version.trim();+ return versions.compareVersions(version, minVersion) >= 0 ?+ Q.resolve({ 'version': version }) :+ Q.reject('Cordova needs ' + toolFriendlyName + ' version ' + minVersion ++ ' or greater, you have version ' + version + '. ' + (message || ''));+ });+}++/**+ * Object that represents one of requirements for current platform.+ * @param {String} id The unique identifier for this requirements.+ * @param {String} name The name of requirements. Human-readable field.+ * @param {Boolean} isFatal Marks the requirement as fatal. If such requirement will fail+ * next requirements' checks will be skipped.+ */+let Requirement = function (id, name, isFatal) {+ this.id = id;+ this.name = name;+ this.installed = false;+ this.metadata = {};+ this.isFatal = isFatal || false;+};++/**+ * Methods that runs all checks one by one and returns a result of checks+ * as an array of Requirement objects. This method intended to be used by cordova-lib check_reqs method+ *+ * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.+ */+module.exports.check_all = function () {++ const requirements = [+ new Requirement('os', 'Apple macOS', true),+ new Requirement('xcode', 'Xcode'),+ new Requirement('ios-deploy', 'ios-deploy'),+ new Requirement('CocoaPods', 'CocoaPods')+ ];++ let result = [];+ let fatalIsHit = false;++ let checkFns = [+ module.exports.check_os,+ module.exports.check_xcodebuild,+ module.exports.check_ios_deploy,+ module.exports.check_cocoapods+ ];++ // Then execute requirement checks one-by-one+ return checkFns.reduce(function (promise, checkFn, idx) {+ return promise.then(function () {+ // If fatal requirement is failed,+ // we don't need to check others+ if (fatalIsHit) return Q();++ let requirement = requirements[idx];+ return checkFn()+ .then(function (version) {+ requirement.installed = true;+ requirement.metadata.version = version;+ result.push(requirement);+ }, function (err) {+ if (requirement.isFatal) fatalIsHit = true;+ requirement.metadata.reason = err;+ result.push(requirement);+ });+ });+ }, Q())+ .then(function () {+ // When chain is completed, return requirements array to upstream API+ return result;+ });+};diff --git a/cordova/platforms/ios/cordova/lib/clean.js b/cordova/platforms/ios/cordova/lib/clean.jsnew file mode 100755index 000000000..e5c24a509--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/clean.js@@ -0,0 +1,42 @@+/**+ * 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 Q = require('q');+var path = require('path');+var shell = require('shelljs');+var superspawn = require('cordova-common').superspawn;++var projectPath = path.join(__dirname, '..', '..');++module.exports.run = function () {+ var projectName = shell.ls(projectPath).filter(function (name) {+ return path.extname(name) === '.xcodeproj';+ })[0];++ if (!projectName) {+ return Q.reject('No Xcode project found in ' + projectPath);+ }++ return superspawn.spawn('xcodebuild', ['-project', projectName, '-configuration', 'Debug', '-alltargets', 'clean'], { cwd: projectPath, printCommand: true, stdio: 'inherit' })+ .then(function () {+ return superspawn.spawn('xcodebuild', ['-project', projectName, '-configuration', 'Release', '-alltargets', 'clean'], { cwd: projectPath, printCommand: true, stdio: 'inherit' });+ }).then(function () {+ return shell.rm('-rf', path.join(projectPath, 'build'));+ });+};diff --git a/cordova/platforms/ios/cordova/lib/list-devices b/cordova/platforms/ios/cordova/lib/list-devicesnew file mode 100755index 000000000..473ff5ccd--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/list-devices@@ -0,0 +1,66 @@+#!/usr/bin/env node++/*+ 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 Q = require('q');+var exec = require('child_process').exec;++/**+ * Gets list of connected iOS devices+ * @return {Promise} Promise fulfilled with list of available iOS devices+ */+function listDevices () {+ var commands = [+ Q.nfcall(exec, "ioreg -p IOUSB -l | sed -n -e '/iPad/,/USB Serial Number/p' | grep 'Serial Number' | awk -F\\\" '{print $4 \" iPad\"}'"),+ Q.nfcall(exec, "ioreg -p IOUSB -l | sed -n -e '/iPhone/,/USB Serial Number/p' | grep 'Serial Number' | awk -F\\\" '{print $4 \" iPhone\"}'"),+ Q.nfcall(exec, "ioreg -p IOUSB -l | sed -n -e '/iPod/,/USB Serial Number/p' | grep 'Serial Number' | awk -F\\\" '{print $4 \" iPod\"}'")+ ];++ // wrap al lexec calls into promises and wait until they're fullfilled+ return Q.all(commands).then(function (results) {+ var accumulator = [];+ results.forEach(function (result) {+ var devicefound;+ // Each command promise resolves with array [stout, stderr], and we need stdout only+ // Append stdout lines to accumulator+ devicefound = result[0].trim().split('\n');+ if (devicefound && devicefound.length) {+ devicefound.forEach(function (device) {+ if (device) {+ accumulator.push(device);+ }+ });+ }+ });+ return accumulator;+ });+}++exports.run = listDevices;++// Check if module is started as separate script.+// If so, then invoke main method and print out results.+if (!module.parent) {+ listDevices().then(function (devices) {+ devices.forEach(function (device) {+ console.log(device);+ });+ });+}diff --git a/cordova/platforms/ios/cordova/lib/list-emulator-build-targets b/cordova/platforms/ios/cordova/lib/list-emulator-build-targetsnew file mode 100755index 000000000..25dfe720f--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/list-emulator-build-targets@@ -0,0 +1,108 @@+#!/usr/bin/env node++/*+ 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 Q = require('q');+var exec = require('child_process').exec;++/**+ * Returns a list of available simulator build targets of the form+ *+ * [+ * { name: <xcode-destination-name>,+ * identifier: <simctl-identifier>,+ * simIdentifier: <cordova emulate target>+ * }+ * ]+ *+ */+function listEmulatorBuildTargets () {+ return Q.nfcall(exec, 'xcrun simctl list --json')+ .then(function (stdio) {+ return JSON.parse(stdio[0]);+ })+ .then(function (simInfo) {+ var devices = simInfo.devices;+ var deviceTypes = simInfo.devicetypes;+ return deviceTypes.reduce(function (typeAcc, deviceType) {+ if (!deviceType.name.match(/^[iPad|iPhone]/)) {+ // ignore targets we don't support (like Apple Watch or Apple TV)+ return typeAcc;+ }+ var availableDevices = Object.keys(devices).reduce(function (availAcc, deviceCategory) {+ var availableDevicesInCategory = devices[deviceCategory];+ availableDevicesInCategory.forEach(function (device) {+ if (device.name === deviceType.name || device.name === deviceType.name.replace(/-inch/g, ' inch')) {+ // Check new flag isAvailable (XCode 10.1+) or legacy string availability (XCode 10 and lower)+ if (device.isAvailable || (device.availability && device.availability.toLowerCase().indexOf('unavailable') < 0)) {+ availAcc.push(device);+ }+ }+ });+ return availAcc;+ }, []);+ // we only want device types that have at least one available device+ // (regardless of OS); this filters things out like iPhone 4s, which+ // is present in deviceTypes, but probably not available on the user's+ // system.+ if (availableDevices.length > 0) {+ typeAcc.push(deviceType);+ }+ return typeAcc;+ }, []);+ })+ .then(function (filteredTargets) {+ // the simIdentifier, or cordova emulate target name, is the very last part+ // of identifier.+ return filteredTargets.map(function (target) {+ var identifierPieces = target.identifier.split('.');+ target.simIdentifier = identifierPieces[identifierPieces.length - 1];+ return target;+ });+ });+}++exports.run = listEmulatorBuildTargets;++/**+ * Given a simIdentifier, return the matching target.+ *+ * @param {string} simIdentifier a target, like "iPhone-SE"+ * @return {Object} the matching target, or undefined if no match+ */+exports.targetForSimIdentifier = function (simIdentifier) {+ return listEmulatorBuildTargets()+ .then(function (targets) {+ return targets.reduce(function (acc, target) {+ if (!acc && target.simIdentifier.toLowerCase() === simIdentifier.toLowerCase()) {+ acc = target;+ }+ return acc;+ }, undefined);+ });+};++// Check if module is started as separate script.+// If so, then invoke main method and print out results.+if (!module.parent) {+ listEmulatorBuildTargets().then(function (targets) {+ console.log(JSON.stringify(targets, null, 2));+ });+}diff --git a/cordova/platforms/ios/cordova/lib/list-emulator-images b/cordova/platforms/ios/cordova/lib/list-emulator-imagesnew file mode 100755index 000000000..99557e236--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/list-emulator-images@@ -0,0 +1,43 @@+#!/usr/bin/env node++/*+ 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 Q = require('q');+var iossim = require('ios-sim');++/**+ * Gets list of iOS devices available for simulation+ * @return {Promise} Promise fulfilled with list of devices available for simulation+ */+function listEmulatorImages () {+ return Q.resolve(iossim.getdevicetypes());+}++exports.run = listEmulatorImages;++// Check if module is started as separate script.+// If so, then invoke main method and print out results.+if (!module.parent) {+ listEmulatorImages().then(function (names) {+ names.forEach(function (name) {+ console.log(name);+ });+ });+}diff --git a/cordova/platforms/ios/cordova/lib/list-started-emulators b/cordova/platforms/ios/cordova/lib/list-started-emulatorsnew file mode 100755index 000000000..3626df810--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/list-started-emulators@@ -0,0 +1,49 @@+#!/usr/bin/env node++/*+ 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 Q = require('q');+var exec = require('child_process').exec;++/**+ * Gets list of running iOS simulators+ * @return {Promise} Promise fulfilled with list of running iOS simulators+ */+function listStartedEmulators () {+ // wrap exec call into promise+ return Q.nfcall(exec, 'ps aux | grep -i "[i]OS Simulator"')+ .then(function () {+ return Q.nfcall(exec, 'defaults read com.apple.iphonesimulator "SimulateDevice"');+ }).then(function (stdio) {+ return stdio[0].trim().split('\n');+ });+}++exports.run = listStartedEmulators;++// Check if module is started as separate script.+// If so, then invoke main method and print out results.+if (!module.parent) {+ listStartedEmulators().then(function (emulators) {+ emulators.forEach(function (emulator) {+ console.log(emulator);+ });+ });+}diff --git a/cordova/platforms/ios/cordova/lib/plugman/pluginHandlers.js b/cordova/platforms/ios/cordova/lib/plugman/pluginHandlers.jsnew file mode 100755index 000000000..bd9d853e3--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/plugman/pluginHandlers.js@@ -0,0 +1,391 @@+/*+ 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.+*/+'use strict';+var fs = require('fs');+var path = require('path');+var shell = require('shelljs');+var util = require('util');+var events = require('cordova-common').events;+var CordovaError = require('cordova-common').CordovaError;++// These frameworks are required by cordova-ios by default. We should never add/remove them.+var keep_these_frameworks = [+ 'MobileCoreServices.framework',+ 'CoreGraphics.framework',+ 'AssetsLibrary.framework'+];++var handlers = {+ 'source-file': {+ install: function (obj, plugin, project, options) {+ installHelper('source-file', obj, plugin.dir, project.projectDir, plugin.id, options, project);+ },+ uninstall: function (obj, plugin, project, options) {+ uninstallHelper('source-file', obj, project.projectDir, plugin.id, options, project);+ }+ },+ 'header-file': {+ install: function (obj, plugin, project, options) {+ installHelper('header-file', obj, plugin.dir, project.projectDir, plugin.id, options, project);+ },+ uninstall: function (obj, plugin, project, options) {+ uninstallHelper('header-file', obj, project.projectDir, plugin.id, options, project);+ }+ },+ 'resource-file': {+ install: function (obj, plugin, project, options) {+ var src = obj.src;+ var target = obj.target;+ var srcFile = path.resolve(plugin.dir, src);++ if (!target) {+ target = path.basename(src);+ }+ var destFile = path.resolve(project.resources_dir, target);++ if (!fs.existsSync(srcFile)) {+ throw new CordovaError('Cannot find resource file "' + srcFile + '" for plugin ' + plugin.id + ' in iOS platform');+ }+ if (fs.existsSync(destFile)) {+ throw new CordovaError('File already exists at destination "' + destFile + '" for resource file specified by plugin ' + plugin.id + ' in iOS platform');+ }+ project.xcode.addResourceFile(path.join('Resources', target));+ var link = !!(options && options.link);+ copyFile(plugin.dir, src, project.projectDir, destFile, link);+ },+ uninstall: function (obj, plugin, project, options) {+ var src = obj.src;+ var target = obj.target;++ if (!target) {+ target = path.basename(src);+ }+ var destFile = path.resolve(project.resources_dir, target);++ project.xcode.removeResourceFile(path.join('Resources', target));+ shell.rm('-rf', destFile);+ }+ },+ 'framework': { // CB-5238 custom frameworks only+ install: function (obj, plugin, project, options) {+ var src = obj.src;+ var custom = !!(obj.custom); // convert to boolean (if truthy/falsy)+ var embed = !!(obj.embed); // convert to boolean (if truthy/falsy)+ var link = !embed; // either link or embed can be true, but not both. the other has to be false++ if (!custom) {+ var keepFrameworks = keep_these_frameworks;++ if (keepFrameworks.indexOf(src) < 0) {+ if (obj.type === 'podspec') {+ // podspec handled in Api.js+ } else {+ project.frameworks[src] = project.frameworks[src] || 0;+ project.frameworks[src]++;+ let opt = { customFramework: false, embed: false, link: true, weak: obj.weak };+ events.emit('verbose', util.format('Adding non-custom framework to project... %s -> %s', src, JSON.stringify(opt)));+ project.xcode.addFramework(src, opt);+ events.emit('verbose', util.format('Non-custom framework added to project. %s -> %s', src, JSON.stringify(opt)));+ }+ }+ return;+ }+ var srcFile = path.resolve(plugin.dir, src);+ var targetDir = path.resolve(project.plugins_dir, plugin.id, path.basename(src));+ if (!fs.existsSync(srcFile)) throw new CordovaError('Cannot find framework "' + srcFile + '" for plugin ' + plugin.id + ' in iOS platform');+ if (fs.existsSync(targetDir)) throw new CordovaError('Framework "' + targetDir + '" for plugin ' + plugin.id + ' already exists in iOS platform');+ var symlink = !!(options && options.link);+ copyFile(plugin.dir, src, project.projectDir, targetDir, symlink); // frameworks are directories+ // CB-10773 translate back slashes to forward on win32+ var project_relative = fixPathSep(path.relative(project.projectDir, targetDir));+ // CB-11233 create Embed Frameworks Build Phase if does not exist+ var existsEmbedFrameworks = project.xcode.buildPhaseObject('PBXCopyFilesBuildPhase', 'Embed Frameworks');+ if (!existsEmbedFrameworks && embed) {+ events.emit('verbose', '"Embed Frameworks" Build Phase (Embedded Binaries) does not exist, creating it.');+ project.xcode.addBuildPhase([], 'PBXCopyFilesBuildPhase', 'Embed Frameworks', null, 'frameworks');+ }+ let opt = { customFramework: true, embed: embed, link: link, sign: true };+ events.emit('verbose', util.format('Adding custom framework to project... %s -> %s', src, JSON.stringify(opt)));+ project.xcode.addFramework(project_relative, opt);+ events.emit('verbose', util.format('Custom framework added to project. %s -> %s', src, JSON.stringify(opt)));+ },+ uninstall: function (obj, plugin, project, options) {+ var src = obj.src;++ if (!obj.custom) { // CB-9825 cocoapod integration for plugins+ var keepFrameworks = keep_these_frameworks;+ if (keepFrameworks.indexOf(src) < 0) {+ if (obj.type !== 'podspec') {+ // this should be refactored+ project.frameworks[src] = project.frameworks[src] || 1;+ project.frameworks[src]--;+ if (project.frameworks[src] < 1) {+ // Only remove non-custom framework from xcode project+ // if there is no references remains+ project.xcode.removeFramework(src);+ delete project.frameworks[src];+ }+ }+ }+ return;+ }++ var targetDir = fixPathSep(path.resolve(project.plugins_dir, plugin.id, path.basename(src)));+ var pbxFile = project.xcode.removeFramework(targetDir, { customFramework: true });+ if (pbxFile) {+ project.xcode.removeFromPbxEmbedFrameworksBuildPhase(pbxFile);+ }+ shell.rm('-rf', targetDir);+ }+ },+ 'lib-file': {+ install: function (obj, plugin, project, options) {+ events.emit('verbose', '<lib-file> install is not supported for iOS plugins');+ },+ uninstall: function (obj, plugin, project, options) {+ events.emit('verbose', '<lib-file> uninstall is not supported for iOS plugins');+ }+ },+ 'asset': {+ install: function (obj, plugin, project, options) {+ if (!obj.src) {+ throw new CordovaError(generateAttributeError('src', 'asset', plugin.id));+ }+ if (!obj.target) {+ throw new CordovaError(generateAttributeError('target', 'asset', plugin.id));+ }++ copyFile(plugin.dir, obj.src, project.www, obj.target);+ if (options && options.usePlatformWww) copyFile(plugin.dir, obj.src, project.platformWww, obj.target);+ },+ uninstall: function (obj, plugin, project, options) {+ var target = obj.target;++ if (!target) {+ throw new CordovaError(generateAttributeError('target', 'asset', plugin.id));+ }++ removeFile(project.www, target);+ removeFileF(path.resolve(project.www, 'plugins', plugin.id));+ if (options && options.usePlatformWww) {+ removeFile(project.platformWww, target);+ removeFileF(path.resolve(project.platformWww, 'plugins', plugin.id));+ }+ }+ },+ 'js-module': {+ install: function (obj, plugin, project, options) {+ // Copy the plugin's files into the www directory.+ var moduleSource = path.resolve(plugin.dir, obj.src);+ var moduleName = plugin.id + '.' + (obj.name || path.basename(obj.src, path.extname(obj.src)));++ // Read in the file, prepend the cordova.define, and write it back out.+ var scriptContent = fs.readFileSync(moduleSource, 'utf-8').replace(/^\ufeff/, ''); // Window BOM+ if (moduleSource.match(/.*\.json$/)) {+ scriptContent = 'module.exports = ' + scriptContent;+ }+ scriptContent = 'cordova.define("' + moduleName + '", function(require, exports, module) {\n' + scriptContent + '\n});\n';++ var moduleDestination = path.resolve(project.www, 'plugins', plugin.id, obj.src);+ shell.mkdir('-p', path.dirname(moduleDestination));+ fs.writeFileSync(moduleDestination, scriptContent, 'utf-8');+ if (options && options.usePlatformWww) {+ var platformWwwDestination = path.resolve(project.platformWww, 'plugins', plugin.id, obj.src);+ shell.mkdir('-p', path.dirname(platformWwwDestination));+ fs.writeFileSync(platformWwwDestination, scriptContent, 'utf-8');+ }+ },+ uninstall: function (obj, plugin, project, options) {+ var pluginRelativePath = path.join('plugins', plugin.id, obj.src);+ removeFileAndParents(project.www, pluginRelativePath);+ if (options && options.usePlatformWww) removeFileAndParents(project.platformWww, pluginRelativePath);+ }+ }+};++module.exports.getInstaller = function (type) {+ if (handlers[type] && handlers[type].install) {+ return handlers[type].install;+ }++ events.emit('warn', '<' + type + '> is not supported for iOS plugins');+};++module.exports.getUninstaller = function (type) {+ if (handlers[type] && handlers[type].uninstall) {+ return handlers[type].uninstall;+ }++ events.emit('warn', '<' + type + '> is not supported for iOS plugins');+};++function installHelper (type, obj, plugin_dir, project_dir, plugin_id, options, project) {+ var srcFile = path.resolve(plugin_dir, obj.src);+ var targetDir = path.resolve(project.plugins_dir, plugin_id, obj.targetDir || '');+ var destFile = path.join(targetDir, path.basename(obj.src));++ var project_ref;+ var link = !!(options && options.link);+ if (link) {+ var trueSrc = fs.realpathSync(srcFile);+ // Create a symlink in the expected place, so that uninstall can use it.+ if (options && options.force) {+ copyFile(plugin_dir, trueSrc, project_dir, destFile, link);+ } else {+ copyNewFile(plugin_dir, trueSrc, project_dir, destFile, link);+ }+ // Xcode won't save changes to a file if there is a symlink involved.+ // Make the Xcode reference the file directly.+ // Note: Can't use path.join() here since it collapses 'Plugins/..', and xcode+ // library special-cases Plugins/ prefix.+ project_ref = 'Plugins/' + fixPathSep(path.relative(fs.realpathSync(project.plugins_dir), trueSrc));+ } else {+ if (options && options.force) {+ copyFile(plugin_dir, srcFile, project_dir, destFile, link);+ } else {+ copyNewFile(plugin_dir, srcFile, project_dir, destFile, link);+ }+ project_ref = 'Plugins/' + fixPathSep(path.relative(project.plugins_dir, destFile));+ }++ if (type === 'header-file') {+ project.xcode.addHeaderFile(project_ref);+ } else if (obj.framework) {+ var opt = { weak: obj.weak };+ var project_relative = path.join(path.basename(project.xcode_path), project_ref);+ project.xcode.addFramework(project_relative, opt);+ project.xcode.addToLibrarySearchPaths({ path: project_ref });+ } else {+ project.xcode.addSourceFile(project_ref, obj.compilerFlags ? { compilerFlags: obj.compilerFlags } : {});+ }+}++function uninstallHelper (type, obj, project_dir, plugin_id, options, project) {+ var targetDir = path.resolve(project.plugins_dir, plugin_id, obj.targetDir || '');+ var destFile = path.join(targetDir, path.basename(obj.src));++ var project_ref;+ var link = !!(options && options.link);+ if (link) {+ var trueSrc = fs.readlinkSync(destFile);+ project_ref = 'Plugins/' + fixPathSep(path.relative(fs.realpathSync(project.plugins_dir), trueSrc));+ } else {+ project_ref = 'Plugins/' + fixPathSep(path.relative(project.plugins_dir, destFile));+ }++ shell.rm('-rf', targetDir);++ if (type === 'header-file') {+ project.xcode.removeHeaderFile(project_ref);+ } else if (obj.framework) {+ var project_relative = path.join(path.basename(project.xcode_path), project_ref);+ project.xcode.removeFramework(project_relative);+ project.xcode.removeFromLibrarySearchPaths({ path: project_ref });+ } else {+ project.xcode.removeSourceFile(project_ref);+ }+}++var pathSepFix = new RegExp(path.sep.replace(/\\/, '\\\\'), 'g');+function fixPathSep (file) {+ return file.replace(pathSepFix, '/');+}++function copyFile (plugin_dir, src, project_dir, dest, link) {+ src = path.resolve(plugin_dir, src);+ if (!fs.existsSync(src)) throw new CordovaError('"' + src + '" not found!');++ // check that src path is inside plugin directory+ var real_path = fs.realpathSync(src);+ var real_plugin_path = fs.realpathSync(plugin_dir);+ if (real_path.indexOf(real_plugin_path) !== 0) { throw new CordovaError('File "' + src + '" is located outside the plugin directory "' + plugin_dir + '"'); }++ dest = path.resolve(project_dir, dest);++ // check that dest path is located in project directory+ if (dest.indexOf(project_dir) !== 0) { throw new CordovaError('Destination "' + dest + '" for source file "' + src + '" is located outside the project'); }++ shell.mkdir('-p', path.dirname(dest));++ if (link) {+ linkFileOrDirTree(src, dest);+ } else if (fs.statSync(src).isDirectory()) {+ // XXX shelljs decides to create a directory when -R|-r is used which sucks. http://goo.gl/nbsjq+ shell.cp('-Rf', path.join(src, '/*'), dest);+ } else {+ shell.cp('-f', src, dest);+ }+}++// Same as copy file but throws error if target exists+function copyNewFile (plugin_dir, src, project_dir, dest, link) {+ var target_path = path.resolve(project_dir, dest);+ if (fs.existsSync(target_path)) { throw new CordovaError('"' + target_path + '" already exists!'); }++ copyFile(plugin_dir, src, project_dir, dest, !!link);+}++function linkFileOrDirTree (src, dest) {+ if (fs.existsSync(dest)) {+ shell.rm('-Rf', dest);+ }++ if (fs.statSync(src).isDirectory()) {+ shell.mkdir('-p', dest);+ fs.readdirSync(src).forEach(function (entry) {+ linkFileOrDirTree(path.join(src, entry), path.join(dest, entry));+ });+ } else {+ fs.linkSync(src, dest);+ }+}++// checks if file exists and then deletes. Error if doesn't exist+function removeFile (project_dir, src) {+ var file = path.resolve(project_dir, src);+ shell.rm('-Rf', file);+}++// deletes file/directory without checking+function removeFileF (file) {+ shell.rm('-Rf', file);+}++function removeFileAndParents (baseDir, destFile, stopper) {+ stopper = stopper || '.';+ var file = path.resolve(baseDir, destFile);+ if (!fs.existsSync(file)) return;++ removeFileF(file);++ // check if directory is empty+ var curDir = path.dirname(file);++ while (curDir !== path.resolve(baseDir, stopper)) {+ if (fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) {+ fs.rmdirSync(curDir);+ curDir = path.resolve(curDir, '..');+ } else {+ // directory not empty...do nothing+ break;+ }+ }+}++function generateAttributeError (attribute, element, id) {+ return 'Required attribute "' + attribute + '" not specified in <' + element + '> element from plugin: ' + id;+}diff --git a/cordova/platforms/ios/cordova/lib/prepare.js b/cordova/platforms/ios/cordova/lib/prepare.jsnew file mode 100755index 000000000..16ffd4e71--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/prepare.js@@ -0,0 +1,1190 @@+/**+ 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.+*/++'use strict';+var Q = require('q');+var fs = require('fs');+var path = require('path');+var shell = require('shelljs');+var unorm = require('unorm');+var plist = require('plist');+var URL = require('url');+var events = require('cordova-common').events;+var xmlHelpers = require('cordova-common').xmlHelpers;+var ConfigParser = require('cordova-common').ConfigParser;+var CordovaError = require('cordova-common').CordovaError;+var PlatformJson = require('cordova-common').PlatformJson;+var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;+var PluginInfoProvider = require('cordova-common').PluginInfoProvider;+var FileUpdater = require('cordova-common').FileUpdater;+var projectFile = require('./projectFile');+var xcode = require('xcode');++// launch storyboard and related constants+var LAUNCHIMAGE_BUILD_SETTING = 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME';+var LAUNCHIMAGE_BUILD_SETTING_VALUE = 'LaunchImage';+var UI_LAUNCH_STORYBOARD_NAME = 'UILaunchStoryboardName';+var CDV_LAUNCH_STORYBOARD_NAME = 'CDVLaunchScreen';+var IMAGESET_COMPACT_SIZE_CLASS = 'compact';+var CDV_ANY_SIZE_CLASS = 'any';++module.exports.prepare = function (cordovaProject, options) {+ var self = this;++ var platformJson = PlatformJson.load(this.locations.root, 'ios');+ var munger = new PlatformMunger('ios', this.locations.root, platformJson, new PluginInfoProvider());++ this._config = updateConfigFile(cordovaProject.projectConfig, munger, this.locations);++ // Update own www dir with project's www assets and plugins' assets and js-files+ return Q.when(updateWww(cordovaProject, this.locations))+ .then(function () {+ // update project according to config.xml changes.+ return updateProject(self._config, self.locations);+ })+ .then(function () {+ updateIcons(cordovaProject, self.locations);+ updateSplashScreens(cordovaProject, self.locations);+ updateLaunchStoryboardImages(cordovaProject, self.locations);+ updateFileResources(cordovaProject, self.locations);+ })+ .then(function () {+ events.emit('verbose', 'Prepared iOS project successfully');+ });+};++module.exports.clean = function (options) {+ // A cordovaProject isn't passed into the clean() function, because it might have+ // been called from the platform shell script rather than the CLI. Check for the+ // noPrepare option passed in by the non-CLI clean script. If that's present, or if+ // there's no config.xml found at the project root, then don't clean prepared files.+ var projectRoot = path.resolve(this.root, '../..');+ var projectConfigFile = path.join(projectRoot, 'config.xml');+ if ((options && options.noPrepare) || !fs.existsSync(projectConfigFile) ||+ !fs.existsSync(this.locations.configXml)) {+ return Q();+ }++ var projectConfig = new ConfigParser(this.locations.configXml);++ var self = this;+ return Q().then(function () {+ cleanWww(projectRoot, self.locations);+ cleanIcons(projectRoot, projectConfig, self.locations);+ cleanSplashScreens(projectRoot, projectConfig, self.locations);+ cleanLaunchStoryboardImages(projectRoot, projectConfig, self.locations);+ cleanFileResources(projectRoot, projectConfig, self.locations);+ });+};++/**+ * Updates config files in project based on app's config.xml and config munge,+ * generated by plugins.+ *+ * @param {ConfigParser} sourceConfig A project's configuration that will+ * be merged into platform's config.xml+ * @param {ConfigChanges} configMunger An initialized ConfigChanges instance+ * for this platform.+ * @param {Object} locations A map of locations for this platform+ *+ * @return {ConfigParser} An instance of ConfigParser, that+ * represents current project's configuration. When returned, the+ * configuration is already dumped to appropriate config.xml file.+ */+function updateConfigFile (sourceConfig, configMunger, locations) {+ events.emit('verbose', 'Generating platform-specific config.xml from defaults for iOS at ' + locations.configXml);++ // First cleanup current config and merge project's one into own+ // Overwrite platform config.xml with defaults.xml.+ shell.cp('-f', locations.defaultConfigXml, locations.configXml);++ // Then apply config changes from global munge to all config files+ // in project (including project's config)+ configMunger.reapply_global_munge().save_all();++ events.emit('verbose', 'Merging project\'s config.xml into platform-specific iOS config.xml');+ // Merge changes from app's config.xml into platform's one+ var config = new ConfigParser(locations.configXml);+ xmlHelpers.mergeXml(sourceConfig.doc.getroot(),+ config.doc.getroot(), 'ios', /* clobber= */true);++ config.write();+ return config;+}++/**+ * Logs all file operations via the verbose event stream, indented.+ */+function logFileOp (message) {+ events.emit('verbose', ' ' + message);+}++/**+ * Updates platform 'www' directory by replacing it with contents of+ * 'platform_www' and app www. Also copies project's overrides' folder into+ * the platform 'www' folder+ *+ * @param {Object} cordovaProject An object which describes cordova project.+ * @param {boolean} destinations An object that contains destinations+ * paths for www files.+ */+function updateWww (cordovaProject, destinations) {+ var sourceDirs = [+ path.relative(cordovaProject.root, cordovaProject.locations.www),+ path.relative(cordovaProject.root, destinations.platformWww)+ ];++ // If project contains 'merges' for our platform, use them as another overrides+ var merges_path = path.join(cordovaProject.root, 'merges', 'ios');+ if (fs.existsSync(merges_path)) {+ events.emit('verbose', 'Found "merges/ios" folder. Copying its contents into the iOS project.');+ sourceDirs.push(path.join('merges', 'ios'));+ }++ var targetDir = path.relative(cordovaProject.root, destinations.www);+ events.emit(+ 'verbose', 'Merging and updating files from [' + sourceDirs.join(', ') + '] to ' + targetDir);+ FileUpdater.mergeAndUpdateDir(+ sourceDirs, targetDir, { rootDir: cordovaProject.root }, logFileOp);+}++/**+ * Cleans all files from the platform 'www' directory.+ */+function cleanWww (projectRoot, locations) {+ var targetDir = path.relative(projectRoot, locations.www);+ events.emit('verbose', 'Cleaning ' + targetDir);++ // No source paths are specified, so mergeAndUpdateDir() will clear the target directory.+ FileUpdater.mergeAndUpdateDir(+ [], targetDir, { rootDir: projectRoot, all: true }, logFileOp);+}++/**+ * Updates project structure and AndroidManifest according to project's configuration.+ *+ * @param {ConfigParser} platformConfig A project's configuration that will+ * be used to update project+ * @param {Object} locations A map of locations for this platform (In/Out)+ */+function updateProject (platformConfig, locations) {++ // CB-6992 it is necessary to normalize characters+ // because node and shell scripts handles unicode symbols differently+ // We need to normalize the name to NFD form since iOS uses NFD unicode form+ var name = unorm.nfd(platformConfig.name());+ var version = platformConfig.version();+ var displayName = platformConfig.shortName && platformConfig.shortName();++ var originalName = path.basename(locations.xcodeCordovaProj);++ // Update package id (bundle id)+ var plistFile = path.join(locations.xcodeCordovaProj, originalName + '-Info.plist');+ var infoPlist = plist.parse(fs.readFileSync(plistFile, 'utf8'));++ // Update version (bundle version)+ infoPlist['CFBundleShortVersionString'] = version;+ var CFBundleVersion = platformConfig.getAttribute('ios-CFBundleVersion') || default_CFBundleVersion(version);+ infoPlist['CFBundleVersion'] = CFBundleVersion;++ if (platformConfig.getAttribute('defaultlocale')) {+ infoPlist['CFBundleDevelopmentRegion'] = platformConfig.getAttribute('defaultlocale');+ }++ if (displayName) {+ infoPlist['CFBundleDisplayName'] = displayName;+ }++ // replace Info.plist ATS entries according to <access> and <allow-navigation> config.xml entries+ var ats = writeATSEntries(platformConfig);+ if (Object.keys(ats).length > 0) {+ infoPlist['NSAppTransportSecurity'] = ats;+ } else {+ delete infoPlist['NSAppTransportSecurity'];+ }++ handleOrientationSettings(platformConfig, infoPlist);+ updateProjectPlistForLaunchStoryboard(platformConfig, infoPlist);++ /* eslint-disable no-tabs */+ // Write out the plist file with the same formatting as Xcode does+ var info_contents = plist.build(infoPlist, { indent: '\t', offset: -1 });+ /* eslint-enable no-tabs */++ info_contents = info_contents.replace(/<string>[\s\r\n]*<\/string>/g, '<string></string>');+ fs.writeFileSync(plistFile, info_contents, 'utf-8');+ events.emit('verbose', 'Wrote out iOS Bundle Version "' + version + '" to ' + plistFile);++ return handleBuildSettings(platformConfig, locations, infoPlist).then(function () {+ if (name === originalName) {+ events.emit('verbose', 'iOS Product Name has not changed (still "' + originalName + '")');+ return Q();+ } else { // CB-11712 <name> was changed, we don't support it'+ var errorString =+ 'The product name change (<name> tag) in config.xml is not supported dynamically.\n' ++ 'To change your product name, you have to remove, then add your ios platform again.\n' ++ 'Make sure you save your plugins beforehand using `cordova plugin save`.\n' ++ '\tcordova plugin save\n' ++ '\tcordova platform rm ios\n' ++ '\tcordova platform add ios\n'+ ;++ return Q.reject(new CordovaError(errorString));+ }+ });+}++function handleOrientationSettings (platformConfig, infoPlist) {++ switch (getOrientationValue(platformConfig)) {+ case 'portrait':+ infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationPortrait' ];+ infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown' ];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown' ];+ break;+ case 'landscape':+ infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationLandscapeLeft' ];+ infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ break;+ case 'all':+ infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationPortrait' ];+ infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ break;+ case 'default':+ infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ delete infoPlist['UIInterfaceOrientation'];+ }+}++function handleBuildSettings (platformConfig, locations, infoPlist) {+ var pkg = platformConfig.getAttribute('ios-CFBundleIdentifier') || platformConfig.packageName();+ var targetDevice = parseTargetDevicePreference(platformConfig.getPreference('target-device', 'ios'));+ var deploymentTarget = platformConfig.getPreference('deployment-target', 'ios');+ var needUpdatedBuildSettingsForLaunchStoryboard = checkIfBuildSettingsNeedUpdatedForLaunchStoryboard(platformConfig, infoPlist);+ var swiftVersion = platformConfig.getPreference('SwiftVersion', 'ios');+ var wkWebViewOnly = platformConfig.getPreference('WKWebViewOnly');++ var project;++ try {+ project = projectFile.parse(locations);+ } catch (err) {+ return Q.reject(new CordovaError('Could not parse ' + locations.pbxproj + ': ' + err));+ }++ var origPkg = project.xcode.getBuildProperty('PRODUCT_BUNDLE_IDENTIFIER');++ // no build settings provided and we don't need to update build settings for launch storyboards,+ // then we don't need to parse and update .pbxproj file+ if (origPkg === pkg && !targetDevice && !deploymentTarget && !needUpdatedBuildSettingsForLaunchStoryboard && !swiftVersion && !wkWebViewOnly) {+ return Q();+ }++ if (origPkg !== pkg) {+ events.emit('verbose', 'Set PRODUCT_BUNDLE_IDENTIFIER to ' + pkg + '.');+ project.xcode.updateBuildProperty('PRODUCT_BUNDLE_IDENTIFIER', pkg);+ }++ if (targetDevice) {+ events.emit('verbose', 'Set TARGETED_DEVICE_FAMILY to ' + targetDevice + '.');+ project.xcode.updateBuildProperty('TARGETED_DEVICE_FAMILY', targetDevice);+ }++ if (deploymentTarget) {+ events.emit('verbose', 'Set IPHONEOS_DEPLOYMENT_TARGET to "' + deploymentTarget + '".');+ project.xcode.updateBuildProperty('IPHONEOS_DEPLOYMENT_TARGET', deploymentTarget);+ }++ if (swiftVersion) {+ events.emit('verbose', 'Set SwiftVersion to "' + swiftVersion + '".');+ project.xcode.updateBuildProperty('SWIFT_VERSION', swiftVersion);+ }+ if (wkWebViewOnly) {+ var wkwebviewValue = '1';+ if (wkWebViewOnly === 'true') {+ events.emit('verbose', 'Set WK_WEB_VIEW_ONLY.');+ } else {+ wkwebviewValue = '0';+ events.emit('verbose', 'Unset WK_WEB_VIEW_ONLY.');+ }+ project.xcode.updateBuildProperty('WK_WEB_VIEW_ONLY', wkwebviewValue);+ var cordovaLibXcodePath = path.join(locations.root, 'CordovaLib', 'CordovaLib.xcodeproj');+ var pbxPath = path.join(cordovaLibXcodePath, 'project.pbxproj');+ var xcodeproj = xcode.project(pbxPath);+ xcodeproj.parseSync();+ xcodeproj.updateBuildProperty('WK_WEB_VIEW_ONLY', wkwebviewValue);+ fs.writeFileSync(pbxPath, xcodeproj.writeSync());+ }++ updateBuildSettingsForLaunchStoryboard(project.xcode, platformConfig, infoPlist);++ project.write();++ return Q();+}++function mapIconResources (icons, iconsDir) {+ // See https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html+ // for launch images sizes reference.+ var platformIcons = [+ { dest: 'icon-20.png', width: 20, height: 20 },+ { dest: '[email protected]', width: 40, height: 40 },+ { dest: '[email protected]', width: 60, height: 60 },+ { dest: 'icon-40.png', width: 40, height: 40 },+ { dest: '[email protected]', width: 80, height: 80 },+ { dest: 'icon-50.png', width: 50, height: 50 },+ { dest: '[email protected]', width: 100, height: 100 },+ { dest: '[email protected]', width: 120, height: 120 },+ { dest: '[email protected]', width: 180, height: 180 },+ { dest: 'icon-72.png', width: 72, height: 72 },+ { dest: '[email protected]', width: 144, height: 144 },+ { dest: 'icon-76.png', width: 76, height: 76 },+ { dest: '[email protected]', width: 152, height: 152 },+ { dest: '[email protected]', width: 167, height: 167 },+ { dest: 'icon-1024.png', width: 1024, height: 1024 },+ { dest: 'icon-29.png', width: 29, height: 29 },+ { dest: '[email protected]', width: 58, height: 58 },+ { dest: '[email protected]', width: 87, height: 87 },+ { dest: 'icon.png', width: 57, height: 57 },+ { dest: '[email protected]', width: 114, height: 114 },+ { dest: '[email protected]', width: 48, height: 48 },+ { dest: '[email protected]', width: 55, height: 55 },+ { dest: '[email protected]', width: 88, height: 88 },+ { dest: '[email protected]', width: 172, height: 172 },+ { dest: '[email protected]', width: 196, height: 196 }+ ];++ var pathMap = {};+ platformIcons.forEach(function (item) {+ var icon = icons.getBySize(item.width, item.height) || icons.getDefault();+ if (icon) {+ var target = path.join(iconsDir, item.dest);+ pathMap[target] = icon.src;+ }+ });+ return pathMap;+}++function getIconsDir (projectRoot, platformProjDir) {+ var iconsDir;+ var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));++ if (xcassetsExists) {+ iconsDir = path.join(platformProjDir, 'Images.xcassets/AppIcon.appiconset/');+ } else {+ iconsDir = path.join(platformProjDir, 'Resources/icons/');+ }++ return iconsDir;+}++function updateIcons (cordovaProject, locations) {+ var icons = cordovaProject.projectConfig.getIcons('ios');++ if (icons.length === 0) {+ events.emit('verbose', 'This app does not have icons defined');+ return;+ }++ var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);+ var iconsDir = getIconsDir(cordovaProject.root, platformProjDir);+ var resourceMap = mapIconResources(icons, iconsDir);+ events.emit('verbose', 'Updating icons at ' + iconsDir);+ FileUpdater.updatePaths(+ resourceMap, { rootDir: cordovaProject.root }, logFileOp);+}++function cleanIcons (projectRoot, projectConfig, locations) {+ var icons = projectConfig.getIcons('ios');+ if (icons.length > 0) {+ var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);+ var iconsDir = getIconsDir(projectRoot, platformProjDir);+ var resourceMap = mapIconResources(icons, iconsDir);+ Object.keys(resourceMap).forEach(function (targetIconPath) {+ resourceMap[targetIconPath] = null;+ });+ events.emit('verbose', 'Cleaning icons at ' + iconsDir);++ // Source paths are removed from the map, so updatePaths() will delete the target files.+ FileUpdater.updatePaths(+ resourceMap, { rootDir: projectRoot, all: true }, logFileOp);+ }+}++function mapSplashScreenResources (splashScreens, splashScreensDir) {+ var platformSplashScreens = [+ { dest: 'Default~iphone.png', width: 320, height: 480 },+ { dest: 'Default@2x~iphone.png', width: 640, height: 960 },+ { dest: 'Default-Portrait~ipad.png', width: 768, height: 1024 },+ { dest: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2048 },+ { dest: 'Default-Landscape~ipad.png', width: 1024, height: 768 },+ { dest: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 },+ { dest: 'Default-568h@2x~iphone.png', width: 640, height: 1136 },+ { dest: 'Default-667h.png', width: 750, height: 1334 },+ { dest: 'Default-736h.png', width: 1242, height: 2208 },+ { dest: 'Default-Landscape-736h.png', width: 2208, height: 1242 },+ { dest: 'Default-2436h.png', width: 1125, height: 2436 },+ { dest: 'Default-Landscape-2436h.png', width: 2436, height: 1125 }+ ];++ var pathMap = {};+ platformSplashScreens.forEach(function (item) {+ var splash = splashScreens.getBySize(item.width, item.height);+ if (splash) {+ var target = path.join(splashScreensDir, item.dest);+ pathMap[target] = splash.src;+ }+ });+ return pathMap;+}++function getSplashScreensDir (projectRoot, platformProjDir) {+ var splashScreensDir;+ var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));++ if (xcassetsExists) {+ splashScreensDir = path.join(platformProjDir, 'Images.xcassets/LaunchImage.launchimage/');+ } else {+ splashScreensDir = path.join(platformProjDir, 'Resources/splash/');+ }++ return splashScreensDir;+}++function updateSplashScreens (cordovaProject, locations) {+ var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios');++ if (splashScreens.length === 0) {+ events.emit('verbose', 'This app does not have splash screens defined');+ return;+ }++ var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);+ var splashScreensDir = getSplashScreensDir(cordovaProject.root, platformProjDir);+ var resourceMap = mapSplashScreenResources(splashScreens, splashScreensDir);+ events.emit('verbose', 'Updating splash screens at ' + splashScreensDir);+ FileUpdater.updatePaths(+ resourceMap, { rootDir: cordovaProject.root }, logFileOp);+}++function cleanSplashScreens (projectRoot, projectConfig, locations) {+ var splashScreens = projectConfig.getSplashScreens('ios');+ if (splashScreens.length > 0) {+ var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);+ var splashScreensDir = getSplashScreensDir(projectRoot, platformProjDir);+ var resourceMap = mapIconResources(splashScreens, splashScreensDir);+ Object.keys(resourceMap).forEach(function (targetSplashPath) {+ resourceMap[targetSplashPath] = null;+ });+ events.emit('verbose', 'Cleaning splash screens at ' + splashScreensDir);++ // Source paths are removed from the map, so updatePaths() will delete the target files.+ FileUpdater.updatePaths(+ resourceMap, { rootDir: projectRoot, all: true }, logFileOp);+ }+}++function updateFileResources (cordovaProject, locations) {+ const platformDir = path.relative(cordovaProject.root, locations.root);+ const files = cordovaProject.projectConfig.getFileResources('ios');++ const project = projectFile.parse(locations);++ // if there are resource-file elements in config.xml+ if (files.length === 0) {+ events.emit('verbose', 'This app does not have additional resource files defined');+ return;+ }++ let resourceMap = {};+ files.forEach(function (res) {+ let src = res.src;+ let target = res.target;++ if (!target) {+ target = src;+ }++ let targetPath = path.join(project.resources_dir, target);+ targetPath = path.relative(cordovaProject.root, targetPath);++ if (!fs.existsSync(targetPath)) {+ project.xcode.addResourceFile(target);+ } else {+ events.emit('warn', 'Overwriting existing resource file at ' + targetPath);+ }++ resourceMap[targetPath] = src;+ });++ events.emit('verbose', 'Updating resource files at ' + platformDir);+ FileUpdater.updatePaths(+ resourceMap, { rootDir: cordovaProject.root }, logFileOp);++ project.write();+}++function cleanFileResources (projectRoot, projectConfig, locations) {+ const platformDir = path.relative(projectRoot, locations.root);+ const files = projectConfig.getFileResources('ios', true);+ if (files.length > 0) {+ events.emit('verbose', 'Cleaning resource files at ' + platformDir);++ const project = projectFile.parse(locations);++ var resourceMap = {};+ files.forEach(function (res) {+ let src = res.src;+ let target = res.target;++ if (!target) {+ target = src;+ }++ let targetPath = path.join(project.resources_dir, target);+ targetPath = path.relative(projectRoot, targetPath);+ const resfile = path.join('Resources', path.basename(targetPath));+ project.xcode.removeResourceFile(resfile);++ resourceMap[targetPath] = null;+ });++ FileUpdater.updatePaths(+ resourceMap, { rootDir: projectRoot, all: true }, logFileOp);++ project.write();+ }+}++/**+ * Returns an array of images for each possible idiom, scale, and size class. The images themselves are+ * located in the platform's splash images by their pattern (@scale~idiom~sizesize). All possible+ * combinations are returned, but not all will have a `filename` property. If the latter isn't present,+ * the device won't attempt to load an image matching the same traits. If the filename is present,+ * the device will try to load the image if it corresponds to the traits.+ *+ * The resulting return looks like this:+ *+ * [+ * {+ * idiom: 'universal|ipad|iphone',+ * scale: '1x|2x|3x',+ * width: 'any|com',+ * height: 'any|com',+ * filename: undefined|'Default@scale~idiom~widthheight.png',+ * src: undefined|'path/to/original/matched/image/from/splash/screens.png',+ * target: undefined|'path/to/asset/library/Default@scale~idiom~widthheight.png'+ * }, ...+ * ]+ *+ * @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform+ * @param {string} launchStoryboardImagesDir project-root/Images.xcassets/LaunchStoryboard.imageset/+ * @return {Array<Object>}+ */+function mapLaunchStoryboardContents (splashScreens, launchStoryboardImagesDir) {+ var platformLaunchStoryboardImages = [];+ var idioms = ['universal', 'ipad', 'iphone'];+ var scalesForIdiom = {+ universal: ['1x', '2x', '3x'],+ ipad: ['1x', '2x'],+ iphone: ['1x', '2x', '3x']+ };+ var sizes = ['com', 'any'];++ idioms.forEach(function (idiom) {+ scalesForIdiom[idiom].forEach(function (scale) {+ sizes.forEach(function (width) {+ sizes.forEach(function (height) {+ var item = {+ idiom: idiom,+ scale: scale,+ width: width,+ height: height+ };++ /* examples of the search pattern:+ * scale ~ idiom ~ width height+ * @2x ~ universal ~ any any+ * @3x ~ iphone ~ com any+ * @2x ~ ipad ~ com any+ */+ var searchPattern = '@' + scale + '~' + idiom + '~' + width + height;++ /* because old node versions don't have Array.find, the below is+ * functionally equivalent to this:+ * var launchStoryboardImage = splashScreens.find(function(item) {+ * return item.src.indexOf(searchPattern) >= 0;+ * });+ */+ var launchStoryboardImage = splashScreens.reduce(function (p, c) {+ return (c.src.indexOf(searchPattern) >= 0) ? c : p;+ }, undefined);++ if (launchStoryboardImage) {+ item.filename = 'Default' + searchPattern + '.png';+ item.src = launchStoryboardImage.src;+ item.target = path.join(launchStoryboardImagesDir, item.filename);+ }++ platformLaunchStoryboardImages.push(item);+ });+ });+ });+ });+ return platformLaunchStoryboardImages;+}++/**+ * Returns a dictionary representing the source and destination paths for the launch storyboard images+ * that need to be copied.+ *+ * The resulting return looks like this:+ *+ * {+ * 'target-path': 'source-path',+ * ...+ * }+ *+ * @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform+ * @param {string} launchStoryboardImagesDir project-root/Images.xcassets/LaunchStoryboard.imageset/+ * @return {Object}+ */+function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir) {+ var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);+ var pathMap = {};+ platformLaunchStoryboardImages.forEach(function (item) {+ if (item.target) {+ pathMap[item.target] = item.src;+ }+ });+ return pathMap;+}++/**+ * Builds the object that represents the contents.json file for the LaunchStoryboard image set.+ *+ * The resulting return looks like this:+ *+ * {+ * images: [+ * {+ * idiom: 'universal|ipad|iphone',+ * scale: '1x|2x|3x',+ * width-class: undefined|'compact',+ * height-class: undefined|'compact'+ * }, ...+ * ],+ * info: {+ * author: 'Xcode',+ * version: 1+ * }+ * }+ *+ * A bit of minor logic is used to map from the array of images returned from mapLaunchStoryboardContents+ * to the format requried by Xcode.+ *+ * @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform+ * @param {string} launchStoryboardImagesDir project-root/Images.xcassets/LaunchStoryboard.imageset/+ * @return {Object}+ */+function getLaunchStoryboardContentsJSON (splashScreens, launchStoryboardImagesDir) {++ var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);+ var contentsJSON = {+ images: [],+ info: {+ author: 'Xcode',+ version: 1+ }+ };+ contentsJSON.images = platformLaunchStoryboardImages.map(function (item) {+ var newItem = {+ idiom: item.idiom,+ scale: item.scale+ };++ // Xcode doesn't want any size class property if the class is "any"+ // If our size class is "com", Xcode wants "compact".+ if (item.width !== CDV_ANY_SIZE_CLASS) {+ newItem['width-class'] = IMAGESET_COMPACT_SIZE_CLASS;+ }+ if (item.height !== CDV_ANY_SIZE_CLASS) {+ newItem['height-class'] = IMAGESET_COMPACT_SIZE_CLASS;+ }++ // Xcode doesn't want a filename property if there's no image for these traits+ if (item.filename) {+ newItem.filename = item.filename;+ }+ return newItem;+ });+ return contentsJSON;+}++/**+ * Determines if the project's build settings may need to be updated for launch storyboard support+ *+ */+function checkIfBuildSettingsNeedUpdatedForLaunchStoryboard (platformConfig, infoPlist) {+ var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig);+ var hasLegacyLaunchImages = platformHasLegacyLaunchImages(platformConfig);+ var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME];++ if (hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME && !hasLegacyLaunchImages) {+ // don't need legacy launch images if we are using our launch storyboard+ // so we do need to update the project file+ events.emit('verbose', 'Need to update build settings because project is using our launch storyboard.');+ return true;+ } else if (hasLegacyLaunchImages && !currentLaunchStoryboard) {+ // we do need to ensure legacy launch images are used if there's no launch storyboard present+ // so we do need to update the project file+ events.emit('verbose', 'Need to update build settings because project is using legacy launch images and no storyboard.');+ return true;+ }+ events.emit('verbose', 'No need to update build settings for launch storyboard support.');+ return false;+}++function updateBuildSettingsForLaunchStoryboard (proj, platformConfig, infoPlist) {+ var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig);+ var hasLegacyLaunchImages = platformHasLegacyLaunchImages(platformConfig);+ var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME];++ if (hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME && !hasLegacyLaunchImages) {+ // don't need legacy launch images if we are using our launch storyboard+ events.emit('verbose', 'Removed ' + LAUNCHIMAGE_BUILD_SETTING + ' because project is using our launch storyboard.');+ proj.removeBuildProperty(LAUNCHIMAGE_BUILD_SETTING);+ } else if (hasLegacyLaunchImages && !currentLaunchStoryboard) {+ // we do need to ensure legacy launch images are used if there's no launch storyboard present+ events.emit('verbose', 'Set ' + LAUNCHIMAGE_BUILD_SETTING + ' to ' + LAUNCHIMAGE_BUILD_SETTING_VALUE + ' because project is using legacy launch images and no storyboard.');+ proj.updateBuildProperty(LAUNCHIMAGE_BUILD_SETTING, LAUNCHIMAGE_BUILD_SETTING_VALUE);+ } else {+ events.emit('verbose', 'Did not update build settings for launch storyboard support.');+ }+}++function splashScreensHaveLaunchStoryboardImages (contentsJSON) {+ /* do we have any launch images do we have for our launch storyboard?+ * Again, for old Node versions, the below code is equivalent to this:+ * return !!contentsJSON.images.find(function (item) {+ * return item.filename !== undefined;+ * });+ */+ return !!contentsJSON.images.reduce(function (p, c) {+ return (c.filename !== undefined) ? c : p;+ }, undefined);+}++function platformHasLaunchStoryboardImages (platformConfig) {+ var splashScreens = platformConfig.getSplashScreens('ios');+ var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, ''); // note: we don't need a file path here; we're just counting+ return splashScreensHaveLaunchStoryboardImages(contentsJSON);+}++function platformHasLegacyLaunchImages (platformConfig) {+ var splashScreens = platformConfig.getSplashScreens('ios');+ return !!splashScreens.reduce(function (p, c) {+ return (c.width !== undefined || c.height !== undefined) ? c : p;+ }, undefined);+}++/**+ * Updates the project's plist based upon our launch storyboard images. If there are no images, then we should+ * fall back to the regular launch images that might be supplied (that is, our app will be scaled on an iPad Pro),+ * and if there are some images, we need to alter the UILaunchStoryboardName property to point to+ * CDVLaunchScreen.+ *+ * There's some logic here to avoid overwriting changes the user might have made to their plist if they are using+ * their own launch storyboard.+ */+function updateProjectPlistForLaunchStoryboard (platformConfig, infoPlist) {+ var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME];+ events.emit('verbose', 'Current launch storyboard ' + currentLaunchStoryboard);++ var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig);++ if (hasLaunchStoryboardImages && !currentLaunchStoryboard) {+ // only change the launch storyboard if we have images to use AND the current value is blank+ // if it's not blank, we've either done this before, or the user has their own launch storyboard+ events.emit('verbose', 'Changing info plist to use our launch storyboard');+ infoPlist[UI_LAUNCH_STORYBOARD_NAME] = CDV_LAUNCH_STORYBOARD_NAME;+ return;+ }++ if (!hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME) {+ // only revert to using the launch images if we have don't have any images for the launch storyboard+ // but only clear it if current launch storyboard is our storyboard; the user might be using their+ // own storyboard instead.+ events.emit('verbose', 'Changing info plist to use legacy launch images');+ delete infoPlist[UI_LAUNCH_STORYBOARD_NAME];+ return;+ }+ events.emit('verbose', 'Not changing launch storyboard setting in info plist.');+}++/**+ * Returns the directory for the Launch Storyboard image set, if image sets are being used. If they aren't+ * being used, returns null.+ *+ * @param {string} projectRoot The project's root directory+ * @param {string} platformProjDir The platform's project directory+ */+function getLaunchStoryboardImagesDir (projectRoot, platformProjDir) {+ var launchStoryboardImagesDir;+ var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));++ if (xcassetsExists) {+ launchStoryboardImagesDir = path.join(platformProjDir, 'Images.xcassets/LaunchStoryboard.imageset/');+ } else {+ // if we don't have a asset library for images, we can't do the storyboard.+ launchStoryboardImagesDir = null;+ }++ return launchStoryboardImagesDir;+}++/**+ * Update the images for the Launch Storyboard and updates the image set's contents.json file appropriately.+ *+ * @param {Object} cordovaProject The cordova project+ * @param {Object} locations A dictionary containing useful location paths+ */+function updateLaunchStoryboardImages (cordovaProject, locations) {+ var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios');+ var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);+ var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(cordovaProject.root, platformProjDir);++ if (launchStoryboardImagesDir) {+ var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir);+ var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir);++ events.emit('verbose', 'Updating launch storyboard images at ' + launchStoryboardImagesDir);+ FileUpdater.updatePaths(+ resourceMap, { rootDir: cordovaProject.root }, logFileOp);++ events.emit('verbose', 'Updating Storyboard image set contents.json');+ fs.writeFileSync(path.join(cordovaProject.root, launchStoryboardImagesDir, 'Contents.json'),+ JSON.stringify(contentsJSON, null, 2));+ }+}++/**+ * Removes the images from the launch storyboard's image set and updates the image set's contents.json+ * file appropriately.+ *+ * @param {string} projectRoot Path to the project root+ * @param {Object} projectConfig The project's config.xml+ * @param {Object} locations A dictionary containing useful location paths+ */+function cleanLaunchStoryboardImages (projectRoot, projectConfig, locations) {+ var splashScreens = projectConfig.getSplashScreens('ios');+ var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);+ var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(projectRoot, platformProjDir);+ if (launchStoryboardImagesDir) {+ var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir);+ var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir);++ Object.keys(resourceMap).forEach(function (targetPath) {+ resourceMap[targetPath] = null;+ });+ events.emit('verbose', 'Cleaning storyboard image set at ' + launchStoryboardImagesDir);++ // Source paths are removed from the map, so updatePaths() will delete the target files.+ FileUpdater.updatePaths(+ resourceMap, { rootDir: projectRoot, all: true }, logFileOp);++ // delete filename from contents.json+ contentsJSON.images.forEach(function (image) {+ image.filename = undefined;+ });++ events.emit('verbose', 'Updating Storyboard image set contents.json');+ fs.writeFileSync(path.join(projectRoot, launchStoryboardImagesDir, 'Contents.json'),+ JSON.stringify(contentsJSON, null, 2));+ }+}++/**+ * Queries ConfigParser object for the orientation <preference> value. Warns if+ * global preference value is not supported by platform.+ *+ * @param {Object} platformConfig ConfigParser object+ *+ * @return {String} Global/platform-specific orientation in lower-case+ * (or empty string if both are undefined).+ */+function getOrientationValue (platformConfig) {++ var ORIENTATION_DEFAULT = 'default';++ var orientation = platformConfig.getPreference('orientation');+ if (!orientation) {+ return '';+ }++ orientation = orientation.toLowerCase();++ // Check if the given global orientation is supported+ if (['default', 'portrait', 'landscape', 'all'].indexOf(orientation) >= 0) {+ return orientation;+ }++ events.emit('warn', 'Unrecognized value for Orientation preference: ' + orientation ++ '. Defaulting to value: ' + ORIENTATION_DEFAULT + '.');++ return ORIENTATION_DEFAULT;+}++/*+ Parses all <access> and <allow-navigation> entries and consolidates duplicates (for ATS).+ Returns an object with a Hostname as the key, and the value an object with properties:+ {+ Hostname, // String+ NSExceptionAllowsInsecureHTTPLoads, // boolean+ NSIncludesSubdomains, // boolean+ NSExceptionMinimumTLSVersion, // String+ NSExceptionRequiresForwardSecrecy, // boolean+ NSRequiresCertificateTransparency, // boolean++ // the three below _only_ show when the Hostname is '*'+ // if any of the three are set, it disables setting NSAllowsArbitraryLoads+ // (Apple already enforces this in ATS)+ NSAllowsArbitraryLoadsInWebContent, // boolean (default: false)+ NSAllowsLocalNetworking, // boolean (default: false)+ NSAllowsArbitraryLoadsForMedia, // boolean (default:false)++ }+*/+function processAccessAndAllowNavigationEntries (config) {+ var accesses = config.getAccesses();+ var allow_navigations = config.getAllowNavigations();++ return allow_navigations+ // we concat allow_navigations and accesses, after processing accesses+ .concat(accesses.map(function (obj) {+ // map accesses to a common key interface using 'href', not origin+ obj.href = obj.origin;+ delete obj.origin;+ return obj;+ }))+ // we reduce the array to an object with all the entries processed (key is Hostname)+ .reduce(function (previousReturn, currentElement) {+ var options = {+ minimum_tls_version: currentElement.minimum_tls_version,+ requires_forward_secrecy: currentElement.requires_forward_secrecy,+ requires_certificate_transparency: currentElement.requires_certificate_transparency,+ allows_arbitrary_loads_for_media: currentElement.allows_arbitrary_loads_in_media || currentElement.allows_arbitrary_loads_for_media,+ allows_arbitrary_loads_in_web_content: currentElement.allows_arbitrary_loads_in_web_content,+ allows_local_networking: currentElement.allows_local_networking+ };+ var obj = parseWhitelistUrlForATS(currentElement.href, options);++ if (obj) {+ // we 'union' duplicate entries+ var item = previousReturn[obj.Hostname];+ if (!item) {+ item = {};+ }+ for (var o in obj) {+ if (obj.hasOwnProperty(o)) {+ item[o] = obj[o];+ }+ }+ previousReturn[obj.Hostname] = item;+ }+ return previousReturn;+ }, {});+}++/*+ Parses a URL and returns an object with these keys:+ {+ Hostname, // String+ NSExceptionAllowsInsecureHTTPLoads, // boolean (default: false)+ NSIncludesSubdomains, // boolean (default: false)+ NSExceptionMinimumTLSVersion, // String (default: 'TLSv1.2')+ NSExceptionRequiresForwardSecrecy, // boolean (default: true)+ NSRequiresCertificateTransparency, // boolean (default: false)++ // the three below _only_ apply when the Hostname is '*'+ // if any of the three are set, it disables setting NSAllowsArbitraryLoads+ // (Apple already enforces this in ATS)+ NSAllowsArbitraryLoadsInWebContent, // boolean (default: false)+ NSAllowsLocalNetworking, // boolean (default: false)+ NSAllowsArbitraryLoadsForMedia, // boolean (default:false)+ }++ null is returned if the URL cannot be parsed, or is to be skipped for ATS.+*/+function parseWhitelistUrlForATS (url, options) {+ // @todo 'url.parse' was deprecated since v11.0.0. Use 'url.URL' constructor instead.+ var href = URL.parse(url); // eslint-disable-line+ var retObj = {};+ retObj.Hostname = href.hostname;++ // Guiding principle: we only set values in retObj if they are NOT the default++ if (url === '*') {+ retObj.Hostname = '*';+ var val;++ val = (options.allows_arbitrary_loads_in_web_content === 'true');+ if (options.allows_arbitrary_loads_in_web_content && val) { // default is false+ retObj.NSAllowsArbitraryLoadsInWebContent = true;+ }++ val = (options.allows_arbitrary_loads_for_media === 'true');+ if (options.allows_arbitrary_loads_for_media && val) { // default is false+ retObj.NSAllowsArbitraryLoadsForMedia = true;+ }++ val = (options.allows_local_networking === 'true');+ if (options.allows_local_networking && val) { // default is false+ retObj.NSAllowsLocalNetworking = true;+ }++ return retObj;+ }++ if (!retObj.Hostname) {+ // check origin, if it allows subdomains (wildcard in hostname), we set NSIncludesSubdomains to YES. Default is NO+ var subdomain1 = '/*.'; // wildcard in hostname+ var subdomain2 = '*://*.'; // wildcard in hostname and protocol+ var subdomain3 = '*://'; // wildcard in protocol only+ if (!href.pathname) {+ return null;+ } else if (href.pathname.indexOf(subdomain1) === 0) {+ retObj.NSIncludesSubdomains = true;+ retObj.Hostname = href.pathname.substring(subdomain1.length);+ } else if (href.pathname.indexOf(subdomain2) === 0) {+ retObj.NSIncludesSubdomains = true;+ retObj.Hostname = href.pathname.substring(subdomain2.length);+ } else if (href.pathname.indexOf(subdomain3) === 0) {+ retObj.Hostname = href.pathname.substring(subdomain3.length);+ } else {+ // Handling "scheme:*" case to avoid creating of a blank key in NSExceptionDomains.+ return null;+ }+ }++ if (options.minimum_tls_version && options.minimum_tls_version !== 'TLSv1.2') { // default is TLSv1.2+ retObj.NSExceptionMinimumTLSVersion = options.minimum_tls_version;+ }++ var rfs = (options.requires_forward_secrecy === 'true');+ if (options.requires_forward_secrecy && !rfs) { // default is true+ retObj.NSExceptionRequiresForwardSecrecy = false;+ }++ var rct = (options.requires_certificate_transparency === 'true');+ if (options.requires_certificate_transparency && rct) { // default is false+ retObj.NSRequiresCertificateTransparency = true;+ }++ // if the scheme is HTTP, we set NSExceptionAllowsInsecureHTTPLoads to YES. Default is NO+ if (href.protocol === 'http:') {+ retObj.NSExceptionAllowsInsecureHTTPLoads = true;+ } else if (!href.protocol && href.pathname.indexOf('*:/') === 0) { // wilcard in protocol+ retObj.NSExceptionAllowsInsecureHTTPLoads = true;+ }++ return retObj;+}++/*+ App Transport Security (ATS) writer from <access> and <allow-navigation> tags+ in config.xml+*/+function writeATSEntries (config) {+ var pObj = processAccessAndAllowNavigationEntries(config);++ var ats = {};++ for (var hostname in pObj) {+ if (pObj.hasOwnProperty(hostname)) {+ var entry = pObj[hostname];++ // Guiding principle: we only set values if they are available++ if (hostname === '*') {+ // always write this, for iOS 9, since in iOS 10 it will be overriden if+ // any of the other three keys are written+ ats['NSAllowsArbitraryLoads'] = true;++ // at least one of the overriding keys is present+ if (entry.NSAllowsArbitraryLoadsInWebContent) {+ ats['NSAllowsArbitraryLoadsInWebContent'] = true;+ }+ if (entry.NSAllowsArbitraryLoadsForMedia) {+ ats['NSAllowsArbitraryLoadsForMedia'] = true;+ }+ if (entry.NSAllowsLocalNetworking) {+ ats['NSAllowsLocalNetworking'] = true;+ }++ continue;+ }++ var exceptionDomain = {};++ for (var key in entry) {+ if (entry.hasOwnProperty(key) && key !== 'Hostname') {+ exceptionDomain[key] = entry[key];+ }+ }++ if (!ats['NSExceptionDomains']) {+ ats['NSExceptionDomains'] = {};+ }++ ats['NSExceptionDomains'][hostname] = exceptionDomain;+ }+ }++ return ats;+}++function folderExists (folderPath) {+ try {+ var stat = fs.statSync(folderPath);+ return stat && stat.isDirectory();+ } catch (e) {+ return false;+ }+}++// Construct a default value for CFBundleVersion as the version with any+// -rclabel stripped=.+function default_CFBundleVersion (version) {+ return version.split('-')[0];+}++// Converts cordova specific representation of target device to XCode value+function parseTargetDevicePreference (value) {+ if (!value) return null;+ var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"' };+ if (map[value.toLowerCase()]) {+ return map[value.toLowerCase()];+ }+ events.emit('warn', 'Unrecognized value for target-device preference: ' + value + '.');+ return null;+}diff --git a/cordova/platforms/ios/cordova/lib/projectFile.js b/cordova/platforms/ios/cordova/lib/projectFile.jsnew file mode 100755index 000000000..8a3f7e516--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/projectFile.js@@ -0,0 +1,134 @@+/*+ 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 xcode = require('xcode');+var plist = require('plist');+var _ = require('underscore');+var path = require('path');+var fs = require('fs');+var shell = require('shelljs');++var pluginHandlers = require('./plugman/pluginHandlers');+var CordovaError = require('cordova-common').CordovaError;++var cachedProjectFiles = {};++function parseProjectFile (locations) {+ var project_dir = locations.root;+ var pbxPath = locations.pbxproj;++ if (cachedProjectFiles[project_dir]) {+ return cachedProjectFiles[project_dir];+ }++ var xcodeproj = xcode.project(pbxPath);+ xcodeproj.parseSync();++ var xcBuildConfiguration = xcodeproj.pbxXCBuildConfigurationSection();+ var plist_file_entry = _.find(xcBuildConfiguration, function (entry) { return entry.buildSettings && entry.buildSettings.INFOPLIST_FILE; });+ var plist_file = path.join(project_dir, plist_file_entry.buildSettings.INFOPLIST_FILE.replace(/^"(.*)"$/g, '$1').replace(/\\&/g, '&'));+ var config_file = path.join(path.dirname(plist_file), 'config.xml');++ if (!fs.existsSync(plist_file) || !fs.existsSync(config_file)) {+ throw new CordovaError('Could not find *-Info.plist file, or config.xml file.');+ }++ var frameworks_file = path.join(project_dir, 'frameworks.json');+ var frameworks = {};+ try {+ frameworks = require(frameworks_file);+ } catch (e) { }++ var xcode_dir = path.dirname(plist_file);+ var pluginsDir = path.resolve(xcode_dir, 'Plugins');+ var resourcesDir = path.resolve(xcode_dir, 'Resources');++ cachedProjectFiles[project_dir] = {+ plugins_dir: pluginsDir,+ resources_dir: resourcesDir,+ xcode: xcodeproj,+ xcode_path: xcode_dir,+ pbx: pbxPath,+ projectDir: project_dir,+ platformWww: path.join(project_dir, 'platform_www'),+ www: path.join(project_dir, 'www'),+ write: function () {+ fs.writeFileSync(pbxPath, xcodeproj.writeSync());+ if (Object.keys(this.frameworks).length === 0) {+ // If there is no framework references remain in the project, just remove this file+ shell.rm('-rf', frameworks_file);+ return;+ }+ fs.writeFileSync(frameworks_file, JSON.stringify(this.frameworks, null, 4));+ },+ getPackageName: function () {+ return plist.parse(fs.readFileSync(plist_file, 'utf8')).CFBundleIdentifier;+ },+ getInstaller: function (name) {+ return pluginHandlers.getInstaller(name);+ },+ getUninstaller: function (name) {+ return pluginHandlers.getUninstaller(name);+ },+ frameworks: frameworks+ };+ return cachedProjectFiles[project_dir];+}++function purgeProjectFileCache (project_dir) {+ delete cachedProjectFiles[project_dir];+}++module.exports = {+ parse: parseProjectFile,+ purgeProjectFileCache: purgeProjectFileCache+};++xcode.project.prototype.pbxEmbedFrameworksBuildPhaseObj = function (target) {+ return this.buildPhaseObject('PBXCopyFilesBuildPhase', 'Embed Frameworks', target);+};++xcode.project.prototype.addToPbxEmbedFrameworksBuildPhase = function (file) {+ var sources = this.pbxEmbedFrameworksBuildPhaseObj(file.target);+ if (sources) {+ sources.files.push(pbxBuildPhaseObj(file));+ }+};+xcode.project.prototype.removeFromPbxEmbedFrameworksBuildPhase = function (file) {+ var sources = this.pbxEmbedFrameworksBuildPhaseObj(file.target);+ if (sources) {+ sources.files = _.reject(sources.files, function (file) {+ return file.comment === longComment(file);+ });+ }+};++// special handlers to add frameworks to the 'Embed Frameworks' build phase, needed for custom frameworks+// see CB-9517. should probably be moved to node-xcode.+var util = require('util');+function pbxBuildPhaseObj (file) {+ var obj = Object.create(null);+ obj.value = file.uuid;+ obj.comment = longComment(file);+ return obj;+}++function longComment (file) {+ return util.format('%s in %s', file.basename, file.group);+}diff --git a/cordova/platforms/ios/cordova/lib/run.js b/cordova/platforms/ios/cordova/lib/run.jsnew file mode 100755index 000000000..f21fee69b--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/run.js@@ -0,0 +1,263 @@+/*+ 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 Q = require('q');+var path = require('path');+var build = require('./build');+var shell = require('shelljs');+var superspawn = require('cordova-common').superspawn;+var check_reqs = require('./check_reqs');+var fs = require('fs-extra');++var events = require('cordova-common').events;++var cordovaPath = path.join(__dirname, '..');+var projectPath = path.join(__dirname, '..', '..');++module.exports.run = function (runOptions) {++ // Validate args+ if (runOptions.device && runOptions.emulator) {+ return Q.reject('Only one of "device"/"emulator" options should be specified');+ }++ // support for CB-8168 `cordova/run --list`+ if (runOptions.list) {+ if (runOptions.device) return module.exports.listDevices();+ if (runOptions.emulator) return module.exports.listEmulators();+ // if no --device or --emulator flag is specified, list both devices and emulators+ return module.exports.listDevices().then(function () {+ return module.exports.listEmulators();+ });+ }++ var useDevice = !!runOptions.device;++ return require('./list-devices').run()+ .then(function (devices) {+ if (devices.length > 0 && !(runOptions.emulator)) {+ useDevice = true;+ // we also explicitly set device flag in options as we pass+ // those parameters to other api (build as an example)+ runOptions.device = true;+ return check_reqs.check_ios_deploy();+ }+ }).then(function () {+ if (!runOptions.nobuild) {+ return build.run(runOptions);+ } else {+ return Q.resolve();+ }+ }).then(function () {+ return build.findXCodeProjectIn(projectPath);+ }).then(function (projectName) {+ var appPath = path.join(projectPath, 'build', 'emulator', projectName + '.app');+ var buildOutputDir = path.join(projectPath, 'build', 'device');++ // select command to run and arguments depending whether+ // we're running on device/emulator+ if (useDevice) {+ return module.exports.checkDeviceConnected()+ .then(function () {+ // Unpack IPA+ var ipafile = path.join(buildOutputDir, projectName + '.ipa');++ // unpack the existing platform/ios/build/device/appname.ipa (zipfile), will create a Payload folder+ return superspawn.spawn('unzip', [ '-o', '-qq', ipafile ], { cwd: buildOutputDir, printCommand: true, stdio: 'inherit' });+ })+ .then(function () {+ // Uncompress IPA (zip file)+ var appFileInflated = path.join(buildOutputDir, 'Payload', projectName + '.app');+ var appFile = path.join(buildOutputDir, projectName + '.app');+ var payloadFolder = path.join(buildOutputDir, 'Payload');++ // delete the existing platform/ios/build/device/appname.app+ fs.removeSync(appFile);+ // move the platform/ios/build/device/Payload/appname.app to parent+ shell.mv('-f', appFileInflated, buildOutputDir);+ // delete the platform/ios/build/device/Payload folder+ shell.rm('-rf', payloadFolder);++ return null;+ })+ .then(function () {+ appPath = path.join(projectPath, 'build', 'device', projectName + '.app');+ var extraArgs = [];+ if (runOptions.argv) {+ // argv.slice(2) removes node and run.js, filterSupportedArgs removes the run.js args+ extraArgs = module.exports.filterSupportedArgs(runOptions.argv.slice(2));+ }+ return module.exports.deployToDevice(appPath, runOptions.target, extraArgs);+ }, function () {+ // if device connection check failed use emulator then+ return module.exports.deployToSim(appPath, runOptions.target);+ });+ } else {+ return module.exports.deployToSim(appPath, runOptions.target);+ }+ });+};++module.exports.filterSupportedArgs = filterSupportedArgs;+module.exports.checkDeviceConnected = checkDeviceConnected;+module.exports.deployToDevice = deployToDevice;+module.exports.deployToSim = deployToSim;+module.exports.startSim = startSim;+module.exports.listDevices = listDevices;+module.exports.listEmulators = listEmulators;++/**+ * Filters the args array and removes supported args for the 'run' command.+ *+ * @return {Array} array with unsupported args for the 'run' command+ */+function filterSupportedArgs (args) {+ var filtered = [];+ var sargs = ['--device', '--emulator', '--nobuild', '--list', '--target', '--debug', '--release'];+ var re = new RegExp(sargs.join('|'));++ args.forEach(function (element) {+ // supported args not found, we add+ // we do a regex search because --target can be "--target=XXX"+ if (element.search(re) === -1) {+ filtered.push(element);+ }+ }, this);++ return filtered;+}++/**+ * Checks if any iOS device is connected+ * @return {Promise} Fullfilled when any device is connected, rejected otherwise+ */+function checkDeviceConnected () {+ return superspawn.spawn('ios-deploy', ['-c', '-t', '1'], { printCommand: true, stdio: 'inherit' });+}++/**+ * Deploy specified app package to connected device+ * using ios-deploy command+ * @param {String} appPath Path to application package+ * @return {Promise} Resolves when deploy succeeds otherwise rejects+ */+function deployToDevice (appPath, target, extraArgs) {+ events.emit('log', 'Deploying to device');+ // Deploying to device...+ if (target) {+ return superspawn.spawn('ios-deploy', ['--justlaunch', '-d', '-b', appPath, '-i', target].concat(extraArgs), { printCommand: true, stdio: 'inherit' });+ } else {+ return superspawn.spawn('ios-deploy', ['--justlaunch', '--no-wifi', '-d', '-b', appPath].concat(extraArgs), { printCommand: true, stdio: 'inherit' });+ }+}++/**+ * Deploy specified app package to ios-sim simulator+ * @param {String} appPath Path to application package+ * @param {String} target Target device type+ * @return {Promise} Resolves when deploy succeeds otherwise rejects+ */+function deployToSim (appPath, target) {+ events.emit('log', 'Deploying to simulator');+ if (!target) {+ // Select target device for emulator+ return require('./list-emulator-images').run()+ .then(function (emulators) {+ if (emulators.length > 0) {+ target = emulators[0];+ }+ emulators.forEach(function (emulator) {+ if (emulator.indexOf('iPhone') === 0) {+ target = emulator;+ }+ });+ events.emit('log', `No target specified for emulator. Deploying to "${target}" simulator.`);+ return startSim(appPath, target);+ });+ } else {+ return startSim(appPath, target);+ }+}++function startSim (appPath, target) {+ var logPath = path.join(cordovaPath, 'console.log');++ return iossimLaunch(appPath, 'com.apple.CoreSimulator.SimDeviceType.' + target, logPath, '--exit');+}++function iossimLaunch (appPath, devicetypeid, log, exit) {+ var f = path.resolve(path.dirname(require.resolve('ios-sim')), 'bin', 'ios-sim');+ var params = ['launch', appPath, '--devicetypeid', devicetypeid, '--log', log, exit];++ return superspawn.spawn(f, params, { cwd: projectPath, printCommand: true })+ .progress(function (stdio) {+ if (stdio.stderr) {+ events.emit('error', `[ios-sim] ${stdio.stderr}`);+ }+ if (stdio.stdout) {+ events.emit('log', `[ios-sim] ${stdio.stdout.trim()}`);+ }+ })+ .then(function (result) {+ events.emit('log', 'Simulator successfully started via `ios-sim`.');+ });+}++function listDevices () {+ return require('./list-devices').run()+ .then(function (devices) {+ events.emit('log', 'Available iOS Devices:');+ devices.forEach(function (device) {+ events.emit('log', '\t' + device);+ });+ });+}++function listEmulators () {+ return require('./list-emulator-images').run()+ .then(function (emulators) {+ events.emit('log', 'Available iOS Simulators:');+ emulators.forEach(function (emulator) {+ events.emit('log', '\t' + emulator);+ });+ });+}++module.exports.help = function () {+ console.log('\nUsage: run [ --device | [ --emulator [ --target=<id> ] ] ] [ --debug | --release | --nobuild ]');+ // TODO: add support for building different archs+ // console.log(" [ --archs=\"<list of target architectures>\" ] ");+ console.log(' --device : Deploys and runs the project on the connected device.');+ console.log(' --emulator : Deploys and runs the project on an emulator.');+ console.log(' --target=<id> : Deploys and runs the project on the specified target.');+ console.log(' --debug : Builds project in debug mode. (Passed down to build command, if necessary)');+ console.log(' --release : Builds project in release mode. (Passed down to build command, if necessary)');+ console.log(' --nobuild : Uses pre-built package, or errors if project is not built.');+ // TODO: add support for building different archs+ // console.log(" --archs : Specific chip architectures (`anycpu`, `arm`, `x86`, `x64`).");+ console.log('');+ console.log('Examples:');+ console.log(' run');+ console.log(' run --device');+ console.log(' run --emulator --target=\"iPhone-6-Plus\"'); /* eslint no-useless-escape : 0 */+ console.log(' run --device --release');+ console.log(' run --emulator --debug');+ console.log('');+ process.exit(0);+};diff --git a/cordova/platforms/ios/cordova/lib/spawn.js b/cordova/platforms/ios/cordova/lib/spawn.jsnew file mode 100755index 000000000..321b04f95--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/spawn.js@@ -0,0 +1,51 @@+/*+ 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 Q = require('q');+var proc = require('child_process');++/**+ * Run specified command with arguments+ * @param {String} cmd Command+ * @param {Array} args Array of arguments that should be passed to command+ * @param {String} opt_cwd Working directory for command+ * @param {String} opt_verbosity Verbosity level for command stdout output, "verbose" by default+ * @return {Promise} Promise either fullfilled or rejected with error code+ * @deprecated Use `require('cordova-common').superspawn` instead.+ */+module.exports = function (cmd, args, opt_cwd) {+ console.warn(+ 'This function is deprecated, may be removed from a future release. ' ++ "Use `require('cordova-common').superspawn` instead.");+ var d = Q.defer();+ try {+ var child = proc.spawn(cmd, args, { cwd: opt_cwd, stdio: 'inherit' });++ child.on('exit', function (code) {+ if (code) {+ d.reject('Error code ' + code + ' for command: ' + cmd + ' with args: ' + args);+ } else {+ d.resolve();+ }+ });+ } catch (e) {+ d.reject(e);+ }+ return d.promise;+};diff --git a/cordova/platforms/ios/cordova/lib/start-emulator b/cordova/platforms/ios/cordova/lib/start-emulatornew file mode 100755index 000000000..624335b1e--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/start-emulator@@ -0,0 +1,30 @@+#!/usr/bin/env bash+#+# 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.+#+# Run the below to get the device targets:+# xcrun instruments -s++set -e+++DEFAULT_TARGET="iPhone 5s"+TARGET=${1:-$DEFAULT_TARGET}+LIB_PATH=$( cd "$( dirname "$0" )" && pwd -P)++xcrun instruments -w "$TARGET" &> /dev/null\ No newline at end of filediff --git a/cordova/platforms/ios/cordova/lib/versions.js b/cordova/platforms/ios/cordova/lib/versions.jsnew file mode 100755index 000000000..828042f5e--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/versions.js@@ -0,0 +1,179 @@+#!/usr/bin/env node++/*+ 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 child_process = require('child_process');+var Q = require('q');+var semver = require('semver');++exports.get_apple_ios_version = function () {+ var d = Q.defer();+ child_process.exec('xcodebuild -showsdks', function (error, stdout, stderr) {+ if (error) {+ d.reject(stderr);+ } else {+ d.resolve(stdout);+ }+ });++ return d.promise.then(function (output) {+ var regex = /[0-9]*\.[0-9]*/;+ var versions = [];+ var regexIOS = /^iOS \d+/;+ output = output.split('\n');+ for (var i = 0; i < output.length; i++) {+ if (output[i].trim().match(regexIOS)) {+ versions[versions.length] = parseFloat(output[i].match(regex)[0]);+ }+ }+ versions.sort();+ console.log(versions[0]);+ return Q();+ }, function (stderr) {+ return Q.reject(stderr);+ });+};++exports.get_apple_osx_version = function () {+ var d = Q.defer();+ child_process.exec('xcodebuild -showsdks', function (error, stdout, stderr) {+ if (error) {+ d.reject(stderr);+ } else {+ d.resolve(stdout);+ }+ });++ return d.promise.then(function (output) {+ var regex = /[0-9]*\.[0-9]*/;+ var versions = [];+ var regexOSX = /^macOS \d+/;+ output = output.split('\n');+ for (var i = 0; i < output.length; i++) {+ if (output[i].trim().match(regexOSX)) {+ versions[versions.length] = parseFloat(output[i].match(regex)[0]);+ }+ }+ versions.sort();+ console.log(versions[0]);+ return Q();+ }, function (stderr) {+ return Q.reject(stderr);+ });+};++exports.get_apple_xcode_version = function () {+ var d = Q.defer();+ child_process.exec('xcodebuild -version', function (error, stdout, stderr) {+ var versionMatch = /Xcode (.*)/.exec(stdout);+ if (error || !versionMatch) {+ d.reject(stderr);+ } else {+ d.resolve(versionMatch[1]);+ }+ });+ return d.promise;+};++/**+ * Gets ios-deploy util version+ * @return {Promise} Promise that either resolved with ios-deploy version+ * or rejected in case of error+ */+exports.get_ios_deploy_version = function () {+ var d = Q.defer();+ child_process.exec('ios-deploy --version', function (error, stdout, stderr) {+ if (error) {+ d.reject(stderr);+ } else {+ d.resolve(stdout);+ }+ });+ return d.promise;+};++/**+ * Gets pod (CocoaPods) util version+ * @return {Promise} Promise that either resolved with pod version+ * or rejected in case of error+ */+exports.get_cocoapods_version = function () {+ var d = Q.defer();+ child_process.exec('pod --version', function (error, stdout, stderr) {+ if (error) {+ d.reject(stderr);+ } else {+ d.resolve(stdout);+ }+ });+ return d.promise;+};++/**+ * Gets ios-sim util version+ * @return {Promise} Promise that either resolved with ios-sim version+ * or rejected in case of error+ */+exports.get_ios_sim_version = function () {+ var d = Q.defer();+ child_process.exec('ios-sim --version', function (error, stdout, stderr) {+ if (error) {+ d.reject(stderr);+ } else {+ d.resolve(stdout);+ }+ });+ return d.promise;+};++/**+ * Gets specific tool version+ * @param {String} toolName Tool name to check. Known tools are 'xcodebuild', 'ios-sim' and 'ios-deploy'+ * @return {Promise} Promise that either resolved with tool version+ * or rejected in case of error+ */+exports.get_tool_version = function (toolName) {+ switch (toolName) {+ case 'xcodebuild': return exports.get_apple_xcode_version();+ case 'ios-sim': return exports.get_ios_sim_version();+ case 'ios-deploy': return exports.get_ios_deploy_version();+ case 'pod': return exports.get_cocoapods_version();+ default: return Q.reject(toolName + ' is not valid tool name. Valid names are: \'xcodebuild\', \'ios-sim\', \'ios-deploy\', and \'pod\'');+ }+};++/**+ * Compares two version strings that can be coerced to semver.+ *+ * @param {String} version1 Version to compare+ * @param {String} version2 Another version to compare+ * @return {Number} Negative number if first version is lower than the second,+ * positive otherwise and 0 if versions are equal.+ */+exports.compareVersions = (...args) => {+ const coerceToSemverIfInvalid = v => {+ const semverVersion = semver.parse(v) || semver.coerce(v);+ if (!semverVersion) throw new TypeError(`Invalid Version: ${v}`);+ return semverVersion;+ };++ const semverVersions = args.map(coerceToSemverIfInvalid);+ return semver.compare(...semverVersions);+};diff --git a/cordova/platforms/ios/cordova/log b/cordova/platforms/ios/cordova/lognew file mode 100755index 000000000..b235b09fd--- /dev/null+++ b/cordova/platforms/ios/cordova/log@@ -0,0 +1,23 @@+#! /bin/sh+#+# 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.+#++CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd -P)++tail -f "$CORDOVA_PATH/console.log"diff --git a/cordova/platforms/ios/cordova/log.bat b/cordova/platforms/ios/cordova/log.batnew file mode 100755index 000000000..4710e57e8--- /dev/null+++ b/cordova/platforms/ios/cordova/log.bat@@ -0,0 +1,19 @@+:: 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++@ECHO OFF+ECHO WARN: The 'log' command is not available for cordova-ios on windows machines.>&2diff --git a/cordova/platforms/ios/cordova/loggingHelper.js b/cordova/platforms/ios/cordova/loggingHelper.jsnew file mode 100755index 000000000..e353399c0--- /dev/null+++ b/cordova/platforms/ios/cordova/loggingHelper.js@@ -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.+*/++var CordovaLogger = require('cordova-common').CordovaLogger;++module.exports = {+ adjustLoggerLevel: function (opts) {+ if (opts.verbose || (Array.isArray(opts) && opts.indexOf('--verbose') !== -1)) {+ CordovaLogger.get().setLevel('verbose');+ } else if (opts.silent || (Array.isArray(opts) && opts.indexOf('--silent') !== -1)) {+ CordovaLogger.get().setLevel('error');+ }+ }+};diff --git a/cordova/platforms/ios/cordova/run b/cordova/platforms/ios/cordova/runnew file mode 100755index 000000000..81741c84f--- /dev/null+++ b/cordova/platforms/ios/cordova/run@@ -0,0 +1,63 @@+#!/usr/bin/env node++/*+ 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 args = process.argv;+var Api = require('./Api');+var nopt = require('nopt');++// Handle help flag+if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {+ require('./lib/run').help();+ process.exit(0);+}++// Parse arguments (includes build params as well)+var opts = nopt({+ 'verbose': Boolean,+ 'silent': Boolean,+ 'debug': Boolean,+ 'release': Boolean,+ 'nobuild': Boolean,+ 'archs': String,+ 'list': Boolean,+ 'device': Boolean,+ 'emulator': Boolean,+ 'target': String,+ 'codeSignIdentity': String,+ 'codeSignResourceRules': String,+ 'provisioningProfile': String,+ 'automaticProvisioning': Boolean,+ 'buildConfig': String,+ 'noSign': Boolean+}, { 'd': '--verbose' }, args);++// Make options compatible with PlatformApi build method spec+opts.argv = opts.argv.remain;++require('./loggingHelper').adjustLoggerLevel(opts);++new Api().run(opts).done(function () {+ console.log('** RUN SUCCEEDED **');+}, function (err) {+ var errorMessage = (err && err.stack) ? err.stack : err;+ console.error(errorMessage);+ process.exit(2);+});diff --git a/cordova/platforms/ios/cordova/run.bat b/cordova/platforms/ios/cordova/run.batnew file mode 100755index 000000000..8a3cad2ad--- /dev/null+++ b/cordova/platforms/ios/cordova/run.bat@@ -0,0 +1,19 @@+:: 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++@ECHO OFF+ECHO WARN: The `run` is not available for cordova-ios on windows machines.>&2diff --git a/cordova/platforms/ios/cordova/version b/cordova/platforms/ios/cordova/versionnew file mode 100755index 000000000..8a81e66fb--- /dev/null+++ b/cordova/platforms/ios/cordova/version@@ -0,0 +1,35 @@+#!/usr/bin/env node++/*+ 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.+*/++/*++ Returns the VERSION of CordovaLib used.+ Note: it does not work if the --shared option was used to create the project.+*/++// Coho updates this line+var VERSION = '5.1.1';++module.exports.version = VERSION;++if (!module.parent) {+ console.log(VERSION);+}diff --git a/cordova/platforms/ios/cordova/version.bat b/cordova/platforms/ios/cordova/version.batnew file mode 100755index 000000000..84c86b438--- /dev/null+++ b/cordova/platforms/ios/cordova/version.bat@@ -0,0 +1,26 @@+:: 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.++@ECHO OFF+SET script="%~dp0version"+IF EXIST %script% (+ node %script% %*+) ELSE (+ ECHO.+ ECHO ERROR: Could not find 'version' script in 'cordova' folder, aborting...>&2+ EXIT /B 1+)diff --git a/cordova/platforms/ios/frameworks.json b/cordova/platforms/ios/frameworks.jsonnew file mode 100644index 000000000..dba8af258--- /dev/null+++ b/cordova/platforms/ios/frameworks.json@@ -0,0 +1,5 @@+{+ "ImageIO.framework": 1,+ "CoreLocation.framework": 1,+ "AVFoundation.framework": 1+}\ No newline at end of filediff --git a/cordova/platforms/ios/ios.json b/cordova/platforms/ios/ios.jsonnew file mode 100644index 000000000..4b7c4fde2--- /dev/null+++ b/cordova/platforms/ios/ios.json@@ -0,0 +1,311 @@+{+ "prepare_queue": {+ "installed": [],+ "uninstalled": []+ },+ "config_munge": {+ "files": {+ "config.xml": {+ "parents": {+ "/*": [+ {+ "xml": "<feature name=\"Device\"><param name=\"ios-package\" value=\"CDVDevice\" /></feature>",+ "count": 1+ },+ {+ "xml": "<feature name=\"BackgroundMode\"><param name=\"ios-package\" onload=\"true\" value=\"APPBackgroundMode\" /><param name=\"onload\" value=\"true\" /></feature>",+ "count": 1+ },+ {+ "xml": "<feature name=\"Camera\"><param name=\"ios-package\" value=\"CDVCamera\" /></feature>",+ "count": 1+ },+ {+ "xml": "<preference name=\"CameraUsesGeolocation\" value=\"false\" />",+ "count": 1+ },+ {+ "xml": "<feature name=\"File\"><param name=\"ios-package\" value=\"CDVFile\" /><param name=\"onload\" value=\"true\" /></feature>",+ "count": 1+ },+ {+ "xml": "<feature name=\"FileOpener2\"><param name=\"ios-package\" value=\"FileOpener2\" /></feature>",+ "count": 1+ }+ ]+ }+ },+ "*-Info.plist": {+ "parents": {+ "UIBackgroundModes": [+ {+ "xml": "<array><string>audio</string></array>",+ "count": 1+ }+ ]+ }+ }+ }+ },+ "installed_plugins": {+ "cordova-plugin-device": {+ "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ },+ "cordova-plugin-background-mode": {+ "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ },+ "cordova-plugin-camera": {+ "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ },+ "cordova-plugin-file": {+ "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ },+ "cordova-plugin-file-opener2": {+ "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ },+ "cordova-plugin-whitelist": {+ "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ }+ },+ "dependent_plugins": {},+ "modules": [+ {+ "id": "cordova-plugin-device.device",+ "file": "plugins/cordova-plugin-device/www/device.js",+ "pluginId": "cordova-plugin-device",+ "clobbers": [+ "device"+ ]+ },+ {+ "id": "cordova-plugin-background-mode.BackgroundMode",+ "file": "plugins/cordova-plugin-background-mode/www/background-mode.js",+ "pluginId": "cordova-plugin-background-mode",+ "clobbers": [+ "cordova.plugins.backgroundMode",+ "plugin.backgroundMode"+ ]+ },+ {+ "id": "cordova-plugin-camera.Camera",+ "file": "plugins/cordova-plugin-camera/www/CameraConstants.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "Camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverOptions",+ "file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverOptions"+ ]+ },+ {+ "id": "cordova-plugin-camera.camera",+ "file": "plugins/cordova-plugin-camera/www/Camera.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "navigator.camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverHandle",+ "file": "plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverHandle"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryEntry",+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryReader",+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryReader"+ ]+ },+ {+ "id": "cordova-plugin-file.Entry",+ "file": "plugins/cordova-plugin-file/www/Entry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Entry"+ ]+ },+ {+ "id": "cordova-plugin-file.File",+ "file": "plugins/cordova-plugin-file/www/File.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.File"+ ]+ },+ {+ "id": "cordova-plugin-file.FileEntry",+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.FileError",+ "file": "plugins/cordova-plugin-file/www/FileError.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileError"+ ]+ },+ {+ "id": "cordova-plugin-file.FileReader",+ "file": "plugins/cordova-plugin-file/www/FileReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileReader"+ ]+ },+ {+ "id": "cordova-plugin-file.FileSystem",+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadOptions",+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadOptions"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadResult",+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadResult"+ ]+ },+ {+ "id": "cordova-plugin-file.FileWriter",+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileWriter"+ ]+ },+ {+ "id": "cordova-plugin-file.Flags",+ "file": "plugins/cordova-plugin-file/www/Flags.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Flags"+ ]+ },+ {+ "id": "cordova-plugin-file.LocalFileSystem",+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.LocalFileSystem"+ ],+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.Metadata",+ "file": "plugins/cordova-plugin-file/www/Metadata.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Metadata"+ ]+ },+ {+ "id": "cordova-plugin-file.ProgressEvent",+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.ProgressEvent"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems",+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",+ "pluginId": "cordova-plugin-file"+ },+ {+ "id": "cordova-plugin-file.requestFileSystem",+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.requestFileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.isChrome",+ "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.iosFileSystem",+ "file": "plugins/cordova-plugin-file/www/ios/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems-roots",+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.fileSystemPaths",+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "cordova"+ ],+ "runs": true+ },+ {+ "id": "cordova-plugin-file-opener2.FileOpener2",+ "file": "plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js",+ "pluginId": "cordova-plugin-file-opener2",+ "clobbers": [+ "cordova.plugins.fileOpener2"+ ]+ }+ ],+ "plugin_metadata": {+ "cordova-plugin-device": "2.0.3",+ "cordova-plugin-background-mode": "0.7.3",+ "cordova-plugin-camera": "4.1.0",+ "cordova-plugin-file": "6.0.2",+ "cordova-plugin-file-opener2": "3.0.4",+ "cordova-plugin-whitelist": "1.3.4"+ }+}diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/.eslintrc.yml b/cordova/platforms/ios/platform_www/cordova-js-src/.eslintrc.ymlnew file mode 100644index 000000000..e3d49d8a0--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova-js-src/.eslintrc.yml@@ -0,0 +1,4 @@+env:+ node: false+ commonjs: true+ browser: truediff --git a/cordova/platforms/ios/platform_www/cordova-js-src/exec.js b/cordova/platforms/ios/platform_www/cordova-js-src/exec.jsnew file mode 100644index 000000000..e7f6ce1c6--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova-js-src/exec.js@@ -0,0 +1,262 @@+/*+ *+ * 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.+ *+*/++/* global require, module, atob, document */++/**+ * Creates a gap bridge iframe used to notify the native code about queued+ * commands.+ */+var cordova = require('cordova');+var utils = require('cordova/utils');+var base64 = require('cordova/base64');+var execIframe;+var commandQueue = []; // Contains pending JS->Native messages.+var isInContextOfEvalJs = 0;+var failSafeTimerId = 0;++function massageArgsJsToNative (args) {+ if (!args || utils.typeName(args) !== 'Array') {+ return args;+ }+ var ret = [];+ args.forEach(function (arg, i) {+ if (utils.typeName(arg) === 'ArrayBuffer') {+ ret.push({+ 'CDVType': 'ArrayBuffer',+ 'data': base64.fromArrayBuffer(arg)+ });+ } else {+ ret.push(arg);+ }+ });+ return ret;+}++function massageMessageNativeToJs (message) {+ if (message.CDVType === 'ArrayBuffer') {+ var stringToArrayBuffer = function (str) {+ var ret = new Uint8Array(str.length);+ for (var i = 0; i < str.length; i++) {+ ret[i] = str.charCodeAt(i);+ }+ return ret.buffer;+ };+ var base64ToArrayBuffer = function (b64) {+ return stringToArrayBuffer(atob(b64));+ };+ message = base64ToArrayBuffer(message.data);+ }+ return message;+}++function convertMessageToArgsNativeToJs (message) {+ var args = [];+ if (!message || !message.hasOwnProperty('CDVType')) {+ args.push(message);+ } else if (message.CDVType === 'MultiPart') {+ message.messages.forEach(function (e) {+ args.push(massageMessageNativeToJs(e));+ });+ } else {+ args.push(massageMessageNativeToJs(message));+ }+ return args;+}++function iOSExec () {++ var successCallback, failCallback, service, action, actionArgs;+ var callbackId = null;+ if (typeof arguments[0] !== 'string') {+ // FORMAT ONE+ successCallback = arguments[0];+ failCallback = arguments[1];+ service = arguments[2];+ action = arguments[3];+ actionArgs = arguments[4];++ // Since we need to maintain backwards compatibility, we have to pass+ // an invalid callbackId even if no callback was provided since plugins+ // will be expecting it. The Cordova.exec() implementation allocates+ // an invalid callbackId and passes it even if no callbacks were given.+ callbackId = 'INVALID';+ } else {+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' ++ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'+ );+ }++ // If actionArgs is not provided, default to an empty array+ actionArgs = actionArgs || [];++ // Register the callbacks and add the callbackId to the positional+ // arguments if given.+ if (successCallback || failCallback) {+ callbackId = service + cordova.callbackId++;+ cordova.callbacks[callbackId] =+ { success: successCallback, fail: failCallback };+ }++ actionArgs = massageArgsJsToNative(actionArgs);++ var command = [callbackId, service, action, actionArgs];++ // Stringify and queue the command. We stringify to command now to+ // effectively clone the command arguments in case they are mutated before+ // the command is executed.+ commandQueue.push(JSON.stringify(command));++ // If we're in the context of a stringByEvaluatingJavaScriptFromString call,+ // then the queue will be flushed when it returns; no need for a poke.+ // Also, if there is already a command in the queue, then we've already+ // poked the native side, so there is no reason to do so again.+ if (!isInContextOfEvalJs && commandQueue.length === 1) {+ pokeNative();+ }+}++// CB-10530+function proxyChanged () {+ var cexec = cordovaExec();++ return (execProxy !== cexec && // proxy objects are different+ iOSExec !== cexec // proxy object is not the current iOSExec+ );+}++// CB-10106+function handleBridgeChange () {+ if (proxyChanged()) {+ var commandString = commandQueue.shift();+ while (commandString) {+ var command = JSON.parse(commandString);+ var callbackId = command[0];+ var service = command[1];+ var action = command[2];+ var actionArgs = command[3];+ var callbacks = cordova.callbacks[callbackId] || {};++ execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);++ commandString = commandQueue.shift();+ }+ return true;+ }++ return false;+}++function pokeNative () {+ // CB-5488 - Don't attempt to create iframe before document.body is available.+ if (!document.body) {+ setTimeout(pokeNative);+ return;+ }++ // Check if they've removed it from the DOM, and put it back if so.+ if (execIframe && execIframe.contentWindow) {+ execIframe.contentWindow.location = 'gap://ready';+ } else {+ execIframe = document.createElement('iframe');+ execIframe.style.display = 'none';+ execIframe.src = 'gap://ready';+ document.body.appendChild(execIframe);+ }+ // Use a timer to protect against iframe being unloaded during the poke (CB-7735).+ // This makes the bridge ~ 7% slower, but works around the poke getting lost+ // when the iframe is removed from the DOM.+ // An onunload listener could be used in the case where the iframe has just been+ // created, but since unload events fire only once, it doesn't work in the normal+ // case of iframe reuse (where unload will have already fired due to the attempted+ // navigation of the page).+ failSafeTimerId = setTimeout(function () {+ if (commandQueue.length) {+ // CB-10106 - flush the queue on bridge change+ if (!handleBridgeChange()) {+ pokeNative();+ }+ }+ }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).+}++iOSExec.nativeFetchMessages = function () {+ // Stop listing for window detatch once native side confirms poke.+ if (failSafeTimerId) {+ clearTimeout(failSafeTimerId);+ failSafeTimerId = 0;+ }+ // Each entry in commandQueue is a JSON string already.+ if (!commandQueue.length) {+ return '';+ }+ var json = '[' + commandQueue.join(',') + ']';+ commandQueue.length = 0;+ return json;+};++iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {+ return iOSExec.nativeEvalAndFetch(function () {+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ function nc2 () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback);+ }+ setTimeout(nc2, 0);+ });+};++iOSExec.nativeEvalAndFetch = function (func) {+ // This shouldn't be nested, but better to be safe.+ isInContextOfEvalJs++;+ try {+ func();+ return iOSExec.nativeFetchMessages();+ } finally {+ isInContextOfEvalJs--;+ }+};++// Proxy the exec for bridge changes. See CB-10106++function cordovaExec () {+ var cexec = require('cordova/exec');+ var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function');+ return (cexec_valid && execProxy !== cexec) ? cexec : iOSExec;+}++function execProxy () {+ cordovaExec().apply(null, arguments);+}++execProxy.nativeFetchMessages = function () {+ return cordovaExec().nativeFetchMessages.apply(null, arguments);+};++execProxy.nativeEvalAndFetch = function () {+ return cordovaExec().nativeEvalAndFetch.apply(null, arguments);+};++execProxy.nativeCallback = function () {+ return cordovaExec().nativeCallback.apply(null, arguments);+};++module.exports = execProxy;diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/platform.js b/cordova/platforms/ios/platform_www/cordova-js-src/platform.jsnew file mode 100644index 000000000..2345fa5b7--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova-js-src/platform.js@@ -0,0 +1,31 @@+/*+ *+ * 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.+ *+*/++module.exports = {+ id: 'ios',+ bootstrap: function () {+ // Attach the console polyfill that is iOS-only to window.console+ // see the file under plugin/ios/console.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');++ require('cordova/channel').onNativeReady.fire();+ }+};diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/console.js b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/console.jsnew file mode 100644index 000000000..0a4820ede--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/console.js@@ -0,0 +1,186 @@+/*+ *+ * 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 logger = require('cordova/plugin/ios/logger');++// ------------------------------------------------------------------------------+// object that we're exporting+// ------------------------------------------------------------------------------+var console = module.exports;++// ------------------------------------------------------------------------------+// copy of the original console object+// ------------------------------------------------------------------------------+var WinConsole = window.console;++// ------------------------------------------------------------------------------+// whether to use the logger+// ------------------------------------------------------------------------------+var UseLogger = false;++// ------------------------------------------------------------------------------+// Timers+// ------------------------------------------------------------------------------+var Timers = {};++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+function noop () {}++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+console.useLogger = function (value) {+ if (arguments.length) UseLogger = !!value;++ if (UseLogger) {+ if (logger.useConsole()) {+ throw new Error('console and logger are too intertwingly');+ }+ }++ return UseLogger;+};++// ------------------------------------------------------------------------------+console.log = function () {+ if (logger.useConsole()) return;+ logger.log.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.error = function () {+ if (logger.useConsole()) return;+ logger.error.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.warn = function () {+ if (logger.useConsole()) return;+ logger.warn.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.info = function () {+ if (logger.useConsole()) return;+ logger.info.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.debug = function () {+ if (logger.useConsole()) return;+ logger.debug.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.assert = function (expression) {+ if (expression) return;++ var message = logger.format.apply(logger.format, [].slice.call(arguments, 1));+ console.log('ASSERT: ' + message);+};++// ------------------------------------------------------------------------------+console.clear = function () {};++// ------------------------------------------------------------------------------+console.dir = function (object) {+ console.log('%o', object);+};++// ------------------------------------------------------------------------------+console.dirxml = function (node) {+ console.log(node.innerHTML);+};++// ------------------------------------------------------------------------------+console.trace = noop;++// ------------------------------------------------------------------------------+console.group = console.log;++// ------------------------------------------------------------------------------+console.groupCollapsed = console.log;++// ------------------------------------------------------------------------------+console.groupEnd = noop;++// ------------------------------------------------------------------------------+console.time = function (name) {+ Timers[name] = new Date().valueOf();+};++// ------------------------------------------------------------------------------+console.timeEnd = function (name) {+ var timeStart = Timers[name];+ if (!timeStart) {+ console.warn('unknown timer: ' + name);+ return;+ }++ var timeElapsed = new Date().valueOf() - timeStart;+ console.log(name + ': ' + timeElapsed + 'ms');+};++// ------------------------------------------------------------------------------+console.timeStamp = noop;++// ------------------------------------------------------------------------------+console.profile = noop;++// ------------------------------------------------------------------------------+console.profileEnd = noop;++// ------------------------------------------------------------------------------+console.count = noop;++// ------------------------------------------------------------------------------+console.exception = console.log;++// ------------------------------------------------------------------------------+console.table = function (data, columns) {+ console.log('%o', data);+};++// ------------------------------------------------------------------------------+// return a new function that calls both functions passed as args+// ------------------------------------------------------------------------------+function wrappedOrigCall (orgFunc, newFunc) {+ return function () {+ var args = [].slice.call(arguments);+ try { orgFunc.apply(WinConsole, args); } catch (e) {}+ try { newFunc.apply(console, args); } catch (e) {}+ };+}++// ------------------------------------------------------------------------------+// For every function that exists in the original console object, that+// also exists in the new console object, wrap the new console method+// with one that calls both+// ------------------------------------------------------------------------------+for (var key in console) {+ if (typeof WinConsole[key] === 'function') {+ console[key] = wrappedOrigCall(WinConsole[key], console[key]);+ }+}diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/logger.js b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/logger.jsnew file mode 100644index 000000000..7dc82e36a--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/logger.js@@ -0,0 +1,349 @@+/*+ *+ * 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.+ *+*/++// ------------------------------------------------------------------------------+// The logger module exports the following properties/functions:+//+// LOG - constant for the level LOG+// ERROR - constant for the level ERROR+// WARN - constant for the level WARN+// INFO - constant for the level INFO+// DEBUG - constant for the level DEBUG+// logLevel() - returns current log level+// logLevel(value) - sets and returns a new log level+// useConsole() - returns whether logger is using console+// useConsole(value) - sets and returns whether logger is using console+// log(message,...) - logs a message at level LOG+// error(message,...) - logs a message at level ERROR+// warn(message,...) - logs a message at level WARN+// info(message,...) - logs a message at level INFO+// debug(message,...) - logs a message at level DEBUG+// logLevel(level,message,...) - logs a message specified level+//+// ------------------------------------------------------------------------------++var logger = exports;++var exec = require('cordova/exec');++var UseConsole = false;+var UseLogger = true;+var Queued = [];+var DeviceReady = false;+var CurrentLevel;++var originalConsole = console;++/**+ * Logging levels+ */++var Levels = [+ 'LOG',+ 'ERROR',+ 'WARN',+ 'INFO',+ 'DEBUG'+];++/*+ * add the logging levels to the logger object and+ * to a separate levelsMap object for testing+ */++var LevelsMap = {};+for (var i = 0; i < Levels.length; i++) {+ var level = Levels[i];+ LevelsMap[level] = i;+ logger[level] = level;+}++CurrentLevel = LevelsMap.WARN;++/**+ * Getter/Setter for the logging level+ *+ * Returns the current logging level.+ *+ * When a value is passed, sets the logging level to that value.+ * The values should be one of the following constants:+ * logger.LOG+ * logger.ERROR+ * logger.WARN+ * logger.INFO+ * logger.DEBUG+ *+ * The value used determines which messages get printed. The logging+ * values above are in order, and only messages logged at the logging+ * level or above will actually be displayed to the user. E.g., the+ * default level is WARN, so only messages logged with LOG, ERROR, or+ * WARN will be displayed; INFO and DEBUG messages will be ignored.+ */+logger.level = function (value) {+ if (arguments.length) {+ if (LevelsMap[value] === null) {+ throw new Error('invalid logging level: ' + value);+ }+ CurrentLevel = LevelsMap[value];+ }++ return Levels[CurrentLevel];+};++/**+ * Getter/Setter for the useConsole functionality+ *+ * When useConsole is true, the logger will log via the+ * browser 'console' object.+ */+logger.useConsole = function (value) {+ if (arguments.length) UseConsole = !!value;++ if (UseConsole) {+ if (typeof console === 'undefined') {+ throw new Error('global console object is not defined');+ }++ if (typeof console.log !== 'function') {+ throw new Error('global console object does not have a log function');+ }++ if (typeof console.useLogger === 'function') {+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }+ }+ }++ return UseConsole;+};++/**+ * Getter/Setter for the useLogger functionality+ *+ * When useLogger is true, the logger will log via the+ * native Logger plugin.+ */+logger.useLogger = function (value) {+ // Enforce boolean+ if (arguments.length) UseLogger = !!value;+ return UseLogger;+};++/**+ * Logs a message at the LOG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.log = function (message) { logWithArgs('LOG', arguments); };++/**+ * Logs a message at the ERROR level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.error = function (message) { logWithArgs('ERROR', arguments); };++/**+ * Logs a message at the WARN level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.warn = function (message) { logWithArgs('WARN', arguments); };++/**+ * Logs a message at the INFO level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.info = function (message) { logWithArgs('INFO', arguments); };++/**+ * Logs a message at the DEBUG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.debug = function (message) { logWithArgs('DEBUG', arguments); };++// log at the specified level with args+function logWithArgs (level, args) {+ args = [level].concat([].slice.call(args));+ logger.logLevel.apply(logger, args);+}++// return the correct formatString for an object+function formatStringForMessage (message) {+ return (typeof message === 'string') ? '' : '%o';+}++/**+ * Logs a message at the specified level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.logLevel = function (level /* , ... */) {+ // format the message with the parameters+ var formatArgs = [].slice.call(arguments, 1);+ var fmtString = formatStringForMessage(formatArgs[0]);+ if (fmtString.length > 0) {+ formatArgs.unshift(fmtString); // add formatString+ }++ var message = logger.format.apply(logger.format, formatArgs);++ if (LevelsMap[level] === null) {+ throw new Error('invalid logging level: ' + level);+ }++ if (LevelsMap[level] > CurrentLevel) return;++ // queue the message if not yet at deviceready+ if (!DeviceReady && !UseConsole) {+ Queued.push([level, message]);+ return;+ }++ // Log using the native logger if that is enabled+ if (UseLogger) {+ exec(null, null, 'Console', 'logLevel', [level, message]);+ }++ // Log using the console if that is enabled+ if (UseConsole) {+ // make sure console is not using logger+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }++ // log to the console+ switch (level) {+ case logger.LOG: originalConsole.log(message); break;+ case logger.ERROR: originalConsole.log('ERROR: ' + message); break;+ case logger.WARN: originalConsole.log('WARN: ' + message); break;+ case logger.INFO: originalConsole.log('INFO: ' + message); break;+ case logger.DEBUG: originalConsole.log('DEBUG: ' + message); break;+ }+ }+};++/**+ * Formats a string and arguments following it ala console.log()+ *+ * Any remaining arguments will be appended to the formatted string.+ *+ * for rationale, see FireBug's Console API:+ * http://getfirebug.com/wiki/index.php/Console_API+ */+logger.format = function (formatString, args) {+ return __format(arguments[0], [].slice.call(arguments, 1)).join(' ');+};++// ------------------------------------------------------------------------------+/**+ * Formats a string and arguments following it ala vsprintf()+ *+ * format chars:+ * %j - format arg as JSON+ * %o - format arg as JSON+ * %c - format arg as ''+ * %% - replace with '%'+ * any other char following % will format it's+ * arg via toString().+ *+ * Returns an array containing the formatted string and any remaining+ * arguments.+ */+function __format (formatString, args) {+ if (formatString === null || formatString === undefined) return [''];+ if (arguments.length === 1) return [formatString.toString()];++ if (typeof formatString !== 'string') { formatString = formatString.toString(); }++ var pattern = /(.*?)%(.)(.*)/;+ var rest = formatString;+ var result = [];++ while (args.length) {+ var match = pattern.exec(rest);+ if (!match) break;++ var arg = args.shift();+ rest = match[3];+ result.push(match[1]);++ if (match[2] === '%') {+ result.push('%');+ args.unshift(arg);+ continue;+ }++ result.push(__formatted(arg, match[2]));+ }++ result.push(rest);++ var remainingArgs = [].slice.call(args);+ remainingArgs.unshift(result.join(''));+ return remainingArgs;+}++function __formatted (object, formatChar) {++ try {+ switch (formatChar) {+ case 'j':+ case 'o': return JSON.stringify(object);+ case 'c': return '';+ }+ } catch (e) {+ return 'error JSON.stringify()ing argument: ' + e;+ }++ if ((object === null) || (object === undefined)) {+ return Object.prototype.toString.call(object);+ }++ return object.toString();+}++// ------------------------------------------------------------------------------+// when deviceready fires, log queued messages+logger.__onDeviceReady = function () {+ if (DeviceReady) return;++ DeviceReady = true;++ for (var i = 0; i < Queued.length; i++) {+ var messageArgs = Queued[i];+ logger.logLevel(messageArgs[0], messageArgs[1]);+ }++ Queued = null;+};++// add a deviceready event to log queued messages+document.addEventListener('deviceready', logger.__onDeviceReady, false);diff --git a/cordova/platforms/ios/platform_www/cordova.js b/cordova/platforms/ios/platform_www/cordova.jsnew file mode 100644index 000000000..9813b231f--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova.js@@ -0,0 +1,2188 @@+// Platform: ios+// 9c79667cd175f51fd2edf2dc91ac8be98b89076a+/*+ 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.+*/+;(function() {+var PLATFORM_VERSION_BUILD_LABEL = '5.1.1';+// file: src/scripts/require.js+var require;+var define;++(function () {+ var modules = {};+ // Stack of moduleIds currently being built.+ var requireStack = [];+ // Map of module ID -> index into requireStack of modules currently being built.+ var inProgressModules = {};+ var SEPARATOR = '.';++ function build (module) {+ var factory = module.factory;+ var localRequire = function (id) {+ var resultantId = id;+ // Its a relative path, so lop off the last portion and add the id (minus "./")+ if (id.charAt(0) === '.') {+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2);+ }+ return require(resultantId);+ };+ module.exports = {};+ delete module.factory;+ factory(localRequire, module.exports, module);+ return module.exports;+ }++ require = function (id) {+ if (!modules[id]) {+ throw 'module ' + id + ' not found';+ } else if (id in inProgressModules) {+ var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;+ throw 'Cycle in require graph: ' + cycle;+ }+ if (modules[id].factory) {+ try {+ inProgressModules[id] = requireStack.length;+ requireStack.push(id);+ return build(modules[id]);+ } finally {+ delete inProgressModules[id];+ requireStack.pop();+ }+ }+ return modules[id].exports;+ };++ define = function (id, factory) {+ if (Object.prototype.hasOwnProperty.call(modules, id)) {+ throw 'module ' + id + ' already defined';+ }++ modules[id] = {+ id: id,+ factory: factory+ };+ };++ define.remove = function (id) {+ delete modules[id];+ };++ define.moduleMap = modules;+})();++// Export for use in node+if (typeof module === 'object' && typeof require === 'function') {+ module.exports.require = require;+ module.exports.define = define;+}++// file: src/cordova.js+define("cordova", function(require, exports, module) {++// Workaround for Windows 10 in hosted environment case+// http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object+if (window.cordova && !(window.cordova instanceof HTMLElement)) {+ throw new Error('cordova already defined');+}++var channel = require('cordova/channel');+var platform = require('cordova/platform');++/**+ * Intercept calls to addEventListener + removeEventListener and handle deviceready,+ * resume, and pause events.+ */+var m_document_addEventListener = document.addEventListener;+var m_document_removeEventListener = document.removeEventListener;+var m_window_addEventListener = window.addEventListener;+var m_window_removeEventListener = window.removeEventListener;++/**+ * Houses custom event handlers to intercept on document + window event listeners.+ */+var documentEventHandlers = {};+var windowEventHandlers = {};++document.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].subscribe(handler);+ } else {+ m_document_addEventListener.call(document, evt, handler, capture);+ }+};++window.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].subscribe(handler);+ } else {+ m_window_addEventListener.call(window, evt, handler, capture);+ }+};++document.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].unsubscribe(handler);+ } else {+ m_document_removeEventListener.call(document, evt, handler, capture);+ }+};++window.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].unsubscribe(handler);+ } else {+ m_window_removeEventListener.call(window, evt, handler, capture);+ }+};++function createEvent (type, data) {+ var event = document.createEvent('Events');+ event.initEvent(type, false, false);+ if (data) {+ for (var i in data) {+ if (data.hasOwnProperty(i)) {+ event[i] = data[i];+ }+ }+ }+ return event;+}++var cordova = {+ define: define,+ require: require,+ version: PLATFORM_VERSION_BUILD_LABEL,+ platformVersion: PLATFORM_VERSION_BUILD_LABEL,+ platformId: platform.id,++ /**+ * Methods to add/remove your own addEventListener hijacking on document + window.+ */+ addWindowEventHandler: function (event) {+ return (windowEventHandlers[event] = channel.create(event));+ },+ addStickyDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.createSticky(event));+ },+ addDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.create(event));+ },+ removeWindowEventHandler: function (event) {+ delete windowEventHandlers[event];+ },+ removeDocumentEventHandler: function (event) {+ delete documentEventHandlers[event];+ },++ /**+ * Retrieve original event handlers that were replaced by Cordova+ *+ * @return object+ */+ getOriginalHandlers: function () {+ return {+ document: {+ addEventListener: m_document_addEventListener,+ removeEventListener: m_document_removeEventListener+ },+ window: {+ addEventListener: m_window_addEventListener,+ removeEventListener: m_window_removeEventListener+ }+ };+ },++ /**+ * Method to fire event from native code+ * bNoDetach is required for events which cause an exception which needs to be caught in native code+ */+ fireDocumentEvent: function (type, data, bNoDetach) {+ var evt = createEvent(type, data);+ if (typeof documentEventHandlers[type] !== 'undefined') {+ if (bNoDetach) {+ documentEventHandlers[type].fire(evt);+ } else {+ setTimeout(function () {+ // Fire deviceready on listeners that were registered before cordova.js was loaded.+ if (type === 'deviceready') {+ document.dispatchEvent(evt);+ }+ documentEventHandlers[type].fire(evt);+ }, 0);+ }+ } else {+ document.dispatchEvent(evt);+ }+ },++ fireWindowEvent: function (type, data) {+ var evt = createEvent(type, data);+ if (typeof windowEventHandlers[type] !== 'undefined') {+ setTimeout(function () {+ windowEventHandlers[type].fire(evt);+ }, 0);+ } else {+ window.dispatchEvent(evt);+ }+ },++ /**+ * Plugin callback mechanism.+ */+ // Randomize the starting callbackId to avoid collisions after refreshing or navigating.+ // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.+ callbackId: Math.floor(Math.random() * 2000000000),+ callbacks: {},+ callbackStatus: {+ NO_RESULT: 0,+ OK: 1,+ CLASS_NOT_FOUND_EXCEPTION: 2,+ ILLEGAL_ACCESS_EXCEPTION: 3,+ INSTANTIATION_EXCEPTION: 4,+ MALFORMED_URL_EXCEPTION: 5,+ IO_EXCEPTION: 6,+ INVALID_ACTION: 7,+ JSON_EXCEPTION: 8,+ ERROR: 9+ },++ /**+ * Called by native code when returning successful result from an action.+ */+ callbackSuccess: function (callbackId, args) {+ cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning error result from an action.+ */+ callbackError: function (callbackId, args) {+ // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.+ // Derive success from status.+ cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning the result from an action.+ */+ callbackFromNative: function (callbackId, isSuccess, status, args, keepCallback) {+ try {+ var callback = cordova.callbacks[callbackId];+ if (callback) {+ if (isSuccess && status === cordova.callbackStatus.OK) {+ callback.success && callback.success.apply(null, args);+ } else if (!isSuccess) {+ callback.fail && callback.fail.apply(null, args);+ }+ /*+ else+ Note, this case is intentionally not caught.+ this can happen if isSuccess is true, but callbackStatus is NO_RESULT+ which is used to remove a callback from the list without calling the callbacks+ typically keepCallback is false in this case+ */+ // Clear callback if not expecting any more results+ if (!keepCallback) {+ delete cordova.callbacks[callbackId];+ }+ }+ } catch (err) {+ var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;+ console && console.log && console.log(msg);+ console && console.log && err.stack && console.log(err.stack);+ cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ throw err;+ }+ },++ addConstructor: function (func) {+ channel.onCordovaReady.subscribe(function () {+ try {+ func();+ } catch (e) {+ console.log('Failed to run constructor: ' + e);+ }+ });+ }+};++module.exports = cordova;++});++// file: src/common/argscheck.js+define("cordova/argscheck", function(require, exports, module) {++var utils = require('cordova/utils');++var moduleExports = module.exports;++var typeMap = {+ 'A': 'Array',+ 'D': 'Date',+ 'N': 'Number',+ 'S': 'String',+ 'F': 'Function',+ 'O': 'Object'+};++function extractParamName (callee, argIndex) {+ return (/\(\s*([^)]*?)\s*\)/).exec(callee)[1].split(/\s*,\s*/)[argIndex];+}++/**+ * Checks the given arguments' types and throws if they are not as expected.+ *+ * `spec` is a string where each character stands for the required type of the+ * argument at the same position. In other words: the character at `spec[i]`+ * specifies the required type for `args[i]`. The characters in `spec` are the+ * first letter of the required type's name. The supported types are:+ *+ * Array, Date, Number, String, Function, Object+ *+ * Lowercase characters specify arguments that must not be `null` or `undefined`+ * while uppercase characters allow those values to be passed.+ *+ * Finally, `*` can be used to allow any type at the corresponding position.+ *+ * @example+ * function foo (arr, opts) {+ * // require `arr` to be an Array and `opts` an Object, null or undefined+ * checkArgs('aO', 'my.package.foo', arguments);+ * // ...+ * }+ * @param {String} spec - the type specification for `args` as described above+ * @param {String} functionName - full name of the callee.+ * Used in the error message+ * @param {Array|arguments} args - the arguments to be checked against `spec`+ * @param {Function} [opt_callee=args.callee] - the recipient of `args`.+ * Used to extract parameter names for the error message+ * @throws {TypeError} if args do not satisfy spec+ */+function checkArgs (spec, functionName, args, opt_callee) {+ if (!moduleExports.enableChecks) {+ return;+ }+ var errMsg = null;+ var typeName;+ for (var i = 0; i < spec.length; ++i) {+ var c = spec.charAt(i);+ var cUpper = c.toUpperCase();+ var arg = args[i];+ // Asterix means allow anything.+ if (c === '*') {+ continue;+ }+ typeName = utils.typeName(arg);+ if ((arg === null || arg === undefined) && c === cUpper) {+ continue;+ }+ if (typeName !== typeMap[cUpper]) {+ errMsg = 'Expected ' + typeMap[cUpper];+ break;+ }+ }+ if (errMsg) {+ errMsg += ', but got ' + typeName + '.';+ errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;+ // Don't log when running unit tests.+ if (typeof jasmine === 'undefined') {+ console.error(errMsg);+ }+ throw TypeError(errMsg);+ }+}++function getValue (value, defaultValue) {+ return value === undefined ? defaultValue : value;+}++moduleExports.checkArgs = checkArgs;+moduleExports.getValue = getValue;+moduleExports.enableChecks = true;++});++// file: src/common/base64.js+define("cordova/base64", function(require, exports, module) {++var base64 = exports;++base64.fromArrayBuffer = function (arrayBuffer) {+ var array = new Uint8Array(arrayBuffer);+ return uint8ToBase64(array);+};++base64.toArrayBuffer = function (str) {+ var decodedStr = atob(str);+ var arrayBuffer = new ArrayBuffer(decodedStr.length);+ var array = new Uint8Array(arrayBuffer);+ for (var i = 0, len = decodedStr.length; i < len; i++) {+ array[i] = decodedStr.charCodeAt(i);+ }+ return arrayBuffer;+};++// ------------------------------------------------------------------------------++/* This code is based on the performance tests at http://jsperf.com/b64tests+ * This 12-bit-at-a-time algorithm was the best performing version on all+ * platforms tested.+ */++var b64_6bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';+var b64_12bit;++var b64_12bitTable = function () {+ b64_12bit = [];+ for (var i = 0; i < 64; i++) {+ for (var j = 0; j < 64; j++) {+ b64_12bit[i * 64 + j] = b64_6bit[i] + b64_6bit[j];+ }+ }+ b64_12bitTable = function () { return b64_12bit; };+ return b64_12bit;+};++function uint8ToBase64 (rawData) {+ var numBytes = rawData.byteLength;+ var output = '';+ var segment;+ var table = b64_12bitTable();+ for (var i = 0; i < numBytes - 2; i += 3) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8) + rawData[i + 2];+ output += table[segment >> 12];+ output += table[segment & 0xfff];+ }+ if (numBytes - i === 2) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8);+ output += table[segment >> 12];+ output += b64_6bit[(segment & 0xfff) >> 6];+ output += '=';+ } else if (numBytes - i === 1) {+ segment = (rawData[i] << 16);+ output += table[segment >> 12];+ output += '==';+ }+ return output;+}++});++// file: src/common/builder.js+define("cordova/builder", function(require, exports, module) {++var utils = require('cordova/utils');++function each (objects, func, context) {+ for (var prop in objects) {+ if (objects.hasOwnProperty(prop)) {+ func.apply(context, [objects[prop], prop]);+ }+ }+}++function clobber (obj, key, value) {+ var needsProperty = false;+ try {+ obj[key] = value;+ } catch (e) {+ needsProperty = true;+ }+ // Getters can only be overridden by getters.+ if (needsProperty || obj[key] !== value) {+ utils.defineGetter(obj, key, function () {+ return value;+ });+ }+}++function assignOrWrapInDeprecateGetter (obj, key, value, message) {+ if (message) {+ utils.defineGetter(obj, key, function () {+ console.log(message);+ delete obj[key];+ clobber(obj, key, value);+ return value;+ });+ } else {+ clobber(obj, key, value);+ }+}++function include (parent, objects, clobber, merge) {+ each(objects, function (obj, key) {+ try {+ var result = obj.path ? require(obj.path) : {};++ if (clobber) {+ // Clobber if it doesn't exist.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else if (typeof obj.path !== 'undefined') {+ // If merging, merge properties onto parent, otherwise, clobber.+ if (merge) {+ recursiveMerge(parent[key], result);+ } else {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ }+ }+ result = parent[key];+ } else {+ // Overwrite if not currently defined.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else {+ // Set result to what already exists, so we can build children into it if they exist.+ result = parent[key];+ }+ }++ if (obj.children) {+ include(result, obj.children, clobber, merge);+ }+ } catch (e) {+ utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');+ }+ });+}++/**+ * Merge properties from one object onto another recursively. Properties from+ * the src object will overwrite existing target property.+ *+ * @param target Object to merge properties into.+ * @param src Object to merge properties from.+ */+function recursiveMerge (target, src) {+ for (var prop in src) {+ if (src.hasOwnProperty(prop)) {+ if (target.prototype && target.prototype.constructor === target) {+ // If the target object is a constructor override off prototype.+ clobber(target.prototype, prop, src[prop]);+ } else {+ if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {+ recursiveMerge(target[prop], src[prop]);+ } else {+ clobber(target, prop, src[prop]);+ }+ }+ }+ }+}++exports.buildIntoButDoNotClobber = function (objects, target) {+ include(target, objects, false, false);+};+exports.buildIntoAndClobber = function (objects, target) {+ include(target, objects, true, false);+};+exports.buildIntoAndMerge = function (objects, target) {+ include(target, objects, true, true);+};+exports.recursiveMerge = recursiveMerge;+exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;++});++// file: src/common/channel.js+define("cordova/channel", function(require, exports, module) {++var utils = require('cordova/utils');+var nextGuid = 1;++/**+ * Custom pub-sub "channel" that can have functions subscribed to it+ * This object is used to define and control firing of events for+ * cordova initialization, as well as for custom events thereafter.+ *+ * The order of events during page load and Cordova startup is as follows:+ *+ * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.+ * onNativeReady* Internal event that indicates the Cordova native side is ready.+ * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.+ * onDeviceReady* User event fired to indicate that Cordova is ready+ * onResume User event fired to indicate a start/resume lifecycle event+ * onPause User event fired to indicate a pause lifecycle event+ *+ * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.+ * All listeners that subscribe after the event is fired will be executed right away.+ *+ * The only Cordova events that user code should register for are:+ * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript+ * pause App has moved to background+ * resume App has returned to foreground+ *+ * Listeners can be registered as:+ * document.addEventListener("deviceready", myDeviceReadyListener, false);+ * document.addEventListener("resume", myResumeListener, false);+ * document.addEventListener("pause", myPauseListener, false);+ *+ * The DOM lifecycle events should be used for saving and restoring state+ * window.onload+ * window.onunload+ *+ */++/**+ * Channel+ * @constructor+ * @param type String the channel name+ */+var Channel = function (type, sticky) {+ this.type = type;+ // Map of guid -> function.+ this.handlers = {};+ // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.+ this.state = sticky ? 1 : 0;+ // Used in sticky mode to remember args passed to fire().+ this.fireArgs = null;+ // Used by onHasSubscribersChange to know if there are any listeners.+ this.numHandlers = 0;+ // Function that is called when the first listener is subscribed, or when+ // the last listener is unsubscribed.+ this.onHasSubscribersChange = null;+};+var channel = {+ /**+ * Calls the provided function only after all of the channels specified+ * have been fired. All channels must be sticky channels.+ */+ join: function (h, c) {+ var len = c.length;+ var i = len;+ var f = function () {+ if (!(--i)) h();+ };+ for (var j = 0; j < len; j++) {+ if (c[j].state === 0) {+ throw Error('Can only use join with sticky channels.');+ }+ c[j].subscribe(f);+ }+ if (!len) h();+ },++ create: function (type) {+ return (channel[type] = new Channel(type, false));+ },+ createSticky: function (type) {+ return (channel[type] = new Channel(type, true));+ },++ /**+ * cordova Channels that must fire before "deviceready" is fired.+ */+ deviceReadyChannelsArray: [],+ deviceReadyChannelsMap: {},++ /**+ * Indicate that a feature needs to be initialized before it is ready to be used.+ * This holds up Cordova's "deviceready" event until the feature has been initialized+ * and Cordova.initComplete(feature) is called.+ *+ * @param feature {String} The unique feature name+ */+ waitForInitialization: function (feature) {+ if (feature) {+ var c = channel[feature] || this.createSticky(feature);+ this.deviceReadyChannelsMap[feature] = c;+ this.deviceReadyChannelsArray.push(c);+ }+ },++ /**+ * Indicate that initialization code has completed and the feature is ready to be used.+ *+ * @param feature {String} The unique feature name+ */+ initializationComplete: function (feature) {+ var c = this.deviceReadyChannelsMap[feature];+ if (c) {+ c.fire();+ }+ }+};++function checkSubscriptionArgument (argument) {+ if (typeof argument !== 'function' && typeof argument.handleEvent !== 'function') {+ throw new Error(+ 'Must provide a function or an EventListener object ' ++ 'implementing the handleEvent interface.'+ );+ }+}++/**+ * Subscribes the given function to the channel. Any time that+ * Channel.fire is called so too will the function.+ * Optionally specify an execution context for the function+ * and a guid that can be used to stop subscribing to the channel.+ * Returns the guid.+ */+Channel.prototype.subscribe = function (eventListenerOrFunction, eventListener) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ eventListener = eventListenerOrFunction;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ if (this.state === 2) {+ handleEvent.apply(eventListener || this, this.fireArgs);+ return;+ }++ guid = eventListenerOrFunction.observer_guid;+ if (typeof eventListener === 'object') {+ handleEvent = utils.close(eventListener, handleEvent);+ }++ if (!guid) {+ // First time any channel has seen this subscriber+ guid = '' + nextGuid++;+ }+ handleEvent.observer_guid = guid;+ eventListenerOrFunction.observer_guid = guid;++ // Don't add the same handler more than once.+ if (!this.handlers[guid]) {+ this.handlers[guid] = handleEvent;+ this.numHandlers++;+ if (this.numHandlers === 1) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Unsubscribes the function with the given guid from the channel.+ */+Channel.prototype.unsubscribe = function (eventListenerOrFunction) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid, handler;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ guid = handleEvent.observer_guid;+ handler = this.handlers[guid];+ if (handler) {+ delete this.handlers[guid];+ this.numHandlers--;+ if (this.numHandlers === 0) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Calls all functions subscribed to this channel.+ */+Channel.prototype.fire = function (e) {+ var fireArgs = Array.prototype.slice.call(arguments);+ // Apply stickiness.+ if (this.state === 1) {+ this.state = 2;+ this.fireArgs = fireArgs;+ }+ if (this.numHandlers) {+ // Copy the values first so that it is safe to modify it from within+ // callbacks.+ var toCall = [];+ for (var item in this.handlers) {+ toCall.push(this.handlers[item]);+ }+ for (var i = 0; i < toCall.length; ++i) {+ toCall[i].apply(this, fireArgs);+ }+ if (this.state === 2 && this.numHandlers) {+ this.numHandlers = 0;+ this.handlers = {};+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++// defining them here so they are ready super fast!+// DOM event that is received when the web page is loaded and parsed.+channel.createSticky('onDOMContentLoaded');++// Event to indicate the Cordova native side is ready.+channel.createSticky('onNativeReady');++// Event to indicate that all Cordova JavaScript objects have been created+// and it's time to run plugin constructors.+channel.createSticky('onCordovaReady');++// Event to indicate that all automatically loaded JS plugins are loaded and ready.+// FIXME remove this+channel.createSticky('onPluginsReady');++// Event to indicate that Cordova is ready+channel.createSticky('onDeviceReady');++// Event to indicate a resume lifecycle event+channel.create('onResume');++// Event to indicate a pause lifecycle event+channel.create('onPause');++// Channels that must fire before "deviceready" is fired.+channel.waitForInitialization('onCordovaReady');+channel.waitForInitialization('onDOMContentLoaded');++module.exports = channel;++});++// file: ../cordova-ios/cordova-js-src/exec.js+define("cordova/exec", function(require, exports, module) {++/* global require, module, atob, document */++/**+ * Creates a gap bridge iframe used to notify the native code about queued+ * commands.+ */+var cordova = require('cordova');+var utils = require('cordova/utils');+var base64 = require('cordova/base64');+var execIframe;+var commandQueue = []; // Contains pending JS->Native messages.+var isInContextOfEvalJs = 0;+var failSafeTimerId = 0;++function massageArgsJsToNative (args) {+ if (!args || utils.typeName(args) !== 'Array') {+ return args;+ }+ var ret = [];+ args.forEach(function (arg, i) {+ if (utils.typeName(arg) === 'ArrayBuffer') {+ ret.push({+ 'CDVType': 'ArrayBuffer',+ 'data': base64.fromArrayBuffer(arg)+ });+ } else {+ ret.push(arg);+ }+ });+ return ret;+}++function massageMessageNativeToJs (message) {+ if (message.CDVType === 'ArrayBuffer') {+ var stringToArrayBuffer = function (str) {+ var ret = new Uint8Array(str.length);+ for (var i = 0; i < str.length; i++) {+ ret[i] = str.charCodeAt(i);+ }+ return ret.buffer;+ };+ var base64ToArrayBuffer = function (b64) {+ return stringToArrayBuffer(atob(b64));+ };+ message = base64ToArrayBuffer(message.data);+ }+ return message;+}++function convertMessageToArgsNativeToJs (message) {+ var args = [];+ if (!message || !message.hasOwnProperty('CDVType')) {+ args.push(message);+ } else if (message.CDVType === 'MultiPart') {+ message.messages.forEach(function (e) {+ args.push(massageMessageNativeToJs(e));+ });+ } else {+ args.push(massageMessageNativeToJs(message));+ }+ return args;+}++function iOSExec () {++ var successCallback, failCallback, service, action, actionArgs;+ var callbackId = null;+ if (typeof arguments[0] !== 'string') {+ // FORMAT ONE+ successCallback = arguments[0];+ failCallback = arguments[1];+ service = arguments[2];+ action = arguments[3];+ actionArgs = arguments[4];++ // Since we need to maintain backwards compatibility, we have to pass+ // an invalid callbackId even if no callback was provided since plugins+ // will be expecting it. The Cordova.exec() implementation allocates+ // an invalid callbackId and passes it even if no callbacks were given.+ callbackId = 'INVALID';+ } else {+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' ++ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'+ );+ }++ // If actionArgs is not provided, default to an empty array+ actionArgs = actionArgs || [];++ // Register the callbacks and add the callbackId to the positional+ // arguments if given.+ if (successCallback || failCallback) {+ callbackId = service + cordova.callbackId++;+ cordova.callbacks[callbackId] =+ { success: successCallback, fail: failCallback };+ }++ actionArgs = massageArgsJsToNative(actionArgs);++ var command = [callbackId, service, action, actionArgs];++ // Stringify and queue the command. We stringify to command now to+ // effectively clone the command arguments in case they are mutated before+ // the command is executed.+ commandQueue.push(JSON.stringify(command));++ // If we're in the context of a stringByEvaluatingJavaScriptFromString call,+ // then the queue will be flushed when it returns; no need for a poke.+ // Also, if there is already a command in the queue, then we've already+ // poked the native side, so there is no reason to do so again.+ if (!isInContextOfEvalJs && commandQueue.length === 1) {+ pokeNative();+ }+}++// CB-10530+function proxyChanged () {+ var cexec = cordovaExec();++ return (execProxy !== cexec && // proxy objects are different+ iOSExec !== cexec // proxy object is not the current iOSExec+ );+}++// CB-10106+function handleBridgeChange () {+ if (proxyChanged()) {+ var commandString = commandQueue.shift();+ while (commandString) {+ var command = JSON.parse(commandString);+ var callbackId = command[0];+ var service = command[1];+ var action = command[2];+ var actionArgs = command[3];+ var callbacks = cordova.callbacks[callbackId] || {};++ execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);++ commandString = commandQueue.shift();+ }+ return true;+ }++ return false;+}++function pokeNative () {+ // CB-5488 - Don't attempt to create iframe before document.body is available.+ if (!document.body) {+ setTimeout(pokeNative);+ return;+ }++ // Check if they've removed it from the DOM, and put it back if so.+ if (execIframe && execIframe.contentWindow) {+ execIframe.contentWindow.location = 'gap://ready';+ } else {+ execIframe = document.createElement('iframe');+ execIframe.style.display = 'none';+ execIframe.src = 'gap://ready';+ document.body.appendChild(execIframe);+ }+ // Use a timer to protect against iframe being unloaded during the poke (CB-7735).+ // This makes the bridge ~ 7% slower, but works around the poke getting lost+ // when the iframe is removed from the DOM.+ // An onunload listener could be used in the case where the iframe has just been+ // created, but since unload events fire only once, it doesn't work in the normal+ // case of iframe reuse (where unload will have already fired due to the attempted+ // navigation of the page).+ failSafeTimerId = setTimeout(function () {+ if (commandQueue.length) {+ // CB-10106 - flush the queue on bridge change+ if (!handleBridgeChange()) {+ pokeNative();+ }+ }+ }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).+}++iOSExec.nativeFetchMessages = function () {+ // Stop listing for window detatch once native side confirms poke.+ if (failSafeTimerId) {+ clearTimeout(failSafeTimerId);+ failSafeTimerId = 0;+ }+ // Each entry in commandQueue is a JSON string already.+ if (!commandQueue.length) {+ return '';+ }+ var json = '[' + commandQueue.join(',') + ']';+ commandQueue.length = 0;+ return json;+};++iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {+ return iOSExec.nativeEvalAndFetch(function () {+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ function nc2 () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback);+ }+ setTimeout(nc2, 0);+ });+};++iOSExec.nativeEvalAndFetch = function (func) {+ // This shouldn't be nested, but better to be safe.+ isInContextOfEvalJs++;+ try {+ func();+ return iOSExec.nativeFetchMessages();+ } finally {+ isInContextOfEvalJs--;+ }+};++// Proxy the exec for bridge changes. See CB-10106++function cordovaExec () {+ var cexec = require('cordova/exec');+ var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function');+ return (cexec_valid && execProxy !== cexec) ? cexec : iOSExec;+}++function execProxy () {+ cordovaExec().apply(null, arguments);+}++execProxy.nativeFetchMessages = function () {+ return cordovaExec().nativeFetchMessages.apply(null, arguments);+};++execProxy.nativeEvalAndFetch = function () {+ return cordovaExec().nativeEvalAndFetch.apply(null, arguments);+};++execProxy.nativeCallback = function () {+ return cordovaExec().nativeCallback.apply(null, arguments);+};++module.exports = execProxy;++});++// file: src/common/exec/proxy.js+define("cordova/exec/proxy", function(require, exports, module) {++// internal map of proxy function+var CommandProxyMap = {};++module.exports = {++ // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);+ add: function (id, proxyObj) {+ console.log('adding proxy for ' + id);+ CommandProxyMap[id] = proxyObj;+ return proxyObj;+ },++ // cordova.commandProxy.remove("Accelerometer");+ remove: function (id) {+ var proxy = CommandProxyMap[id];+ delete CommandProxyMap[id];+ CommandProxyMap[id] = null;+ return proxy;+ },++ get: function (service, action) {+ return (CommandProxyMap[service] ? CommandProxyMap[service][action] : null);+ }+};++});++// file: src/common/init.js+define("cordova/init", function(require, exports, module) {++var channel = require('cordova/channel');+var cordova = require('cordova');+var modulemapper = require('cordova/modulemapper');+var platform = require('cordova/platform');+var pluginloader = require('cordova/pluginloader');+var utils = require('cordova/utils');++var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];++function logUnfiredChannels (arr) {+ for (var i = 0; i < arr.length; ++i) {+ if (arr[i].state !== 2) {+ console.log('Channel not fired: ' + arr[i].type);+ }+ }+}++window.setTimeout(function () {+ if (channel.onDeviceReady.state !== 2) {+ console.log('deviceready has not fired after 5 seconds.');+ logUnfiredChannels(platformInitChannelsArray);+ logUnfiredChannels(channel.deviceReadyChannelsArray);+ }+}, 5000);++// Replace navigator before any modules are required(), to ensure it happens as soon as possible.+// We replace it so that properties that can't be clobbered can instead be overridden.+function replaceNavigator (origNavigator) {+ var CordovaNavigator = function () {};+ CordovaNavigator.prototype = origNavigator;+ var newNavigator = new CordovaNavigator();+ // This work-around really only applies to new APIs that are newer than Function.bind.+ // Without it, APIs such as getGamepads() break.+ if (CordovaNavigator.bind) {+ for (var key in origNavigator) {+ if (typeof origNavigator[key] === 'function') {+ newNavigator[key] = origNavigator[key].bind(origNavigator);+ } else {+ (function (k) {+ utils.defineGetterSetter(newNavigator, key, function () {+ return origNavigator[k];+ });+ })(key);+ }+ }+ }+ return newNavigator;+}++if (window.navigator) {+ window.navigator = replaceNavigator(window.navigator);+}++if (!window.console) {+ window.console = {+ log: function () {}+ };+}+if (!window.console.warn) {+ window.console.warn = function (msg) {+ this.log('warn: ' + msg);+ };+}++// Register pause, resume and deviceready channels as events on document.+channel.onPause = cordova.addDocumentEventHandler('pause');+channel.onResume = cordova.addDocumentEventHandler('resume');+channel.onActivated = cordova.addDocumentEventHandler('activated');+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');++// Listen for DOMContentLoaded and notify our channel subscribers.+if (document.readyState === 'complete' || document.readyState === 'interactive') {+ channel.onDOMContentLoaded.fire();+} else {+ document.addEventListener('DOMContentLoaded', function () {+ channel.onDOMContentLoaded.fire();+ }, false);+}++// _nativeReady is global variable that the native side can set+// to signify that the native code is ready. It is a global since+// it may be called before any cordova JS is ready.+if (window._nativeReady) {+ channel.onNativeReady.fire();+}++modulemapper.clobbers('cordova', 'cordova');+modulemapper.clobbers('cordova/exec', 'cordova.exec');+modulemapper.clobbers('cordova/exec', 'Cordova.exec');++// Call the platform-specific initialization.+platform.bootstrap && platform.bootstrap();++// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.+// The delay allows the attached modules to be defined before the plugin loader looks for them.+setTimeout(function () {+ pluginloader.load(function () {+ channel.onPluginsReady.fire();+ });+}, 0);++/**+ * Create all cordova objects once native side is ready.+ */+channel.join(function () {+ modulemapper.mapModules(window);++ platform.initialize && platform.initialize();++ // Fire event to notify that all objects are created+ channel.onCordovaReady.fire();++ // Fire onDeviceReady event once page has fully loaded, all+ // constructors have run and cordova info has been received from native+ // side.+ channel.join(function () {+ require('cordova').fireDocumentEvent('deviceready');+ }, channel.deviceReadyChannelsArray);++}, platformInitChannelsArray);++});++// file: src/common/modulemapper.js+define("cordova/modulemapper", function(require, exports, module) {++var builder = require('cordova/builder');+var moduleMap = define.moduleMap;+var symbolList;+var deprecationMap;++exports.reset = function () {+ symbolList = [];+ deprecationMap = {};+};++function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {+ if (!(moduleName in moduleMap)) {+ throw new Error('Module ' + moduleName + ' does not exist.');+ }+ symbolList.push(strategy, moduleName, symbolPath);+ if (opt_deprecationMessage) {+ deprecationMap[symbolPath] = opt_deprecationMessage;+ }+}++// Note: Android 2.3 does have Function.bind().+exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('c', moduleName, symbolPath, opt_deprecationMessage);+};++exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('m', moduleName, symbolPath, opt_deprecationMessage);+};++exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('d', moduleName, symbolPath, opt_deprecationMessage);+};++exports.runs = function (moduleName) {+ addEntry('r', moduleName, null);+};++function prepareNamespace (symbolPath, context) {+ if (!symbolPath) {+ return context;+ }+ return symbolPath.split('.').reduce(function (cur, part) {+ return (cur[part] = cur[part] || {});+ }, context);+}++exports.mapModules = function (context) {+ var origSymbols = {};+ context.CDV_origSymbols = origSymbols;+ for (var i = 0, len = symbolList.length; i < len; i += 3) {+ var strategy = symbolList[i];+ var moduleName = symbolList[i + 1];+ var module = require(moduleName);+ // <runs/>+ if (strategy === 'r') {+ continue;+ }+ var symbolPath = symbolList[i + 2];+ var lastDot = symbolPath.lastIndexOf('.');+ var namespace = symbolPath.substr(0, lastDot);+ var lastName = symbolPath.substr(lastDot + 1);++ var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;+ var parentObj = prepareNamespace(namespace, context);+ var target = parentObj[lastName];++ if (strategy === 'm' && target) {+ builder.recursiveMerge(target, module);+ } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {+ if (!(symbolPath in origSymbols)) {+ origSymbols[symbolPath] = target;+ }+ builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);+ }+ }+};++exports.getOriginalSymbol = function (context, symbolPath) {+ var origSymbols = context.CDV_origSymbols;+ if (origSymbols && (symbolPath in origSymbols)) {+ return origSymbols[symbolPath];+ }+ var parts = symbolPath.split('.');+ var obj = context;+ for (var i = 0; i < parts.length; ++i) {+ obj = obj && obj[parts[i]];+ }+ return obj;+};++exports.reset();++});++// file: ../cordova-ios/cordova-js-src/platform.js+define("cordova/platform", function(require, exports, module) {++module.exports = {+ id: 'ios',+ bootstrap: function () {+ // Attach the console polyfill that is iOS-only to window.console+ // see the file under plugin/ios/console.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');++ require('cordova/channel').onNativeReady.fire();+ }+};++});++// file: ../cordova-ios/cordova-js-src/plugin/ios/console.js+define("cordova/plugin/ios/console", function(require, exports, module) {++// ------------------------------------------------------------------------------++var logger = require('cordova/plugin/ios/logger');++// ------------------------------------------------------------------------------+// object that we're exporting+// ------------------------------------------------------------------------------+var console = module.exports;++// ------------------------------------------------------------------------------+// copy of the original console object+// ------------------------------------------------------------------------------+var WinConsole = window.console;++// ------------------------------------------------------------------------------+// whether to use the logger+// ------------------------------------------------------------------------------+var UseLogger = false;++// ------------------------------------------------------------------------------+// Timers+// ------------------------------------------------------------------------------+var Timers = {};++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+function noop () {}++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+console.useLogger = function (value) {+ if (arguments.length) UseLogger = !!value;++ if (UseLogger) {+ if (logger.useConsole()) {+ throw new Error('console and logger are too intertwingly');+ }+ }++ return UseLogger;+};++// ------------------------------------------------------------------------------+console.log = function () {+ if (logger.useConsole()) return;+ logger.log.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.error = function () {+ if (logger.useConsole()) return;+ logger.error.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.warn = function () {+ if (logger.useConsole()) return;+ logger.warn.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.info = function () {+ if (logger.useConsole()) return;+ logger.info.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.debug = function () {+ if (logger.useConsole()) return;+ logger.debug.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.assert = function (expression) {+ if (expression) return;++ var message = logger.format.apply(logger.format, [].slice.call(arguments, 1));+ console.log('ASSERT: ' + message);+};++// ------------------------------------------------------------------------------+console.clear = function () {};++// ------------------------------------------------------------------------------+console.dir = function (object) {+ console.log('%o', object);+};++// ------------------------------------------------------------------------------+console.dirxml = function (node) {+ console.log(node.innerHTML);+};++// ------------------------------------------------------------------------------+console.trace = noop;++// ------------------------------------------------------------------------------+console.group = console.log;++// ------------------------------------------------------------------------------+console.groupCollapsed = console.log;++// ------------------------------------------------------------------------------+console.groupEnd = noop;++// ------------------------------------------------------------------------------+console.time = function (name) {+ Timers[name] = new Date().valueOf();+};++// ------------------------------------------------------------------------------+console.timeEnd = function (name) {+ var timeStart = Timers[name];+ if (!timeStart) {+ console.warn('unknown timer: ' + name);+ return;+ }++ var timeElapsed = new Date().valueOf() - timeStart;+ console.log(name + ': ' + timeElapsed + 'ms');+};++// ------------------------------------------------------------------------------+console.timeStamp = noop;++// ------------------------------------------------------------------------------+console.profile = noop;++// ------------------------------------------------------------------------------+console.profileEnd = noop;++// ------------------------------------------------------------------------------+console.count = noop;++// ------------------------------------------------------------------------------+console.exception = console.log;++// ------------------------------------------------------------------------------+console.table = function (data, columns) {+ console.log('%o', data);+};++// ------------------------------------------------------------------------------+// return a new function that calls both functions passed as args+// ------------------------------------------------------------------------------+function wrappedOrigCall (orgFunc, newFunc) {+ return function () {+ var args = [].slice.call(arguments);+ try { orgFunc.apply(WinConsole, args); } catch (e) {}+ try { newFunc.apply(console, args); } catch (e) {}+ };+}++// ------------------------------------------------------------------------------+// For every function that exists in the original console object, that+// also exists in the new console object, wrap the new console method+// with one that calls both+// ------------------------------------------------------------------------------+for (var key in console) {+ if (typeof WinConsole[key] === 'function') {+ console[key] = wrappedOrigCall(WinConsole[key], console[key]);+ }+}++});++// file: ../cordova-ios/cordova-js-src/plugin/ios/logger.js+define("cordova/plugin/ios/logger", function(require, exports, module) {++// ------------------------------------------------------------------------------+// The logger module exports the following properties/functions:+//+// LOG - constant for the level LOG+// ERROR - constant for the level ERROR+// WARN - constant for the level WARN+// INFO - constant for the level INFO+// DEBUG - constant for the level DEBUG+// logLevel() - returns current log level+// logLevel(value) - sets and returns a new log level+// useConsole() - returns whether logger is using console+// useConsole(value) - sets and returns whether logger is using console+// log(message,...) - logs a message at level LOG+// error(message,...) - logs a message at level ERROR+// warn(message,...) - logs a message at level WARN+// info(message,...) - logs a message at level INFO+// debug(message,...) - logs a message at level DEBUG+// logLevel(level,message,...) - logs a message specified level+//+// ------------------------------------------------------------------------------++var logger = exports;++var exec = require('cordova/exec');++var UseConsole = false;+var UseLogger = true;+var Queued = [];+var DeviceReady = false;+var CurrentLevel;++var originalConsole = console;++/**+ * Logging levels+ */++var Levels = [+ 'LOG',+ 'ERROR',+ 'WARN',+ 'INFO',+ 'DEBUG'+];++/*+ * add the logging levels to the logger object and+ * to a separate levelsMap object for testing+ */++var LevelsMap = {};+for (var i = 0; i < Levels.length; i++) {+ var level = Levels[i];+ LevelsMap[level] = i;+ logger[level] = level;+}++CurrentLevel = LevelsMap.WARN;++/**+ * Getter/Setter for the logging level+ *+ * Returns the current logging level.+ *+ * When a value is passed, sets the logging level to that value.+ * The values should be one of the following constants:+ * logger.LOG+ * logger.ERROR+ * logger.WARN+ * logger.INFO+ * logger.DEBUG+ *+ * The value used determines which messages get printed. The logging+ * values above are in order, and only messages logged at the logging+ * level or above will actually be displayed to the user. E.g., the+ * default level is WARN, so only messages logged with LOG, ERROR, or+ * WARN will be displayed; INFO and DEBUG messages will be ignored.+ */+logger.level = function (value) {+ if (arguments.length) {+ if (LevelsMap[value] === null) {+ throw new Error('invalid logging level: ' + value);+ }+ CurrentLevel = LevelsMap[value];+ }++ return Levels[CurrentLevel];+};++/**+ * Getter/Setter for the useConsole functionality+ *+ * When useConsole is true, the logger will log via the+ * browser 'console' object.+ */+logger.useConsole = function (value) {+ if (arguments.length) UseConsole = !!value;++ if (UseConsole) {+ if (typeof console === 'undefined') {+ throw new Error('global console object is not defined');+ }++ if (typeof console.log !== 'function') {+ throw new Error('global console object does not have a log function');+ }++ if (typeof console.useLogger === 'function') {+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }+ }+ }++ return UseConsole;+};++/**+ * Getter/Setter for the useLogger functionality+ *+ * When useLogger is true, the logger will log via the+ * native Logger plugin.+ */+logger.useLogger = function (value) {+ // Enforce boolean+ if (arguments.length) UseLogger = !!value;+ return UseLogger;+};++/**+ * Logs a message at the LOG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.log = function (message) { logWithArgs('LOG', arguments); };++/**+ * Logs a message at the ERROR level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.error = function (message) { logWithArgs('ERROR', arguments); };++/**+ * Logs a message at the WARN level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.warn = function (message) { logWithArgs('WARN', arguments); };++/**+ * Logs a message at the INFO level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.info = function (message) { logWithArgs('INFO', arguments); };++/**+ * Logs a message at the DEBUG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.debug = function (message) { logWithArgs('DEBUG', arguments); };++// log at the specified level with args+function logWithArgs (level, args) {+ args = [level].concat([].slice.call(args));+ logger.logLevel.apply(logger, args);+}++// return the correct formatString for an object+function formatStringForMessage (message) {+ return (typeof message === 'string') ? '' : '%o';+}++/**+ * Logs a message at the specified level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.logLevel = function (level /* , ... */) {+ // format the message with the parameters+ var formatArgs = [].slice.call(arguments, 1);+ var fmtString = formatStringForMessage(formatArgs[0]);+ if (fmtString.length > 0) {+ formatArgs.unshift(fmtString); // add formatString+ }++ var message = logger.format.apply(logger.format, formatArgs);++ if (LevelsMap[level] === null) {+ throw new Error('invalid logging level: ' + level);+ }++ if (LevelsMap[level] > CurrentLevel) return;++ // queue the message if not yet at deviceready+ if (!DeviceReady && !UseConsole) {+ Queued.push([level, message]);+ return;+ }++ // Log using the native logger if that is enabled+ if (UseLogger) {+ exec(null, null, 'Console', 'logLevel', [level, message]);+ }++ // Log using the console if that is enabled+ if (UseConsole) {+ // make sure console is not using logger+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }++ // log to the console+ switch (level) {+ case logger.LOG: originalConsole.log(message); break;+ case logger.ERROR: originalConsole.log('ERROR: ' + message); break;+ case logger.WARN: originalConsole.log('WARN: ' + message); break;+ case logger.INFO: originalConsole.log('INFO: ' + message); break;+ case logger.DEBUG: originalConsole.log('DEBUG: ' + message); break;+ }+ }+};++/**+ * Formats a string and arguments following it ala console.log()+ *+ * Any remaining arguments will be appended to the formatted string.+ *+ * for rationale, see FireBug's Console API:+ * http://getfirebug.com/wiki/index.php/Console_API+ */+logger.format = function (formatString, args) {+ return __format(arguments[0], [].slice.call(arguments, 1)).join(' ');+};++// ------------------------------------------------------------------------------+/**+ * Formats a string and arguments following it ala vsprintf()+ *+ * format chars:+ * %j - format arg as JSON+ * %o - format arg as JSON+ * %c - format arg as ''+ * %% - replace with '%'+ * any other char following % will format it's+ * arg via toString().+ *+ * Returns an array containing the formatted string and any remaining+ * arguments.+ */+function __format (formatString, args) {+ if (formatString === null || formatString === undefined) return [''];+ if (arguments.length === 1) return [formatString.toString()];++ if (typeof formatString !== 'string') { formatString = formatString.toString(); }++ var pattern = /(.*?)%(.)(.*)/;+ var rest = formatString;+ var result = [];++ while (args.length) {+ var match = pattern.exec(rest);+ if (!match) break;++ var arg = args.shift();+ rest = match[3];+ result.push(match[1]);++ if (match[2] === '%') {+ result.push('%');+ args.unshift(arg);+ continue;+ }++ result.push(__formatted(arg, match[2]));+ }++ result.push(rest);++ var remainingArgs = [].slice.call(args);+ remainingArgs.unshift(result.join(''));+ return remainingArgs;+}++function __formatted (object, formatChar) {++ try {+ switch (formatChar) {+ case 'j':+ case 'o': return JSON.stringify(object);+ case 'c': return '';+ }+ } catch (e) {+ return 'error JSON.stringify()ing argument: ' + e;+ }++ if ((object === null) || (object === undefined)) {+ return Object.prototype.toString.call(object);+ }++ return object.toString();+}++// ------------------------------------------------------------------------------+// when deviceready fires, log queued messages+logger.__onDeviceReady = function () {+ if (DeviceReady) return;++ DeviceReady = true;++ for (var i = 0; i < Queued.length; i++) {+ var messageArgs = Queued[i];+ logger.logLevel(messageArgs[0], messageArgs[1]);+ }++ Queued = null;+};++// add a deviceready event to log queued messages+document.addEventListener('deviceready', logger.__onDeviceReady, false);++});++// file: src/common/pluginloader.js+define("cordova/pluginloader", function(require, exports, module) {++var modulemapper = require('cordova/modulemapper');++// Helper function to inject a <script> tag.+// Exported for testing.+exports.injectScript = function (url, onload, onerror) {+ var script = document.createElement('script');+ // onload fires even when script fails loads with an error.+ script.onload = onload;+ // onerror fires for malformed URLs.+ script.onerror = onerror;+ script.src = url;+ document.head.appendChild(script);+};++function injectIfNecessary (id, url, onload, onerror) {+ onerror = onerror || onload;+ if (id in define.moduleMap) {+ onload();+ } else {+ exports.injectScript(url, function () {+ if (id in define.moduleMap) {+ onload();+ } else {+ onerror();+ }+ }, onerror);+ }+}++function onScriptLoadingComplete (moduleList, finishPluginLoading) {+ // Loop through all the plugins and then through their clobbers and merges.+ for (var i = 0, module; (module = moduleList[i]); i++) {+ if (module.clobbers && module.clobbers.length) {+ for (var j = 0; j < module.clobbers.length; j++) {+ modulemapper.clobbers(module.id, module.clobbers[j]);+ }+ }++ if (module.merges && module.merges.length) {+ for (var k = 0; k < module.merges.length; k++) {+ modulemapper.merges(module.id, module.merges[k]);+ }+ }++ // Finally, if runs is truthy we want to simply require() the module.+ if (module.runs) {+ modulemapper.runs(module.id);+ }+ }++ finishPluginLoading();+}++// Handler for the cordova_plugins.js content.+// See plugman's plugin_loader.js for the details of this object.+// This function is only called if the really is a plugins array that isn't empty.+// Otherwise the onerror response handler will just call finishPluginLoading().+function handlePluginsObject (path, moduleList, finishPluginLoading) {+ // Now inject the scripts.+ var scriptCounter = moduleList.length;++ if (!scriptCounter) {+ finishPluginLoading();+ return;+ }+ function scriptLoadedCallback () {+ if (!--scriptCounter) {+ onScriptLoadingComplete(moduleList, finishPluginLoading);+ }+ }++ for (var i = 0; i < moduleList.length; i++) {+ injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback);+ }+}++function findCordovaPath () {+ var path = null;+ var scripts = document.getElementsByTagName('script');+ var term = '/cordova.js';+ for (var n = scripts.length - 1; n > -1; n--) {+ var src = scripts[n].src.replace(/\?.*$/, ''); // Strip any query param (CB-6007).+ if (src.indexOf(term) === (src.length - term.length)) {+ path = src.substring(0, src.length - term.length) + '/';+ break;+ }+ }+ return path;+}++// Tries to load all plugins' js-modules.+// This is an async process, but onDeviceReady is blocked on onPluginsReady.+// onPluginsReady is fired when there are no plugins to load, or they are all done.+exports.load = function (callback) {+ var pathPrefix = findCordovaPath();+ if (pathPrefix === null) {+ console.log('Could not find cordova.js script tag. Plugin loading may fail.');+ pathPrefix = '';+ }+ injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function () {+ var moduleList = require('cordova/plugin_list');+ handlePluginsObject(pathPrefix, moduleList, callback);+ }, callback);+};++});++// file: src/common/urlutil.js+define("cordova/urlutil", function(require, exports, module) {++/**+ * For already absolute URLs, returns what is passed in.+ * For relative URLs, converts them to absolute ones.+ */+exports.makeAbsolute = function makeAbsolute (url) {+ var anchorEl = document.createElement('a');+ anchorEl.href = url;+ return anchorEl.href;+};++});++// file: src/common/utils.js+define("cordova/utils", function(require, exports, module) {++var utils = exports;++/**+ * Defines a property getter / setter for obj[key].+ */+utils.defineGetterSetter = function (obj, key, getFunc, opt_setFunc) {+ if (Object.defineProperty) {+ var desc = {+ get: getFunc,+ configurable: true+ };+ if (opt_setFunc) {+ desc.set = opt_setFunc;+ }+ Object.defineProperty(obj, key, desc);+ } else {+ obj.__defineGetter__(key, getFunc);+ if (opt_setFunc) {+ obj.__defineSetter__(key, opt_setFunc);+ }+ }+};++/**+ * Defines a property getter for obj[key].+ */+utils.defineGetter = utils.defineGetterSetter;++utils.arrayIndexOf = function (a, item) {+ if (a.indexOf) {+ return a.indexOf(item);+ }+ var len = a.length;+ for (var i = 0; i < len; ++i) {+ if (a[i] === item) {+ return i;+ }+ }+ return -1;+};++/**+ * Returns whether the item was found in the array.+ */+utils.arrayRemove = function (a, item) {+ var index = utils.arrayIndexOf(a, item);+ if (index !== -1) {+ a.splice(index, 1);+ }+ return index !== -1;+};++utils.typeName = function (val) {+ return Object.prototype.toString.call(val).slice(8, -1);+};++/**+ * Returns an indication of whether the argument is an array or not+ */+utils.isArray = Array.isArray ||+ function (a) { return utils.typeName(a) === 'Array'; };++/**+ * Returns an indication of whether the argument is a Date or not+ */+utils.isDate = function (d) {+ return (d instanceof Date);+};++/**+ * Does a deep clone of the object.+ */+utils.clone = function (obj) {+ if (!obj || typeof obj === 'function' || utils.isDate(obj) || typeof obj !== 'object') {+ return obj;+ }++ var retVal, i;++ if (utils.isArray(obj)) {+ retVal = [];+ for (i = 0; i < obj.length; ++i) {+ retVal.push(utils.clone(obj[i]));+ }+ return retVal;+ }++ retVal = {};+ for (i in obj) {+ // 'unknown' type may be returned in custom protocol activation case on+ // Windows Phone 8.1 causing "No such interface supported" exception on+ // cloning (https://issues.apache.org/jira/browse/CB-11522)+ // eslint-disable-next-line valid-typeof+ if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') {+ retVal[i] = utils.clone(obj[i]);+ }+ }+ return retVal;+};++/**+ * Returns a wrapped version of the function+ */+utils.close = function (context, func, params) {+ return function () {+ var args = params || arguments;+ return func.apply(context, args);+ };+};++// ------------------------------------------------------------------------------+function UUIDcreatePart (length) {+ var uuidpart = '';+ for (var i = 0; i < length; i++) {+ var uuidchar = parseInt((Math.random() * 256), 10).toString(16);+ if (uuidchar.length === 1) {+ uuidchar = '0' + uuidchar;+ }+ uuidpart += uuidchar;+ }+ return uuidpart;+}++/**+ * Create a UUID+ */+utils.createUUID = function () {+ return UUIDcreatePart(4) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(6);+};++/**+ * Extends a child object from a parent object using classical inheritance+ * pattern.+ */+utils.extend = (function () {+ // proxy used to establish prototype chain+ var F = function () {};+ // extend Child from Parent+ return function (Child, Parent) {++ F.prototype = Parent.prototype;+ Child.prototype = new F();+ Child.__super__ = Parent.prototype;+ Child.prototype.constructor = Child;+ };+}());++/**+ * Alerts a message in any available way: alert or console.log.+ */+utils.alert = function (msg) {+ if (window.alert) {+ window.alert(msg);+ } else if (console && console.log) {+ console.log(msg);+ }+};++});++window.cordova = require('cordova');+// file: src/scripts/bootstrap.js+require('cordova/init');++})();diff --git a/cordova/platforms/ios/platform_www/cordova_plugins.js b/cordova/platforms/ios/platform_www/cordova_plugins.jsnew file mode 100644index 000000000..e8ef01fbe--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova_plugins.js@@ -0,0 +1,242 @@+cordova.define('cordova/plugin_list', function(require, exports, module) {+ module.exports = [+ {+ "id": "cordova-plugin-device.device",+ "file": "plugins/cordova-plugin-device/www/device.js",+ "pluginId": "cordova-plugin-device",+ "clobbers": [+ "device"+ ]+ },+ {+ "id": "cordova-plugin-background-mode.BackgroundMode",+ "file": "plugins/cordova-plugin-background-mode/www/background-mode.js",+ "pluginId": "cordova-plugin-background-mode",+ "clobbers": [+ "cordova.plugins.backgroundMode",+ "plugin.backgroundMode"+ ]+ },+ {+ "id": "cordova-plugin-camera.Camera",+ "file": "plugins/cordova-plugin-camera/www/CameraConstants.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "Camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverOptions",+ "file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverOptions"+ ]+ },+ {+ "id": "cordova-plugin-camera.camera",+ "file": "plugins/cordova-plugin-camera/www/Camera.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "navigator.camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverHandle",+ "file": "plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverHandle"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryEntry",+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryReader",+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryReader"+ ]+ },+ {+ "id": "cordova-plugin-file.Entry",+ "file": "plugins/cordova-plugin-file/www/Entry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Entry"+ ]+ },+ {+ "id": "cordova-plugin-file.File",+ "file": "plugins/cordova-plugin-file/www/File.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.File"+ ]+ },+ {+ "id": "cordova-plugin-file.FileEntry",+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.FileError",+ "file": "plugins/cordova-plugin-file/www/FileError.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileError"+ ]+ },+ {+ "id": "cordova-plugin-file.FileReader",+ "file": "plugins/cordova-plugin-file/www/FileReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileReader"+ ]+ },+ {+ "id": "cordova-plugin-file.FileSystem",+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadOptions",+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadOptions"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadResult",+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadResult"+ ]+ },+ {+ "id": "cordova-plugin-file.FileWriter",+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileWriter"+ ]+ },+ {+ "id": "cordova-plugin-file.Flags",+ "file": "plugins/cordova-plugin-file/www/Flags.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Flags"+ ]+ },+ {+ "id": "cordova-plugin-file.LocalFileSystem",+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.LocalFileSystem"+ ],+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.Metadata",+ "file": "plugins/cordova-plugin-file/www/Metadata.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Metadata"+ ]+ },+ {+ "id": "cordova-plugin-file.ProgressEvent",+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.ProgressEvent"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems",+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",+ "pluginId": "cordova-plugin-file"+ },+ {+ "id": "cordova-plugin-file.requestFileSystem",+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.requestFileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.isChrome",+ "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.iosFileSystem",+ "file": "plugins/cordova-plugin-file/www/ios/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems-roots",+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.fileSystemPaths",+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "cordova"+ ],+ "runs": true+ },+ {+ "id": "cordova-plugin-file-opener2.FileOpener2",+ "file": "plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js",+ "pluginId": "cordova-plugin-file-opener2",+ "clobbers": [+ "cordova.plugins.fileOpener2"+ ]+ }+ ];+ module.exports.metadata = {+ "cordova-plugin-device": "2.0.3",+ "cordova-plugin-background-mode": "0.7.3",+ "cordova-plugin-camera": "4.1.0",+ "cordova-plugin-file": "6.0.2",+ "cordova-plugin-file-opener2": "3.0.4",+ "cordova-plugin-whitelist": "1.3.4"+ };+});\ No newline at end of filediff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-background-mode/www/background-mode.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-background-mode/www/background-mode.jsnew file mode 100644index 000000000..7895b27ad--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-background-mode/www/background-mode.js@@ -0,0 +1,513 @@+cordova.define("cordova-plugin-background-mode.BackgroundMode", function(require, exports, module) {+/*+ Copyright 2013-2017 appPlant GmbH++ 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 = require('cordova/exec'),+ channel = require('cordova/channel');++/**+ * Activates the background mode. When activated the application+ * will be prevented from going to sleep while in background+ * for the next time.+ *+ * @return [ Void ]+ */+exports.enable = function()+{+ if (this.isEnabled())+ return;++ var fn = function() {+ exports._isEnabled = true;+ exports.fireEvent('enable');+ };++ cordova.exec(fn, null, 'BackgroundMode', 'enable', []);+};++/**+ * Deactivates the background mode. When deactivated the application+ * will not stay awake while in background.+ *+ * @return [ Void ]+ */+exports.disable = function()+{+ if (!this.isEnabled())+ return;++ var fn = function() {+ exports._isEnabled = false;+ exports.fireEvent('disable');+ };++ cordova.exec(fn, null, 'BackgroundMode', 'disable', []);+};++/**+ * Enable or disable the background mode.+ *+ * @param [ Bool ] enable The status to set for.+ *+ * @return [ Void ]+ */+exports.setEnabled = function (enable)+{+ if (enable) {+ this.enable();+ } else {+ this.disable();+ }+};++/**+ * List of all available options with their default value.+ *+ * @return [ Object ]+ */+exports.getDefaults = function()+{+ return this._defaults;+};++/**+ * The actual applied settings.+ *+ * @return [ Object ]+ */+exports.getSettings = function()+{+ return this._settings || {};+};++/**+ * Overwrite the default settings.+ *+ * @param [ Object ] overrides Dict of options to be overridden.+ *+ * @return [ Void ]+ */+exports.setDefaults = function (overrides)+{+ var defaults = this.getDefaults();++ for (var key in defaults)+ {+ if (overrides.hasOwnProperty(key))+ {+ defaults[key] = overrides[key];+ }+ }++ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundMode', 'configure', [defaults, false]);+ }+};++/**+ * Configures the notification settings for Android.+ * Will be merged with the defaults.+ *+ * @param [ Object ] options Dict of options to be overridden.+ *+ * @return [ Void ]+ */+exports.configure = function (options)+{+ var settings = this.getSettings(),+ defaults = this.getDefaults();++ if (!this._isAndroid)+ return;++ if (!this._isActive)+ {+ console.log('BackgroundMode is not active, skipped...');+ return;+ }++ this._mergeObjects(options, settings);+ this._mergeObjects(options, defaults);+ this._settings = options;++ cordova.exec(null, null, 'BackgroundMode', 'configure', [options, true]);+};++/**+ * Enable GPS-tracking in background (Android).+ *+ * @return [ Void ]+ */+exports.disableWebViewOptimizations = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'webview', []);+ }+};++/**+ * Disables battery optimazation mode for the app.+ *+ * @return [ Void ]+ */+exports.disableBatteryOptimizations = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'battery', []);+ }+};++/**+ * Opens the system settings dialog where the user can tweak or turn off any+ * custom app start settings added by the manufacturer if available.+ *+ * @param [ Object|Bool ] options Set to false if you dont want to display an+ * alert dialog first.+ *+ * @return [ Void ]+ */+exports.openAppStartSettings = function (options)+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'appstart', [options]);+ }+};++/**+ * Move app to background (Android only).+ *+ * @return [ Void ]+ */+exports.moveToBackground = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'background', []);+ }+};++/**+ * Move app to foreground when in background (Android only).+ *+ * @return [ Void ]+ */+exports.moveToForeground = function()+{+ if (this.isActive() && this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'foreground', []);+ }+};++/**+ * Exclude the app from the recent tasks list (Android only).+ *+ * @return [ Void ]+ */+exports.excludeFromTaskList = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'tasklist', []);+ }+};++/**+ * Override the back button on Android to go to background+ * instead of closing the app.+ *+ * @return [ Void ]+ */+exports.overrideBackButton = function()+{+ document.addEventListener('backbutton', function() {+ exports.moveToBackground();+ }, false);+};++/**+ * If the screen is off.+ *+ * @param [ Function ] fn Callback function to invoke with boolean arg.+ *+ * @return [ Void ]+ */+exports.isScreenOff = function (fn)+{+ if (this._isAndroid)+ {+ cordova.exec(fn, null, 'BackgroundModeExt', 'dimmed', []);+ }+ else+ {+ fn(undefined);+ }+};++/**+ * Wake up the device.+ *+ * @return [ Void ]+ */+exports.wakeUp = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'wakeup', []);+ }+};++/**+ * Wake up and unlock the device.+ *+ * @return [ Void ]+ */+exports.unlock = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'unlock', []);+ }+};++/**+ * If the mode is enabled or disabled.+ *+ * @return [ Boolean ]+ */+exports.isEnabled = function()+{+ return this._isEnabled !== false;+};++/**+ * If the mode is active.+ *+ * @return [ Boolean ]+ */+exports.isActive = function()+{+ return this._isActive !== false;+};++exports._listener = {};++/**+ * Fire event with given arguments.+ *+ * @param [ String ] event The event's name.+ * @param [ Array<Object> ] The callback's arguments.+ *+ * @return [ Void ]+ */+exports.fireEvent = function (event)+{+ var args = Array.apply(null, arguments).slice(1),+ listener = this._listener[event];++ if (!listener)+ return;++ for (var i = 0; i < listener.length; i++)+ {+ var fn = listener[i][0],+ scope = listener[i][1];++ fn.apply(scope, args);+ }+};++/**+ * Register callback for given event.+ *+ * @param [ String ] event The event's name.+ * @param [ Function ] callback The function to be exec as callback.+ * @param [ Object ] scope The callback function's scope.+ *+ * @return [ Void ]+ */+exports.on = function (event, callback, scope)+{+ if (typeof callback !== "function")+ return;++ if (!this._listener[event])+ {+ this._listener[event] = [];+ }++ var item = [callback, scope || window];++ this._listener[event].push(item);+};++/**+ * Unregister callback for given event.+ *+ * @param [ String ] event The event's name.+ * @param [ Function ] callback The function to be exec as callback.+ *+ * @return [ Void ]+ */+exports.un = function (event, callback)+{+ var listener = this._listener[event];++ if (!listener)+ return;++ for (var i = 0; i < listener.length; i++)+ {+ var fn = listener[i][0];++ if (fn == callback)+ {+ listener.splice(i, 1);+ break;+ }+ }+};++/**+ * @private+ *+ * Flag indicates if the mode is enabled.+ */+exports._isEnabled = false;++/**+ * @private+ *+ * Flag indicates if the mode is active.+ */+exports._isActive = false;++/**+ * @private+ *+ * Default values of all available options.+ */+exports._defaults =+{+ title: 'App is running in background',+ text: 'Doing heavy tasks.',+ bigText: false,+ resume: true,+ silent: false,+ hidden: true,+ color: undefined,+ icon: 'icon'+};++/**+ * @private+ *+ * Merge settings with default values.+ *+ * @param [ Object ] options The custom options.+ * @param [ Object ] toMergeIn The options to merge in.+ *+ * @return [ Object ] Default values merged with custom values.+ */+exports._mergeObjects = function (options, toMergeIn)+{+ for (var key in toMergeIn)+ {+ if (!options.hasOwnProperty(key))+ {+ options[key] = toMergeIn[key];+ continue;+ }+ }++ return options;+};++/**+ * @private+ *+ * Setter for the isActive flag. Resets the+ * settings if the mode isnt active anymore.+ *+ * @param [ Boolean] value The new value for the flag.+ *+ * @return [ Void ]+ */+exports._setActive = function(value)+{+ if (this._isActive == value)+ return;++ this._isActive = value;+ this._settings = value ? this._mergeObjects({}, this._defaults) : {};+};++/**+ * @private+ *+ * Initialize the plugin.+ *+ * Method should be called after the 'deviceready' event+ * but before the event listeners will be called.+ *+ * @return [ Void ]+ */+exports._pluginInitialize = function()+{+ this._isAndroid = device.platform.match(/^android|amazon/i) !== null;+ this.setDefaults({});++ if (device.platform == 'browser')+ {+ this.enable();+ this._isEnabled = true;+ }++ this._isActive = this._isActive || device.platform == 'browser';+};++// Called before 'deviceready' listener will be called+channel.onCordovaReady.subscribe(function()+{+ channel.onCordovaInfoReady.subscribe(function() {+ exports._pluginInitialize();+ });+});++// Called after 'deviceready' event+channel.deviceready.subscribe(function()+{+ if (exports.isEnabled())+ {+ exports.fireEvent('enable');+ }++ if (exports.isActive())+ {+ exports.fireEvent('activate');+ }+});++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/Camera.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/Camera.jsnew file mode 100644index 000000000..3f614ec80--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/Camera.js@@ -0,0 +1,188 @@+cordova.define("cordova-plugin-camera.camera", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var exec = require('cordova/exec');+var Camera = require('./Camera');+// XXX: commented out+// CameraPopoverHandle = require('./CameraPopoverHandle');++/**+ * @namespace navigator+ */++/**+ * @exports camera+ */+var cameraExport = {};++// Tack on the Camera Constants to the base camera plugin.+for (var key in Camera) {+ cameraExport[key] = Camera[key];+}++/**+ * Callback function that provides an error message.+ * @callback module:camera.onError+ * @param {string} message - The message is provided by the device's native code.+ */++/**+ * Callback function that provides the image data.+ * @callback module:camera.onSuccess+ * @param {string} imageData - Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`]{@link module:camera.CameraOptions} in effect.+ * @example+ * // Show image+ * //+ * function cameraCallback(imageData) {+ * var image = document.getElementById('myImage');+ * image.src = "data:image/jpeg;base64," + imageData;+ * }+ */++/**+ * Optional parameters to customize the camera settings.+ * * [Quirks](#CameraOptions-quirks)+ * @typedef module:camera.CameraOptions+ * @type {Object}+ * @property {number} [quality=50] - Quality of the saved image, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information about the camera's resolution is unavailable.)+ * @property {module:Camera.DestinationType} [destinationType=FILE_URI] - Choose the format of the return value.+ * @property {module:Camera.PictureSourceType} [sourceType=CAMERA] - Set the source of the picture.+ * @property {Boolean} [allowEdit=false] - Allow simple editing of image before selection.+ * @property {module:Camera.EncodingType} [encodingType=JPEG] - Choose the returned image file's encoding.+ * @property {number} [targetWidth] - Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant.+ * @property {number} [targetHeight] - Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant.+ * @property {module:Camera.MediaType} [mediaType=PICTURE] - Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`.+ * @property {Boolean} [correctOrientation] - Rotate the image to correct for the orientation of the device during capture.+ * @property {Boolean} [saveToPhotoAlbum] - Save the image to the photo album on the device after capture.+ * @property {module:CameraPopoverOptions} [popoverOptions] - iOS-only options that specify popover location in iPad.+ * @property {module:Camera.Direction} [cameraDirection=BACK] - Choose the camera to use (front- or back-facing).+ */++/**+ * @description Takes a photo using the camera, or retrieves a photo from the device's+ * image gallery. The image is passed to the success callback as a+ * Base64-encoded `String`, or as the URI for the image file.+ *+ * The `camera.getPicture` function opens the device's default camera+ * application that allows users to snap pictures by default - this behavior occurs,+ * when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`]{@link module:Camera.PictureSourceType}.+ * Once the user snaps the photo, the camera application closes and the application is restored.+ *+ * If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or+ * `Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays+ * that allows users to select an existing image.+ *+ * The return value is sent to the [`cameraSuccess`]{@link module:camera.onSuccess} callback function, in+ * one of the following formats, depending on the specified+ * `cameraOptions`:+ *+ * - A `String` containing the Base64-encoded photo image.+ * - A `String` representing the image file location on local storage (default).+ *+ * You can do whatever you want with the encoded image or URI, for+ * example:+ *+ * - Render the image in an `<img>` tag, as in the example below+ * - Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)+ * - Post the data to a remote server+ *+ * __NOTE__: Photo resolution on newer devices is quite good. Photos+ * selected from the device's gallery are not downscaled to a lower+ * quality, even if a `quality` parameter is specified. To avoid common+ * memory problems, set `Camera.destinationType` to `FILE_URI` rather+ * than `DATA_URL`.+ *+ * __Supported Platforms__+ *+ * - Android+ * - BlackBerry+ * - Browser+ * - Firefox+ * - FireOS+ * - iOS+ * - Windows+ * - WP8+ * - Ubuntu+ *+ * More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).+ *+ * @example+ * navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);+ * @param {module:camera.onSuccess} successCallback+ * @param {module:camera.onError} errorCallback+ * @param {module:camera.CameraOptions} options CameraOptions+ */+cameraExport.getPicture = function (successCallback, errorCallback, options) {+ argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);+ options = options || {};+ var getValue = argscheck.getValue;++ var quality = getValue(options.quality, 50);+ var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);+ var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);+ var targetWidth = getValue(options.targetWidth, -1);+ var targetHeight = getValue(options.targetHeight, -1);+ var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);+ var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);+ var allowEdit = !!options.allowEdit;+ var correctOrientation = !!options.correctOrientation;+ var saveToPhotoAlbum = !!options.saveToPhotoAlbum;+ var popoverOptions = getValue(options.popoverOptions, null);+ var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);++ var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,+ mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];++ exec(successCallback, errorCallback, 'Camera', 'takePicture', args);+ // XXX: commented out+ // return new CameraPopoverHandle();+};++/**+ * Removes intermediate image files that are kept in temporary storage+ * after calling [`camera.getPicture`]{@link module:camera.getPicture}. Applies only when the value of+ * `Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the+ * `Camera.destinationType` equals `Camera.DestinationType.FILE_URI`.+ *+ * __Supported Platforms__+ *+ * - iOS+ *+ * @example+ * navigator.camera.cleanup(onSuccess, onFail);+ *+ * function onSuccess() {+ * console.log("Camera cleanup success.")+ * }+ *+ * function onFail(message) {+ * alert('Failed because: ' + message);+ * }+ */+cameraExport.cleanup = function (successCallback, errorCallback) {+ exec(successCallback, errorCallback, 'Camera', 'cleanup', []);+};++module.exports = cameraExport;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/CameraConstants.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/CameraConstants.jsnew file mode 100644index 000000000..4f4b046f1--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/CameraConstants.js@@ -0,0 +1,104 @@+cordova.define("cordova-plugin-camera.Camera", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * @module Camera+ */+module.exports = {+ /**+ * @description+ * Defines the output format of `Camera.getPicture` call.+ * _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with+ * `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will+ * disable any image modifications (resize, quality change, cropping, etc.) due+ * to implementation specific.+ *+ * @enum {number}+ */+ DestinationType: {+ /** Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible */+ DATA_URL: 0,+ /** Return file uri (content://media/external/images/media/2 for Android) */+ FILE_URI: 1,+ /** Return native uri (eg. asset-library://... for iOS) */+ NATIVE_URI: 2+ },+ /**+ * @enum {number}+ */+ EncodingType: {+ /** Return JPEG encoded image */+ JPEG: 0,+ /** Return PNG encoded image */+ PNG: 1+ },+ /**+ * @enum {number}+ */+ MediaType: {+ /** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */+ PICTURE: 0,+ /** Allow selection of video only, ONLY RETURNS URL */+ VIDEO: 1,+ /** Allow selection from all media types */+ ALLMEDIA: 2+ },+ /**+ * @description+ * Defines the output format of `Camera.getPicture` call.+ * _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`+ * along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality+ * change, cropping, etc.) due to implementation specific.+ *+ * @enum {number}+ */+ PictureSourceType: {+ /** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */+ PHOTOLIBRARY: 0,+ /** Take picture from camera */+ CAMERA: 1,+ /** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */+ SAVEDPHOTOALBUM: 2+ },+ /**+ * Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.+ * @enum {number}+ */+ PopoverArrowDirection: {+ ARROW_UP: 1,+ ARROW_DOWN: 2,+ ARROW_LEFT: 4,+ ARROW_RIGHT: 8,+ ARROW_ANY: 15+ },+ /**+ * @enum {number}+ */+ Direction: {+ /** Use the back-facing camera */+ BACK: 0,+ /** Use the front-facing camera */+ FRONT: 1+ }+};++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.jsnew file mode 100644index 000000000..6e03c52ee--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js@@ -0,0 +1,59 @@+cordova.define("cordova-plugin-camera.CameraPopoverOptions", function(require, exports, module) {+/*+ *+ * 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 Camera = require('./Camera');++/**+ * @namespace navigator+ */++/**+ * iOS-only parameters that specify the anchor element location and arrow+ * direction of the popover when selecting images from an iPad's library+ * or album.+ * Note that the size of the popover may change to adjust to the+ * direction of the arrow and orientation of the screen. Make sure to+ * account for orientation changes when specifying the anchor element+ * location.+ * @module CameraPopoverOptions+ * @param {Number} [x=0] - x pixel coordinate of screen element onto which to anchor the popover.+ * @param {Number} [y=32] - y pixel coordinate of screen element onto which to anchor the popover.+ * @param {Number} [width=320] - width, in pixels, of the screen element onto which to anchor the popover.+ * @param {Number} [height=480] - height, in pixels, of the screen element onto which to anchor the popover.+ * @param {module:Camera.PopoverArrowDirection} [arrowDir=ARROW_ANY] - Direction the arrow on the popover should point.+ * @param {Number} [popoverWidth=0] - width of the popover (0 or not specified will use apple's default width).+ * @param {Number} [popoverHeight=0] - height of the popover (0 or not specified will use apple's default height).+ */+var CameraPopoverOptions = function (x, y, width, height, arrowDir, popoverWidth, popoverHeight) {+ // information of rectangle that popover should be anchored to+ this.x = x || 0;+ this.y = y || 32;+ this.width = width || 320;+ this.height = height || 480;+ this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;+ this.popoverWidth = popoverWidth || 0;+ this.popoverHeight = popoverHeight || 0;+};++module.exports = CameraPopoverOptions;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.jsnew file mode 100644index 000000000..6da9fa35d--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js@@ -0,0 +1,69 @@+cordova.define("cordova-plugin-camera.CameraPopoverHandle", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');++/**+ * @namespace navigator+ */++/**+ * A handle to an image picker popover.+ *+ * __Supported Platforms__+ *+ * - iOS+ *+ * @example+ * navigator.camera.getPicture(onSuccess, onFail,+ * {+ * destinationType: Camera.DestinationType.FILE_URI,+ * sourceType: Camera.PictureSourceType.PHOTOLIBRARY,+ * popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY, 300, 600)+ * });+ *+ * // Reposition the popover if the orientation changes.+ * window.onorientationchange = function() {+ * var cameraPopoverHandle = new CameraPopoverHandle();+ * var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY, 400, 500);+ * cameraPopoverHandle.setPosition(cameraPopoverOptions);+ * }+ * @module CameraPopoverHandle+ */+var CameraPopoverHandle = function () {+ /**+ * Can be used to reposition the image selection dialog,+ * for example, when the device orientation changes.+ * @memberof CameraPopoverHandle+ * @instance+ * @method setPosition+ * @param {module:CameraPopoverOptions} popoverOptions+ */+ this.setPosition = function (popoverOptions) {+ var args = [ popoverOptions ];+ exec(null, null, 'Camera', 'repositionPopover', args);+ };+};++module.exports = CameraPopoverHandle;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-device/www/device.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-device/www/device.jsnew file mode 100644index 000000000..ae48e3546--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-device/www/device.js@@ -0,0 +1,86 @@+cordova.define("cordova-plugin-device.device", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var channel = require('cordova/channel');+var utils = require('cordova/utils');+var exec = require('cordova/exec');+var cordova = require('cordova');++channel.createSticky('onCordovaInfoReady');+// Tell cordova channel to wait on the CordovaInfoReady event+channel.waitForInitialization('onCordovaInfoReady');++/**+ * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the+ * phone, etc.+ * @constructor+ */+function Device () {+ this.available = false;+ this.platform = null;+ this.version = null;+ this.uuid = null;+ this.cordova = null;+ this.model = null;+ this.manufacturer = null;+ this.isVirtual = null;+ this.serial = null;++ var me = this;++ channel.onCordovaReady.subscribe(function () {+ me.getInfo(function (info) {+ // ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js+ // TODO: CB-5105 native implementations should not return info.cordova+ var buildLabel = cordova.version;+ me.available = true;+ me.platform = info.platform;+ me.version = info.version;+ me.uuid = info.uuid;+ me.cordova = buildLabel;+ me.model = info.model;+ me.isVirtual = info.isVirtual;+ me.manufacturer = info.manufacturer || 'unknown';+ me.serial = info.serial || 'unknown';+ channel.onCordovaInfoReady.fire();+ }, function (e) {+ me.available = false;+ utils.alert('[ERROR] Error initializing Cordova: ' + e);+ });+ });+}++/**+ * Get device info+ *+ * @param {Function} successCallback The function to call when the heading data is available+ * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)+ */+Device.prototype.getInfo = function (successCallback, errorCallback) {+ argscheck.checkArgs('fF', 'Device.getInfo', arguments);+ exec(successCallback, errorCallback, 'Device', 'getDeviceInfo', []);+};++module.exports = new Device();++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.jsnew file mode 100644index 000000000..395c4d973--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js@@ -0,0 +1,54 @@+cordova.define("cordova-plugin-file-opener2.FileOpener2", function(require, exports, module) {+/*jslint browser: true, devel: true, node: true, sloppy: true, plusplus: true*/+/*global require, cordova */+/*+The MIT License (MIT)++Copyright (c) 2013 pwlin - [email protected]++Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+*/+var exec = require('cordova/exec');++function FileOpener2() {}++FileOpener2.prototype.open = function (fileName, contentType, callbackContext) {+ contentType = contentType || '';+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'open', [fileName, contentType]);+};++FileOpener2.prototype.showOpenWithDialog = function (fileName, contentType, callbackContext) {+ contentType = contentType || '';+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'open', [fileName, contentType, false, callbackContext.position || [0, 0]]);+};++FileOpener2.prototype.uninstall = function (packageId, callbackContext) {+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'uninstall', [packageId]);+};++FileOpener2.prototype.appIsInstalled = function (packageId, callbackContext) {+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'appIsInstalled', [packageId]);+};++module.exports = new FileOpener2();++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/DirectoryEntry.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/DirectoryEntry.jsnew file mode 100644index 000000000..bb676eb6c--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/DirectoryEntry.js@@ -0,0 +1,120 @@+cordova.define("cordova-plugin-file.DirectoryEntry", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var utils = require('cordova/utils');+var exec = require('cordova/exec');+var Entry = require('./Entry');+var FileError = require('./FileError');+var DirectoryReader = require('./DirectoryReader');++/**+ * An interface representing a directory on the file system.+ *+ * {boolean} isFile always false (readonly)+ * {boolean} isDirectory always true (readonly)+ * {DOMString} name of the directory, excluding the path leading to it (readonly)+ * {DOMString} fullPath the absolute full path to the directory (readonly)+ * {FileSystem} filesystem on which the directory resides (readonly)+ */+var DirectoryEntry = function (name, fullPath, fileSystem, nativeURL) {++ // add trailing slash if it is missing+ if ((fullPath) && !/\/$/.test(fullPath)) {+ fullPath += '/';+ }+ // add trailing slash if it is missing+ if (nativeURL && !/\/$/.test(nativeURL)) {+ nativeURL += '/';+ }+ DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL);+};++utils.extend(DirectoryEntry, Entry);++/**+ * Creates a new DirectoryReader to read entries from this directory+ */+DirectoryEntry.prototype.createReader = function () {+ return new DirectoryReader(this.toInternalURL());+};++/**+ * Creates or looks up a directory+ *+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory+ * @param {Flags} options to create or exclusively create the directory+ * @param {Function} successCallback is called with the new entry+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryEntry.prototype.getDirectory = function (path, options, successCallback, errorCallback) {+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);+ var fs = this.filesystem;+ var win = successCallback && function (result) {+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);+ successCallback(entry);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getDirectory', [this.toInternalURL(), path, options]);+};++/**+ * Deletes a directory and all of it's contents+ *+ * @param {Function} successCallback is called with no parameters+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryEntry.prototype.removeRecursively = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(successCallback, fail, 'File', 'removeRecursively', [this.toInternalURL()]);+};++/**+ * Creates or looks up a file+ *+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file+ * @param {Flags} options to create or exclusively create the file+ * @param {Function} successCallback is called with the new entry+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryEntry.prototype.getFile = function (path, options, successCallback, errorCallback) {+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);+ var fs = this.filesystem;+ var win = successCallback && function (result) {+ var FileEntry = require('./FileEntry');+ var entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL);+ successCallback(entry);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getFile', [this.toInternalURL(), path, options]);+};++module.exports = DirectoryEntry;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/DirectoryReader.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/DirectoryReader.jsnew file mode 100644index 000000000..417c85f10--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/DirectoryReader.js@@ -0,0 +1,75 @@+cordova.define("cordova-plugin-file.DirectoryReader", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var FileError = require('./FileError');++/**+ * An interface that lists the files and directories in a directory.+ */+function DirectoryReader (localURL) {+ this.localURL = localURL || null;+ this.hasReadEntries = false;+}++/**+ * Returns a list of entries from a directory.+ *+ * @param {Function} successCallback is called with a list of entries+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryReader.prototype.readEntries = function (successCallback, errorCallback) {+ // If we've already read and passed on this directory's entries, return an empty list.+ if (this.hasReadEntries) {+ successCallback([]);+ return;+ }+ var reader = this;+ var win = typeof successCallback !== 'function' ? null : function (result) {+ var retVal = [];+ for (var i = 0; i < result.length; i++) {+ var entry = null;+ if (result[i].isDirectory) {+ entry = new (require('./DirectoryEntry'))();+ } else if (result[i].isFile) {+ entry = new (require('./FileEntry'))();+ }+ entry.isDirectory = result[i].isDirectory;+ entry.isFile = result[i].isFile;+ entry.name = result[i].name;+ entry.fullPath = result[i].fullPath;+ entry.filesystem = new (require('./FileSystem'))(result[i].filesystemName);+ entry.nativeURL = result[i].nativeURL;+ retVal.push(entry);+ }+ reader.hasReadEntries = true;+ successCallback(retVal);+ };+ var fail = typeof errorCallback !== 'function' ? null : function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'readEntries', [this.localURL]);+};++module.exports = DirectoryReader;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Entry.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Entry.jsnew file mode 100644index 000000000..b296d999e--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Entry.js@@ -0,0 +1,263 @@+cordova.define("cordova-plugin-file.Entry", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var exec = require('cordova/exec');+var FileError = require('./FileError');+var Metadata = require('./Metadata');++/**+ * Represents a file or directory on the local file system.+ *+ * @param isFile+ * {boolean} true if Entry is a file (readonly)+ * @param isDirectory+ * {boolean} true if Entry is a directory (readonly)+ * @param name+ * {DOMString} name of the file or directory, excluding the path+ * leading to it (readonly)+ * @param fullPath+ * {DOMString} the absolute full path to the file or directory+ * (readonly)+ * @param fileSystem+ * {FileSystem} the filesystem on which this entry resides+ * (readonly)+ * @param nativeURL+ * {DOMString} an alternate URL which can be used by native+ * webview controls, for example media players.+ * (optional, readonly)+ */+function Entry (isFile, isDirectory, name, fullPath, fileSystem, nativeURL) {+ this.isFile = !!isFile;+ this.isDirectory = !!isDirectory;+ this.name = name || '';+ this.fullPath = fullPath || '';+ this.filesystem = fileSystem || null;+ this.nativeURL = nativeURL || null;+}++/**+ * Look up the metadata of the entry.+ *+ * @param successCallback+ * {Function} is called with a Metadata object+ * @param errorCallback+ * {Function} is called with a FileError+ */+Entry.prototype.getMetadata = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);+ var success = successCallback && function (entryMetadata) {+ var metadata = new Metadata({+ size: entryMetadata.size,+ modificationTime: entryMetadata.lastModifiedDate+ });+ successCallback(metadata);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(success, fail, 'File', 'getFileMetadata', [this.toInternalURL()]);+};++/**+ * Set the metadata of the entry.+ *+ * @param successCallback+ * {Function} is called with a Metadata object+ * @param errorCallback+ * {Function} is called with a FileError+ * @param metadataObject+ * {Object} keys and values to set+ */+Entry.prototype.setMetadata = function (successCallback, errorCallback, metadataObject) {+ argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);+ exec(successCallback, errorCallback, 'File', 'setMetadata', [this.toInternalURL(), metadataObject]);+};++/**+ * Move a file or directory to a new location.+ *+ * @param parent+ * {DirectoryEntry} the directory to which to move this entry+ * @param newName+ * {DOMString} new name of the entry, defaults to the current name+ * @param successCallback+ * {Function} called with the new DirectoryEntry object+ * @param errorCallback+ * {Function} called with a FileError+ */+Entry.prototype.moveTo = function (parent, newName, successCallback, errorCallback) {+ argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ var srcURL = this.toInternalURL();+ // entry name+ var name = newName || this.name;+ var success = function (entry) {+ if (entry) {+ if (successCallback) {+ // create appropriate Entry object+ var newFSName = entry.filesystemName || (entry.filesystem && entry.filesystem.name);+ var fs = newFSName ? new FileSystem(newFSName, { name: '', fullPath: '/' }) : new FileSystem(parent.filesystem.name, { name: '', fullPath: '/' }); // eslint-disable-line no-undef+ var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('cordova-plugin-file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL);+ successCallback(result);+ }+ } else {+ // no Entry object returned+ if (fail) {+ fail(FileError.NOT_FOUND_ERR);+ }+ }+ };++ // copy+ exec(success, fail, 'File', 'moveTo', [srcURL, parent.toInternalURL(), name]);+};++/**+ * Copy a directory to a different location.+ *+ * @param parent+ * {DirectoryEntry} the directory to which to copy the entry+ * @param newName+ * {DOMString} new name of the entry, defaults to the current name+ * @param successCallback+ * {Function} called with the new Entry object+ * @param errorCallback+ * {Function} called with a FileError+ */+Entry.prototype.copyTo = function (parent, newName, successCallback, errorCallback) {+ argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ var srcURL = this.toInternalURL();+ // entry name+ var name = newName || this.name;+ // success callback+ var success = function (entry) {+ if (entry) {+ if (successCallback) {+ // create appropriate Entry object+ var newFSName = entry.filesystemName || (entry.filesystem && entry.filesystem.name);+ var fs = newFSName ? new FileSystem(newFSName, { name: '', fullPath: '/' }) : new FileSystem(parent.filesystem.name, { name: '', fullPath: '/' }); // eslint-disable-line no-undef+ var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('cordova-plugin-file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL);+ successCallback(result);+ }+ } else {+ // no Entry object returned+ if (fail) {+ fail(FileError.NOT_FOUND_ERR);+ }+ }+ };++ // copy+ exec(success, fail, 'File', 'copyTo', [srcURL, parent.toInternalURL(), name]);+};++/**+ * Return a URL that can be passed across the bridge to identify this entry.+ */+Entry.prototype.toInternalURL = function () {+ if (this.filesystem && this.filesystem.__format__) {+ return this.filesystem.__format__(this.fullPath, this.nativeURL);+ }+};++/**+ * Return a URL that can be used to identify this entry.+ * Use a URL that can be used to as the src attribute of a <video> or+ * <audio> tag. If that is not possible, construct a cdvfile:// URL.+ */+Entry.prototype.toURL = function () {+ if (this.nativeURL) {+ return this.nativeURL;+ }+ // fullPath attribute may contain the full URL in the case that+ // toInternalURL fails.+ return this.toInternalURL() || 'file://localhost' + this.fullPath;+};++/**+ * Backwards-compatibility: In v1.0.0 - 1.0.2, .toURL would only return a+ * cdvfile:// URL, and this method was necessary to obtain URLs usable by the+ * webview.+ * See CB-6051, CB-6106, CB-6117, CB-6152, CB-6199, CB-6201, CB-6243, CB-6249,+ * and CB-6300.+ */+Entry.prototype.toNativeURL = function () {+ console.log("DEPRECATED: Update your code to use 'toURL'");+ return this.toURL();+};++/**+ * Returns a URI that can be used to identify this entry.+ *+ * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.+ * @return uri+ */+Entry.prototype.toURI = function (mimeType) {+ console.log("DEPRECATED: Update your code to use 'toURL'");+ return this.toURL();+};++/**+ * Remove a file or directory. It is an error to attempt to delete a+ * directory that is not empty. It is an error to attempt to delete a+ * root directory of a file system.+ *+ * @param successCallback {Function} called with no parameters+ * @param errorCallback {Function} called with a FileError+ */+Entry.prototype.remove = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'Entry.remove', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(successCallback, fail, 'File', 'remove', [this.toInternalURL()]);+};++/**+ * Look up the parent DirectoryEntry of this entry.+ *+ * @param successCallback {Function} called with the parent DirectoryEntry object+ * @param errorCallback {Function} called with a FileError+ */+Entry.prototype.getParent = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'Entry.getParent', arguments);+ var fs = this.filesystem;+ var win = successCallback && function (result) {+ var DirectoryEntry = require('./DirectoryEntry');+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);+ successCallback(entry);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getParent', [this.toInternalURL()]);+};++module.exports = Entry;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/File.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/File.jsnew file mode 100644index 000000000..c77178653--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/File.js@@ -0,0 +1,81 @@+cordova.define("cordova-plugin-file.File", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Constructor.+ * name {DOMString} name of the file, without path information+ * fullPath {DOMString} the full path of the file, including the name+ * type {DOMString} mime type+ * lastModifiedDate {Date} last modified date+ * size {Number} size of the file in bytes+ */++var File = function (name, localURL, type, lastModifiedDate, size) {+ this.name = name || '';+ this.localURL = localURL || null;+ this.type = type || null;+ this.lastModified = lastModifiedDate || null;+ // For backwards compatibility, store the timestamp in lastModifiedDate as well+ this.lastModifiedDate = lastModifiedDate || null;+ this.size = size || 0;++ // These store the absolute start and end for slicing the file.+ this.start = 0;+ this.end = this.size;+};++/**+ * Returns a "slice" of the file. Since Cordova Files don't contain the actual+ * content, this really returns a File with adjusted start and end.+ * Slices of slices are supported.+ * start {Number} The index at which to start the slice (inclusive).+ * end {Number} The index at which to end the slice (exclusive).+ */+File.prototype.slice = function (start, end) {+ var size = this.end - this.start;+ var newStart = 0;+ var newEnd = size;+ if (arguments.length) {+ if (start < 0) {+ newStart = Math.max(size + start, 0);+ } else {+ newStart = Math.min(size, start);+ }+ }++ if (arguments.length >= 2) {+ if (end < 0) {+ newEnd = Math.max(size + end, 0);+ } else {+ newEnd = Math.min(end, size);+ }+ }++ var newFile = new File(this.name, this.localURL, this.type, this.lastModified, this.size);+ newFile.start = this.start + newStart;+ newFile.end = this.start + newEnd;+ return newFile;+};++module.exports = File;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileEntry.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileEntry.jsnew file mode 100644index 000000000..6651b5542--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileEntry.js@@ -0,0 +1,95 @@+cordova.define("cordova-plugin-file.FileEntry", function(require, exports, module) {+/*+ *+ * 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 utils = require('cordova/utils');+var exec = require('cordova/exec');+var Entry = require('./Entry');+var FileWriter = require('./FileWriter');+var File = require('./File');+var FileError = require('./FileError');++/**+ * An interface representing a file on the file system.+ *+ * {boolean} isFile always true (readonly)+ * {boolean} isDirectory always false (readonly)+ * {DOMString} name of the file, excluding the path leading to it (readonly)+ * {DOMString} fullPath the absolute full path to the file (readonly)+ * {FileSystem} filesystem on which the file resides (readonly)+ */+var FileEntry = function (name, fullPath, fileSystem, nativeURL) {+ // remove trailing slash if it is present+ if (fullPath && /\/$/.test(fullPath)) {+ fullPath = fullPath.substring(0, fullPath.length - 1);+ }+ if (nativeURL && /\/$/.test(nativeURL)) {+ nativeURL = nativeURL.substring(0, nativeURL.length - 1);+ }++ FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);+};++utils.extend(FileEntry, Entry);++/**+ * Creates a new FileWriter associated with the file that this FileEntry represents.+ *+ * @param {Function} successCallback is called with the new FileWriter+ * @param {Function} errorCallback is called with a FileError+ */+FileEntry.prototype.createWriter = function (successCallback, errorCallback) {+ this.file(function (filePointer) {+ var writer = new FileWriter(filePointer);++ if (writer.localURL === null || writer.localURL === '') {+ if (errorCallback) {+ errorCallback(new FileError(FileError.INVALID_STATE_ERR));+ }+ } else {+ if (successCallback) {+ successCallback(writer);+ }+ }+ }, errorCallback);+};++/**+ * Returns a File that represents the current state of the file that this FileEntry represents.+ *+ * @param {Function} successCallback is called with the new File object+ * @param {Function} errorCallback is called with a FileError+ */+FileEntry.prototype.file = function (successCallback, errorCallback) {+ var localURL = this.toInternalURL();+ var win = successCallback && function (f) {+ var file = new File(f.name, localURL, f.type, f.lastModifiedDate, f.size);+ successCallback(file);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getFileMetadata', [localURL]);+};++module.exports = FileEntry;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileError.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileError.jsnew file mode 100644index 000000000..f378c3874--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileError.js@@ -0,0 +1,49 @@+cordova.define("cordova-plugin-file.FileError", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * FileError+ */+function FileError (error) {+ this.code = error || null;+}++// File error codes+// Found in DOMException+FileError.NOT_FOUND_ERR = 1;+FileError.SECURITY_ERR = 2;+FileError.ABORT_ERR = 3;++// Added by File API specification+FileError.NOT_READABLE_ERR = 4;+FileError.ENCODING_ERR = 5;+FileError.NO_MODIFICATION_ALLOWED_ERR = 6;+FileError.INVALID_STATE_ERR = 7;+FileError.SYNTAX_ERR = 8;+FileError.INVALID_MODIFICATION_ERR = 9;+FileError.QUOTA_EXCEEDED_ERR = 10;+FileError.TYPE_MISMATCH_ERR = 11;+FileError.PATH_EXISTS_ERR = 12;++module.exports = FileError;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileReader.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileReader.jsnew file mode 100644index 000000000..5c030913b--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileReader.js@@ -0,0 +1,301 @@+cordova.define("cordova-plugin-file.FileReader", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var modulemapper = require('cordova/modulemapper');+var utils = require('cordova/utils');+var FileError = require('./FileError');+var ProgressEvent = require('./ProgressEvent');+var origFileReader = modulemapper.getOriginalSymbol(window, 'FileReader');++/**+ * This class reads the mobile device file system.+ *+ * For Android:+ * The root directory is the root of the file system.+ * To read from the SD card, the file name is "sdcard/my_file.txt"+ * @constructor+ */+var FileReader = function () {+ this._readyState = 0;+ this._error = null;+ this._result = null;+ this._progress = null;+ this._localURL = '';+ this._realReader = origFileReader ? new origFileReader() : {}; // eslint-disable-line new-cap+};++/**+ * Defines the maximum size to read at a time via the native API. The default value is a compromise between+ * minimizing the overhead of many exec() calls while still reporting progress frequently enough for large files.+ * (Note attempts to allocate more than a few MB of contiguous memory on the native side are likely to cause+ * OOM exceptions, while the JS engine seems to have fewer problems managing large strings or ArrayBuffers.)+ */+FileReader.READ_CHUNK_SIZE = 256 * 1024;++// States+FileReader.EMPTY = 0;+FileReader.LOADING = 1;+FileReader.DONE = 2;++utils.defineGetter(FileReader.prototype, 'readyState', function () {+ return this._localURL ? this._readyState : this._realReader.readyState;+});++utils.defineGetter(FileReader.prototype, 'error', function () {+ return this._localURL ? this._error : this._realReader.error;+});++utils.defineGetter(FileReader.prototype, 'result', function () {+ return this._localURL ? this._result : this._realReader.result;+});++function defineEvent (eventName) {+ utils.defineGetterSetter(FileReader.prototype, eventName, function () {+ return this._realReader[eventName] || null;+ }, function (value) {+ this._realReader[eventName] = value;+ });+}+defineEvent('onloadstart'); // When the read starts.+defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)+defineEvent('onload'); // When the read has successfully completed.+defineEvent('onerror'); // When the read has failed (see errors).+defineEvent('onloadend'); // When the request has completed (either in success or failure).+defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.++function initRead (reader, file) {+ // Already loading something+ if (reader.readyState === FileReader.LOADING) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ reader._result = null;+ reader._error = null;+ reader._progress = 0;+ reader._readyState = FileReader.LOADING;++ if (typeof file.localURL === 'string') {+ reader._localURL = file.localURL;+ } else {+ reader._localURL = '';+ return true;+ }++ if (reader.onloadstart) {+ reader.onloadstart(new ProgressEvent('loadstart', {target: reader}));+ }+}++/**+ * Callback used by the following read* functions to handle incremental or final success.+ * Must be bound to the FileReader's this along with all but the last parameter,+ * e.g. readSuccessCallback.bind(this, "readAsText", "UTF-8", offset, totalSize, accumulate)+ * @param readType The name of the read function to call.+ * @param encoding Text encoding, or null if this is not a text type read.+ * @param offset Starting offset of the read.+ * @param totalSize Total number of bytes or chars to read.+ * @param accumulate A function that takes the callback result and accumulates it in this._result.+ * @param r Callback result returned by the last read exec() call, or null to begin reading.+ */+function readSuccessCallback (readType, encoding, offset, totalSize, accumulate, r) {+ if (this._readyState === FileReader.DONE) {+ return;+ }++ var CHUNK_SIZE = FileReader.READ_CHUNK_SIZE;+ if (readType === 'readAsDataURL') {+ // Windows proxy does not support reading file slices as Data URLs+ // so read the whole file at once.+ CHUNK_SIZE = cordova.platformId === 'windows' ? totalSize : // eslint-disable-line no-undef+ // Calculate new chunk size for data URLs to be multiply of 3+ // Otherwise concatenated base64 chunks won't be valid base64 data+ FileReader.READ_CHUNK_SIZE - (FileReader.READ_CHUNK_SIZE % 3) + 3;+ }++ if (typeof r !== 'undefined') {+ accumulate(r);+ this._progress = Math.min(this._progress + CHUNK_SIZE, totalSize);++ if (typeof this.onprogress === 'function') {+ this.onprogress(new ProgressEvent('progress', {loaded: this._progress, total: totalSize}));+ }+ }++ if (typeof r === 'undefined' || this._progress < totalSize) {+ var execArgs = [+ this._localURL,+ offset + this._progress,+ offset + this._progress + Math.min(totalSize - this._progress, CHUNK_SIZE)];+ if (encoding) {+ execArgs.splice(1, 0, encoding);+ }+ exec(+ readSuccessCallback.bind(this, readType, encoding, offset, totalSize, accumulate),+ readFailureCallback.bind(this),+ 'File', readType, execArgs);+ } else {+ this._readyState = FileReader.DONE;++ if (typeof this.onload === 'function') {+ this.onload(new ProgressEvent('load', {target: this}));+ }++ if (typeof this.onloadend === 'function') {+ this.onloadend(new ProgressEvent('loadend', {target: this}));+ }+ }+}++/**+ * Callback used by the following read* functions to handle errors.+ * Must be bound to the FileReader's this, e.g. readFailureCallback.bind(this)+ */+function readFailureCallback (e) {+ if (this._readyState === FileReader.DONE) {+ return;+ }++ this._readyState = FileReader.DONE;+ this._result = null;+ this._error = new FileError(e);++ if (typeof this.onerror === 'function') {+ this.onerror(new ProgressEvent('error', {target: this}));+ }++ if (typeof this.onloadend === 'function') {+ this.onloadend(new ProgressEvent('loadend', {target: this}));+ }+}++/**+ * Abort reading file.+ */+FileReader.prototype.abort = function () {+ if (origFileReader && !this._localURL) {+ return this._realReader.abort();+ }+ this._result = null;++ if (this._readyState === FileReader.DONE || this._readyState === FileReader.EMPTY) {+ return;+ }++ this._readyState = FileReader.DONE;++ // If abort callback+ if (typeof this.onabort === 'function') {+ this.onabort(new ProgressEvent('abort', {target: this}));+ }+ // If load end callback+ if (typeof this.onloadend === 'function') {+ this.onloadend(new ProgressEvent('loadend', {target: this}));+ }+};++/**+ * Read text file.+ *+ * @param file {File} File object containing file properties+ * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)+ */+FileReader.prototype.readAsText = function (file, encoding) {+ if (initRead(this, file)) {+ return this._realReader.readAsText(file, encoding);+ }++ // Default encoding is UTF-8+ var enc = encoding || 'UTF-8';++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsText', enc, file.start, totalSize, function (r) {+ if (this._progress === 0) {+ this._result = '';+ }+ this._result += r;+ }.bind(this));+};++/**+ * Read file and return data as a base64 encoded data url.+ * A data url is of the form:+ * data:[<mediatype>][;base64],<data>+ *+ * @param file {File} File object containing file properties+ */+FileReader.prototype.readAsDataURL = function (file) {+ if (initRead(this, file)) {+ return this._realReader.readAsDataURL(file);+ }++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsDataURL', null, file.start, totalSize, function (r) {+ var commaIndex = r.indexOf(',');+ if (this._progress === 0) {+ this._result = r;+ } else {+ this._result += r.substring(commaIndex + 1);+ }+ }.bind(this));+};++/**+ * Read file and return data as a binary data.+ *+ * @param file {File} File object containing file properties+ */+FileReader.prototype.readAsBinaryString = function (file) {+ if (initRead(this, file)) {+ return this._realReader.readAsBinaryString(file);+ }++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsBinaryString', null, file.start, totalSize, function (r) {+ if (this._progress === 0) {+ this._result = '';+ }+ this._result += r;+ }.bind(this));+};++/**+ * Read file and return data as a binary data.+ *+ * @param file {File} File object containing file properties+ */+FileReader.prototype.readAsArrayBuffer = function (file) {+ if (initRead(this, file)) {+ return this._realReader.readAsArrayBuffer(file);+ }++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsArrayBuffer', null, file.start, totalSize, function (r) {+ var resultArray = (this._progress === 0 ? new Uint8Array(totalSize) : new Uint8Array(this._result));+ resultArray.set(new Uint8Array(r), this._progress);+ this._result = resultArray.buffer;+ }.bind(this));+};++module.exports = FileReader;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileSystem.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileSystem.jsnew file mode 100644index 000000000..ad9ea7859--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileSystem.js@@ -0,0 +1,58 @@+cordova.define("cordova-plugin-file.FileSystem", function(require, exports, module) {+/*+ *+ * 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 DirectoryEntry = require('./DirectoryEntry');++/**+ * An interface representing a file system+ *+ * @constructor+ * {DOMString} name the unique name of the file system (readonly)+ * {DirectoryEntry} root directory of the file system (readonly)+ */+var FileSystem = function (name, root) {+ this.name = name;+ if (root) {+ this.root = new DirectoryEntry(root.name, root.fullPath, this, root.nativeURL);+ } else {+ this.root = new DirectoryEntry(this.name, '/', this);+ }+};++FileSystem.prototype.__format__ = function (fullPath, nativeUrl) {+ return fullPath;+};++FileSystem.prototype.toJSON = function () {+ return '<FileSystem: ' + this.name + '>';+};++// Use instead of encodeURI() when encoding just the path part of a URI rather than an entire URI.+FileSystem.encodeURIPath = function (path) {+ // Because # is a valid filename character, it must be encoded to prevent part of the+ // path from being parsed as a URI fragment.+ return encodeURI(path).replace(/#/g, '%23');+};++module.exports = FileSystem;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileUploadOptions.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileUploadOptions.jsnew file mode 100644index 000000000..6acd09334--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileUploadOptions.js@@ -0,0 +1,44 @@+cordova.define("cordova-plugin-file.FileUploadOptions", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Options to customize the HTTP request used to upload files.+ * @constructor+ * @param fileKey {String} Name of file request parameter.+ * @param fileName {String} Filename to be used by the server. Defaults to image.jpg.+ * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.+ * @param params {Object} Object with key: value params to send to the server.+ * @param headers {Object} Keys are header names, values are header values. Multiple+ * headers of the same name are not supported.+ */+var FileUploadOptions = function (fileKey, fileName, mimeType, params, headers, httpMethod) {+ this.fileKey = fileKey || null;+ this.fileName = fileName || null;+ this.mimeType = mimeType || null;+ this.params = params || null;+ this.headers = headers || null;+ this.httpMethod = httpMethod || null;+};++module.exports = FileUploadOptions;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileUploadResult.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileUploadResult.jsnew file mode 100644index 000000000..e3c3a7431--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileUploadResult.js@@ -0,0 +1,33 @@+cordova.define("cordova-plugin-file.FileUploadResult", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * FileUploadResult+ * @constructor+ */+module.exports = function FileUploadResult (size, code, content) {+ this.bytesSent = size;+ this.responseCode = code;+ this.response = content;+};++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileWriter.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileWriter.jsnew file mode 100644index 000000000..c3e856219--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/FileWriter.js@@ -0,0 +1,328 @@+cordova.define("cordova-plugin-file.FileWriter", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var FileError = require('./FileError');+var FileReader = require('./FileReader');+var ProgressEvent = require('./ProgressEvent');++/**+ * This class writes to the mobile device file system.+ *+ * For Android:+ * The root directory is the root of the file system.+ * To write to the SD card, the file name is "sdcard/my_file.txt"+ *+ * @constructor+ * @param file {File} File object containing file properties+ * @param append if true write to the end of the file, otherwise overwrite the file+ */+var FileWriter = function (file) {+ this.fileName = '';+ this.length = 0;+ if (file) {+ this.localURL = file.localURL || file;+ this.length = file.size || 0;+ }+ // default is to write at the beginning of the file+ this.position = 0;++ this.readyState = 0; // EMPTY++ this.result = null;++ // Error+ this.error = null;++ // Event handlers+ this.onwritestart = null; // When writing starts+ this.onprogress = null; // While writing the file, and reporting partial file data+ this.onwrite = null; // When the write has successfully completed.+ this.onwriteend = null; // When the request has completed (either in success or failure).+ this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.+ this.onerror = null; // When the write has failed (see errors).+};++// States+FileWriter.INIT = 0;+FileWriter.WRITING = 1;+FileWriter.DONE = 2;++/**+ * Abort writing file.+ */+FileWriter.prototype.abort = function () {+ // check for invalid state+ if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ // set error+ this.error = new FileError(FileError.ABORT_ERR);++ this.readyState = FileWriter.DONE;++ // If abort callback+ if (typeof this.onabort === 'function') {+ this.onabort(new ProgressEvent('abort', {'target': this}));+ }++ // If write end callback+ if (typeof this.onwriteend === 'function') {+ this.onwriteend(new ProgressEvent('writeend', {'target': this}));+ }+};++/**+ * Writes data to the file+ *+ * @param data text or blob to be written+ * @param isPendingBlobReadResult {Boolean} true if the data is the pending blob read operation result+ */+FileWriter.prototype.write = function (data, isPendingBlobReadResult) {++ var that = this;+ var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined');+ /* eslint-disable no-undef */+ var isProxySupportBlobNatively = (cordova.platformId === 'windows8' || cordova.platformId === 'windows');+ var isBinary;++ // Check to see if the incoming data is a blob+ if (data instanceof File || (!isProxySupportBlobNatively && supportsBinary && data instanceof Blob)) {+ var fileReader = new FileReader();+ /* eslint-enable no-undef */+ fileReader.onload = function () {+ // Call this method again, with the arraybuffer as argument+ FileWriter.prototype.write.call(that, this.result, true /* isPendingBlobReadResult */);+ };+ fileReader.onerror = function () {+ // DONE state+ that.readyState = FileWriter.DONE;++ // Save error+ that.error = this.error;++ // If onerror callback+ if (typeof that.onerror === 'function') {+ that.onerror(new ProgressEvent('error', {'target': that}));+ }++ // If onwriteend callback+ if (typeof that.onwriteend === 'function') {+ that.onwriteend(new ProgressEvent('writeend', {'target': that}));+ }+ };++ // WRITING state+ this.readyState = FileWriter.WRITING;++ if (supportsBinary) {+ fileReader.readAsArrayBuffer(data);+ } else {+ fileReader.readAsText(data);+ }+ return;+ }++ // Mark data type for safer transport over the binary bridge+ isBinary = supportsBinary && (data instanceof ArrayBuffer);+ if (isBinary && cordova.platformId === 'windowsphone') { // eslint-disable-line no-undef+ // create a plain array, using the keys from the Uint8Array view so that we can serialize it+ data = Array.apply(null, new Uint8Array(data));+ }++ // Throw an exception if we are already writing a file+ if (this.readyState === FileWriter.WRITING && !isPendingBlobReadResult) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ // WRITING state+ this.readyState = FileWriter.WRITING;++ var me = this;++ // If onwritestart callback+ if (typeof me.onwritestart === 'function') {+ me.onwritestart(new ProgressEvent('writestart', {'target': me}));+ }++ // Write file+ exec(+ // Success callback+ function (r) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // position always increases by bytes written because file would be extended+ me.position += r;+ // The length of the file is now where we are done writing.++ me.length = me.position;++ // DONE state+ me.readyState = FileWriter.DONE;++ // If onwrite callback+ if (typeof me.onwrite === 'function') {+ me.onwrite(new ProgressEvent('write', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ },+ // Error callback+ function (e) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // DONE state+ me.readyState = FileWriter.DONE;++ // Save error+ me.error = new FileError(e);++ // If onerror callback+ if (typeof me.onerror === 'function') {+ me.onerror(new ProgressEvent('error', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ }, 'File', 'write', [this.localURL, data, this.position, isBinary]);+};++/**+ * Moves the file pointer to the location specified.+ *+ * If the offset is a negative number the position of the file+ * pointer is rewound. If the offset is greater than the file+ * size the position is set to the end of the file.+ *+ * @param offset is the location to move the file pointer to.+ */+FileWriter.prototype.seek = function (offset) {+ // Throw an exception if we are already writing a file+ if (this.readyState === FileWriter.WRITING) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ if (!offset && offset !== 0) {+ return;+ }++ // See back from end of file.+ if (offset < 0) {+ this.position = Math.max(offset + this.length, 0);+ // Offset is bigger than file size so set position+ // to the end of the file.+ } else if (offset > this.length) {+ this.position = this.length;+ // Offset is between 0 and file size so set the position+ // to start writing.+ } else {+ this.position = offset;+ }+};++/**+ * Truncates the file to the size specified.+ *+ * @param size to chop the file at.+ */+FileWriter.prototype.truncate = function (size) {+ // Throw an exception if we are already writing a file+ if (this.readyState === FileWriter.WRITING) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ // WRITING state+ this.readyState = FileWriter.WRITING;++ var me = this;++ // If onwritestart callback+ if (typeof me.onwritestart === 'function') {+ me.onwritestart(new ProgressEvent('writestart', {'target': this}));+ }++ // Write file+ exec(+ // Success callback+ function (r) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // DONE state+ me.readyState = FileWriter.DONE;++ // Update the length of the file+ me.length = r;+ me.position = Math.min(me.position, r);++ // If onwrite callback+ if (typeof me.onwrite === 'function') {+ me.onwrite(new ProgressEvent('write', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ },+ // Error callback+ function (e) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // DONE state+ me.readyState = FileWriter.DONE;++ // Save error+ me.error = new FileError(e);++ // If onerror callback+ if (typeof me.onerror === 'function') {+ me.onerror(new ProgressEvent('error', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ }, 'File', 'truncate', [this.localURL, size]);+};++module.exports = FileWriter;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Flags.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Flags.jsnew file mode 100644index 000000000..cdb12bb73--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Flags.js@@ -0,0 +1,39 @@+cordova.define("cordova-plugin-file.Flags", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Supplies arguments to methods that lookup or create files and directories.+ *+ * @param create+ * {boolean} file or directory if it doesn't exist+ * @param exclusive+ * {boolean} used with create; if true the command will fail if+ * target path exists+ */+function Flags (create, exclusive) {+ this.create = create || false;+ this.exclusive = exclusive || false;+}++module.exports = Flags;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/LocalFileSystem.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/LocalFileSystem.jsnew file mode 100644index 000000000..4ce684812--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/LocalFileSystem.js@@ -0,0 +1,26 @@+cordova.define("cordova-plugin-file.LocalFileSystem", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++exports.TEMPORARY = 0;+exports.PERSISTENT = 1;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Metadata.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Metadata.jsnew file mode 100644index 000000000..22366e167--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/Metadata.js@@ -0,0 +1,43 @@+cordova.define("cordova-plugin-file.Metadata", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Information about the state of the file or directory+ *+ * {Date} modificationTime (readonly)+ */+var Metadata = function (metadata) {+ if (typeof metadata === 'object') {+ this.modificationTime = new Date(metadata.modificationTime);+ this.size = metadata.size || 0;+ } else if (typeof metadata === 'undefined') {+ this.modificationTime = null;+ this.size = 0;+ } else {+ /* Backwards compatiblity with platforms that only return a timestamp */+ this.modificationTime = new Date(metadata);+ }+};++module.exports = Metadata;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/ProgressEvent.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/ProgressEvent.jsnew file mode 100644index 000000000..cbecdb12b--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/ProgressEvent.js@@ -0,0 +1,70 @@+cordova.define("cordova-plugin-file.ProgressEvent", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++// If ProgressEvent exists in global context, use it already, otherwise use our own polyfill+// Feature test: See if we can instantiate a native ProgressEvent;+// if so, use that approach,+// otherwise fill-in with our own implementation.+//+// NOTE: right now we always fill in with our own. Down the road would be nice if we can use whatever is native in the webview.+var ProgressEvent = (function () {+ /*+ var createEvent = function(data) {+ var event = document.createEvent('Events');+ event.initEvent('ProgressEvent', false, false);+ if (data) {+ for (var i in data) {+ if (data.hasOwnProperty(i)) {+ event[i] = data[i];+ }+ }+ if (data.target) {+ // TODO: cannot call <some_custom_object>.dispatchEvent+ // need to first figure out how to implement EventTarget+ }+ }+ return event;+ };+ try {+ var ev = createEvent({type:"abort",target:document});+ return function ProgressEvent(type, data) {+ data.type = type;+ return createEvent(data);+ };+ } catch(e){+ */+ return function ProgressEvent (type, dict) {+ this.type = type;+ this.bubbles = false;+ this.cancelBubble = false;+ this.cancelable = false;+ this.lengthComputable = false;+ this.loaded = dict && dict.loaded ? dict.loaded : 0;+ this.total = dict && dict.total ? dict.total : 0;+ this.target = dict && dict.target ? dict.target : null;+ };+ // }+})();++module.exports = ProgressEvent;++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/browser/isChrome.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/browser/isChrome.jsnew file mode 100644index 000000000..90450d862--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/browser/isChrome.js@@ -0,0 +1,29 @@+cordova.define("cordova-plugin-file.isChrome", function(require, exports, module) {+/*+ *+ * 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.+ *+ */++module.exports = function () {+ // window.webkitRequestFileSystem and window.webkitResolveLocalFileSystemURL are available only in Chrome and+ // possibly a good flag to indicate that we're running in Chrome+ return window.webkitRequestFileSystem && window.webkitResolveLocalFileSystemURL;+};++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystemPaths.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystemPaths.jsnew file mode 100644index 000000000..4bfc0f629--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystemPaths.js@@ -0,0 +1,65 @@+cordova.define("cordova-plugin-file.fileSystemPaths", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var channel = require('cordova/channel');++exports.file = {+ // Read-only directory where the application is installed.+ applicationDirectory: null,+ // Root of app's private writable storage+ applicationStorageDirectory: null,+ // Where to put app-specific data files.+ dataDirectory: null,+ // Cached files that should survive app restarts.+ // Apps should not rely on the OS to delete files in here.+ cacheDirectory: null,+ // Android: the application space on external storage.+ externalApplicationStorageDirectory: null,+ // Android: Where to put app-specific data files on external storage.+ externalDataDirectory: null,+ // Android: the application cache on external storage.+ externalCacheDirectory: null,+ // Android: the external storage (SD card) root.+ externalRootDirectory: null,+ // iOS: Temp directory that the OS can clear at will.+ tempDirectory: null,+ // iOS: Holds app-specific files that should be synced (e.g. to iCloud).+ syncedDataDirectory: null,+ // iOS: Files private to the app, but that are meaningful to other applications (e.g. Office files)+ documentsDirectory: null,+ // BlackBerry10: Files globally available to all apps+ sharedDirectory: null+};++channel.waitForInitialization('onFileSystemPathsReady');+channel.onCordovaReady.subscribe(function () {+ function after (paths) {+ for (var k in paths) {+ exports.file[k] = paths[k];+ }+ channel.initializationComplete('onFileSystemPathsReady');+ }+ exec(after, null, 'File', 'requestAllPaths', []);+});++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.jsnew file mode 100644index 000000000..6e02953e8--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js@@ -0,0 +1,49 @@+cordova.define("cordova-plugin-file.fileSystems-roots", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++// Map of fsName -> FileSystem.+var fsMap = null;+var FileSystem = require('./FileSystem');+var exec = require('cordova/exec');++// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.+require('./fileSystems').getFs = function (name, callback) {+ function success (response) {+ fsMap = {};+ for (var i = 0; i < response.length; ++i) {+ var fsRoot = response[i];+ if (fsRoot) {+ var fs = new FileSystem(fsRoot.filesystemName, fsRoot);+ fsMap[fs.name] = fs;+ }+ }+ callback(fsMap[name]);+ }++ if (fsMap) {+ callback(fsMap[name]);+ } else {+ exec(success, null, 'File', 'requestAllFileSystems', []);+ }+};++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystems.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystems.jsnew file mode 100644index 000000000..e61ceafc8--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/fileSystems.js@@ -0,0 +1,28 @@+cordova.define("cordova-plugin-file.fileSystems", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.+module.exports.getFs = function (name, callback) {+ callback(null);+};++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/ios/FileSystem.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/ios/FileSystem.jsnew file mode 100644index 000000000..551b51545--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/ios/FileSystem.js@@ -0,0 +1,32 @@+cordova.define("cordova-plugin-file.iosFileSystem", function(require, exports, module) {+/*+ *+ * 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.+ *+*/+/* eslint no-undef : 0 */+FILESYSTEM_PROTOCOL = 'cdvfile';++module.exports = {+ __format__: function (fullPath) {+ var path = ('/' + this.name + (fullPath[0] === '/' ? '' : '/') + FileSystem.encodeURIPath(fullPath)).replace('//', '/');+ return FILESYSTEM_PROTOCOL + '://localhost' + path;+ }+};++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/requestFileSystem.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/requestFileSystem.jsnew file mode 100644index 000000000..7f652193c--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/requestFileSystem.js@@ -0,0 +1,84 @@+cordova.define("cordova-plugin-file.requestFileSystem", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++(function () {+ // For browser platform: not all browsers use this file.+ function checkBrowser () {+ if (cordova.platformId === 'browser' && require('./isChrome')()) { // eslint-disable-line no-undef+ module.exports = window.requestFileSystem || window.webkitRequestFileSystem;+ return true;+ }+ return false;+ }+ if (checkBrowser()) {+ return;+ }++ var argscheck = require('cordova/argscheck');+ var FileError = require('./FileError');+ var FileSystem = require('./FileSystem');+ var exec = require('cordova/exec');+ var fileSystems = require('./fileSystems');++ /**+ * Request a file system in which to store application data.+ * @param type local file system type+ * @param size indicates how much storage space, in bytes, the application expects to need+ * @param successCallback invoked with a FileSystem object+ * @param errorCallback invoked if error occurs retrieving file system+ */+ var requestFileSystem = function (type, size, successCallback, errorCallback) {+ argscheck.checkArgs('nnFF', 'requestFileSystem', arguments);+ var fail = function (code) {+ if (errorCallback) {+ errorCallback(new FileError(code));+ }+ };++ if (type < 0) {+ fail(FileError.SYNTAX_ERR);+ } else {+ // if successful, return a FileSystem object+ var success = function (file_system) {+ if (file_system) {+ if (successCallback) {+ fileSystems.getFs(file_system.name, function (fs) {+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)+ if (!fs) {+ fs = new FileSystem(file_system.name, file_system.root);+ }+ successCallback(fs);+ });+ }+ } else {+ // no FileSystem object returned+ fail(FileError.NOT_FOUND_ERR);+ }+ };+ exec(success, fail, 'File', 'requestFileSystem', [type, size]);+ }+ };++ module.exports = requestFileSystem;+})();++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.jsnew file mode 100644index 000000000..73715bc0e--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js@@ -0,0 +1,94 @@+cordova.define("cordova-plugin-file.resolveLocalFileSystemURI", function(require, exports, module) {+/*+ *+ * 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.+ *+*/+(function () {+ // For browser platform: not all browsers use overrided `resolveLocalFileSystemURL`.+ function checkBrowser () {+ if (cordova.platformId === 'browser' && require('./isChrome')()) { // eslint-disable-line no-undef+ module.exports.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;+ return true;+ }+ return false;+ }+ if (checkBrowser()) {+ return;+ }++ var argscheck = require('cordova/argscheck');+ var DirectoryEntry = require('./DirectoryEntry');+ var FileEntry = require('./FileEntry');+ var FileError = require('./FileError');+ var exec = require('cordova/exec');+ var fileSystems = require('./fileSystems');++ /**+ * Look up file system Entry referred to by local URI.+ * @param {DOMString} uri URI referring to a local file or directory+ * @param successCallback invoked with Entry object corresponding to URI+ * @param errorCallback invoked if error occurs retrieving file system entry+ */+ module.exports.resolveLocalFileSystemURL = module.exports.resolveLocalFileSystemURL || function (uri, successCallback, errorCallback) {+ argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments);+ // error callback+ var fail = function (error) {+ if (errorCallback) {+ errorCallback(new FileError(error));+ }+ };+ // sanity check for 'not:valid:filename' or '/not:valid:filename'+ // file.spec.12 window.resolveLocalFileSystemURI should error (ENCODING_ERR) when resolving invalid URI with leading /.+ if (!uri || uri.split(':').length > 2) {+ setTimeout(function () {+ fail(FileError.ENCODING_ERR);+ }, 0);+ return;+ }+ // if successful, return either a file or directory entry+ var success = function (entry) {+ if (entry) {+ if (successCallback) {+ // create appropriate Entry object+ var fsName = entry.filesystemName || (entry.filesystem && entry.filesystem.name) || (entry.filesystem === window.PERSISTENT ? 'persistent' : 'temporary'); // eslint-disable-line no-undef+ fileSystems.getFs(fsName, function (fs) {+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)+ if (!fs) {+ fs = new FileSystem(fsName, {name: '', fullPath: '/'}); // eslint-disable-line no-undef+ }+ var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL);+ successCallback(result);+ });+ }+ } else {+ // no Entry object returned+ fail(FileError.NOT_FOUND_ERR);+ }+ };++ exec(success, fail, 'File', 'resolveLocalFileSystemURI', [uri]);+ };++ module.exports.resolveLocalFileSystemURI = function () {+ console.log('resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.');+ module.exports.resolveLocalFileSystemURL.apply(this, arguments);+ };+})();++});diff --git a/cordova/platforms/ios/pods-debug.xcconfig b/cordova/platforms/ios/pods-debug.xcconfignew file mode 100644index 000000000..12c706516--- /dev/null+++ b/cordova/platforms/ios/pods-debug.xcconfig@@ -0,0 +1,20 @@+//+// 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.+//++// DO NOT MODIFY -- auto-generated by Apache Cordovadiff --git a/cordova/platforms/ios/pods-release.xcconfig b/cordova/platforms/ios/pods-release.xcconfignew file mode 100644index 000000000..12e2b13f9--- /dev/null+++ b/cordova/platforms/ios/pods-release.xcconfig@@ -0,0 +1,20 @@+//+// 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.+//++// DO NOT MODIFY -- auto-generated by Apache Cordova\ No newline at end of filediff --git a/cordova/platforms/ios/pods.json b/cordova/platforms/ios/pods.jsonnew file mode 100644index 000000000..ae83877b4--- /dev/null+++ b/cordova/platforms/ios/pods.json@@ -0,0 +1,5 @@+{+ "declarations": {},+ "sources": {},+ "libraries": {}+}\ No newline at end of filediff --git a/cordova/platforms/ios/www/LICENSE.txt b/cordova/platforms/ios/www/LICENSE.txtnew file mode 100644index 000000000..dba13ed2d--- /dev/null+++ b/cordova/platforms/ios/www/LICENSE.txt@@ -0,0 +1,661 @@+ GNU AFFERO GENERAL PUBLIC LICENSE+ Version 3, 19 November 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU Affero General Public License is a free, copyleft license for+software and other kinds of works, specifically designed to ensure+cooperation with the community in the case of network server software.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+our General Public Licenses are intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ Developers that use our General Public Licenses protect your rights+with two steps: (1) assert copyright on the software, and (2) offer+you this License which gives you legal permission to copy, distribute+and/or modify the software.++ A secondary benefit of defending all users' freedom is that+improvements made in alternate versions of the program, if they+receive widespread use, become available for other developers to+incorporate. Many developers of free software are heartened and+encouraged by the resulting cooperation. However, in the case of+software used on network servers, this result may fail to come about.+The GNU General Public License permits making a modified version and+letting the public access it on a server without ever releasing its+source code to the public.++ The GNU Affero General Public License is designed specifically to+ensure that, in such cases, the modified source code becomes available+to the community. It requires the operator of a network server to+provide the source code of the modified version running there to the+users of that server. Therefore, public use of a modified version, on+a publicly accessible server, gives the public access to the source+code of the modified version.++ An older license, called the Affero General Public License and+published by Affero, was designed to accomplish similar goals. This is+a different license, not a version of the Affero GPL, but Affero has+released a new version of the Affero GPL which permits relicensing under+this license.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU Affero General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Remote Network Interaction; Use with the GNU General Public License.++ Notwithstanding any other provision of this License, if you modify the+Program, your modified version must prominently offer all users+interacting with it remotely through a computer network (if your version+supports such interaction) an opportunity to receive the Corresponding+Source of your version by providing access to the Corresponding Source+from a network server at no charge, through some standard or customary+means of facilitating copying of software. This Corresponding Source+shall include the Corresponding Source for any work covered by version 3+of the GNU General Public License that is incorporated pursuant to the+following paragraph.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the work with which it is combined will remain governed by version+3 of the GNU General Public License.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU Affero General Public License from time to time. Such new versions+will be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU Affero General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU Affero General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU Affero General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU Affero General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ along with this program. If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If your software can interact with users remotely through a computer+network, you should also make sure that it provides a way for users to+get its source. For example, if your program is a web application, its+interface could display a "Source" link that leads users to an archive+of the code. There are many ways you could offer source, and different+solutions will be better for different programs; see section 13 for the+specific requirements.++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU AGPL, see+<http://www.gnu.org/licenses/>.diff --git a/cordova/platforms/ios/www/cordova-js-src/.eslintrc.yml b/cordova/platforms/ios/www/cordova-js-src/.eslintrc.ymlnew file mode 100644index 000000000..e3d49d8a0--- /dev/null+++ b/cordova/platforms/ios/www/cordova-js-src/.eslintrc.yml@@ -0,0 +1,4 @@+env:+ node: false+ commonjs: true+ browser: truediff --git a/cordova/platforms/ios/www/cordova-js-src/exec.js b/cordova/platforms/ios/www/cordova-js-src/exec.jsnew file mode 100644index 000000000..e7f6ce1c6--- /dev/null+++ b/cordova/platforms/ios/www/cordova-js-src/exec.js@@ -0,0 +1,262 @@+/*+ *+ * 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.+ *+*/++/* global require, module, atob, document */++/**+ * Creates a gap bridge iframe used to notify the native code about queued+ * commands.+ */+var cordova = require('cordova');+var utils = require('cordova/utils');+var base64 = require('cordova/base64');+var execIframe;+var commandQueue = []; // Contains pending JS->Native messages.+var isInContextOfEvalJs = 0;+var failSafeTimerId = 0;++function massageArgsJsToNative (args) {+ if (!args || utils.typeName(args) !== 'Array') {+ return args;+ }+ var ret = [];+ args.forEach(function (arg, i) {+ if (utils.typeName(arg) === 'ArrayBuffer') {+ ret.push({+ 'CDVType': 'ArrayBuffer',+ 'data': base64.fromArrayBuffer(arg)+ });+ } else {+ ret.push(arg);+ }+ });+ return ret;+}++function massageMessageNativeToJs (message) {+ if (message.CDVType === 'ArrayBuffer') {+ var stringToArrayBuffer = function (str) {+ var ret = new Uint8Array(str.length);+ for (var i = 0; i < str.length; i++) {+ ret[i] = str.charCodeAt(i);+ }+ return ret.buffer;+ };+ var base64ToArrayBuffer = function (b64) {+ return stringToArrayBuffer(atob(b64));+ };+ message = base64ToArrayBuffer(message.data);+ }+ return message;+}++function convertMessageToArgsNativeToJs (message) {+ var args = [];+ if (!message || !message.hasOwnProperty('CDVType')) {+ args.push(message);+ } else if (message.CDVType === 'MultiPart') {+ message.messages.forEach(function (e) {+ args.push(massageMessageNativeToJs(e));+ });+ } else {+ args.push(massageMessageNativeToJs(message));+ }+ return args;+}++function iOSExec () {++ var successCallback, failCallback, service, action, actionArgs;+ var callbackId = null;+ if (typeof arguments[0] !== 'string') {+ // FORMAT ONE+ successCallback = arguments[0];+ failCallback = arguments[1];+ service = arguments[2];+ action = arguments[3];+ actionArgs = arguments[4];++ // Since we need to maintain backwards compatibility, we have to pass+ // an invalid callbackId even if no callback was provided since plugins+ // will be expecting it. The Cordova.exec() implementation allocates+ // an invalid callbackId and passes it even if no callbacks were given.+ callbackId = 'INVALID';+ } else {+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' ++ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'+ );+ }++ // If actionArgs is not provided, default to an empty array+ actionArgs = actionArgs || [];++ // Register the callbacks and add the callbackId to the positional+ // arguments if given.+ if (successCallback || failCallback) {+ callbackId = service + cordova.callbackId++;+ cordova.callbacks[callbackId] =+ { success: successCallback, fail: failCallback };+ }++ actionArgs = massageArgsJsToNative(actionArgs);++ var command = [callbackId, service, action, actionArgs];++ // Stringify and queue the command. We stringify to command now to+ // effectively clone the command arguments in case they are mutated before+ // the command is executed.+ commandQueue.push(JSON.stringify(command));++ // If we're in the context of a stringByEvaluatingJavaScriptFromString call,+ // then the queue will be flushed when it returns; no need for a poke.+ // Also, if there is already a command in the queue, then we've already+ // poked the native side, so there is no reason to do so again.+ if (!isInContextOfEvalJs && commandQueue.length === 1) {+ pokeNative();+ }+}++// CB-10530+function proxyChanged () {+ var cexec = cordovaExec();++ return (execProxy !== cexec && // proxy objects are different+ iOSExec !== cexec // proxy object is not the current iOSExec+ );+}++// CB-10106+function handleBridgeChange () {+ if (proxyChanged()) {+ var commandString = commandQueue.shift();+ while (commandString) {+ var command = JSON.parse(commandString);+ var callbackId = command[0];+ var service = command[1];+ var action = command[2];+ var actionArgs = command[3];+ var callbacks = cordova.callbacks[callbackId] || {};++ execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);++ commandString = commandQueue.shift();+ }+ return true;+ }++ return false;+}++function pokeNative () {+ // CB-5488 - Don't attempt to create iframe before document.body is available.+ if (!document.body) {+ setTimeout(pokeNative);+ return;+ }++ // Check if they've removed it from the DOM, and put it back if so.+ if (execIframe && execIframe.contentWindow) {+ execIframe.contentWindow.location = 'gap://ready';+ } else {+ execIframe = document.createElement('iframe');+ execIframe.style.display = 'none';+ execIframe.src = 'gap://ready';+ document.body.appendChild(execIframe);+ }+ // Use a timer to protect against iframe being unloaded during the poke (CB-7735).+ // This makes the bridge ~ 7% slower, but works around the poke getting lost+ // when the iframe is removed from the DOM.+ // An onunload listener could be used in the case where the iframe has just been+ // created, but since unload events fire only once, it doesn't work in the normal+ // case of iframe reuse (where unload will have already fired due to the attempted+ // navigation of the page).+ failSafeTimerId = setTimeout(function () {+ if (commandQueue.length) {+ // CB-10106 - flush the queue on bridge change+ if (!handleBridgeChange()) {+ pokeNative();+ }+ }+ }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).+}++iOSExec.nativeFetchMessages = function () {+ // Stop listing for window detatch once native side confirms poke.+ if (failSafeTimerId) {+ clearTimeout(failSafeTimerId);+ failSafeTimerId = 0;+ }+ // Each entry in commandQueue is a JSON string already.+ if (!commandQueue.length) {+ return '';+ }+ var json = '[' + commandQueue.join(',') + ']';+ commandQueue.length = 0;+ return json;+};++iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {+ return iOSExec.nativeEvalAndFetch(function () {+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ function nc2 () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback);+ }+ setTimeout(nc2, 0);+ });+};++iOSExec.nativeEvalAndFetch = function (func) {+ // This shouldn't be nested, but better to be safe.+ isInContextOfEvalJs++;+ try {+ func();+ return iOSExec.nativeFetchMessages();+ } finally {+ isInContextOfEvalJs--;+ }+};++// Proxy the exec for bridge changes. See CB-10106++function cordovaExec () {+ var cexec = require('cordova/exec');+ var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function');+ return (cexec_valid && execProxy !== cexec) ? cexec : iOSExec;+}++function execProxy () {+ cordovaExec().apply(null, arguments);+}++execProxy.nativeFetchMessages = function () {+ return cordovaExec().nativeFetchMessages.apply(null, arguments);+};++execProxy.nativeEvalAndFetch = function () {+ return cordovaExec().nativeEvalAndFetch.apply(null, arguments);+};++execProxy.nativeCallback = function () {+ return cordovaExec().nativeCallback.apply(null, arguments);+};++module.exports = execProxy;diff --git a/cordova/platforms/ios/www/cordova-js-src/platform.js b/cordova/platforms/ios/www/cordova-js-src/platform.jsnew file mode 100644index 000000000..2345fa5b7--- /dev/null+++ b/cordova/platforms/ios/www/cordova-js-src/platform.js@@ -0,0 +1,31 @@+/*+ *+ * 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.+ *+*/++module.exports = {+ id: 'ios',+ bootstrap: function () {+ // Attach the console polyfill that is iOS-only to window.console+ // see the file under plugin/ios/console.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');++ require('cordova/channel').onNativeReady.fire();+ }+};diff --git a/cordova/platforms/ios/www/cordova-js-src/plugin/ios/console.js b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/console.jsnew file mode 100644index 000000000..0a4820ede--- /dev/null+++ b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/console.js@@ -0,0 +1,186 @@+/*+ *+ * 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 logger = require('cordova/plugin/ios/logger');++// ------------------------------------------------------------------------------+// object that we're exporting+// ------------------------------------------------------------------------------+var console = module.exports;++// ------------------------------------------------------------------------------+// copy of the original console object+// ------------------------------------------------------------------------------+var WinConsole = window.console;++// ------------------------------------------------------------------------------+// whether to use the logger+// ------------------------------------------------------------------------------+var UseLogger = false;++// ------------------------------------------------------------------------------+// Timers+// ------------------------------------------------------------------------------+var Timers = {};++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+function noop () {}++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+console.useLogger = function (value) {+ if (arguments.length) UseLogger = !!value;++ if (UseLogger) {+ if (logger.useConsole()) {+ throw new Error('console and logger are too intertwingly');+ }+ }++ return UseLogger;+};++// ------------------------------------------------------------------------------+console.log = function () {+ if (logger.useConsole()) return;+ logger.log.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.error = function () {+ if (logger.useConsole()) return;+ logger.error.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.warn = function () {+ if (logger.useConsole()) return;+ logger.warn.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.info = function () {+ if (logger.useConsole()) return;+ logger.info.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.debug = function () {+ if (logger.useConsole()) return;+ logger.debug.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.assert = function (expression) {+ if (expression) return;++ var message = logger.format.apply(logger.format, [].slice.call(arguments, 1));+ console.log('ASSERT: ' + message);+};++// ------------------------------------------------------------------------------+console.clear = function () {};++// ------------------------------------------------------------------------------+console.dir = function (object) {+ console.log('%o', object);+};++// ------------------------------------------------------------------------------+console.dirxml = function (node) {+ console.log(node.innerHTML);+};++// ------------------------------------------------------------------------------+console.trace = noop;++// ------------------------------------------------------------------------------+console.group = console.log;++// ------------------------------------------------------------------------------+console.groupCollapsed = console.log;++// ------------------------------------------------------------------------------+console.groupEnd = noop;++// ------------------------------------------------------------------------------+console.time = function (name) {+ Timers[name] = new Date().valueOf();+};++// ------------------------------------------------------------------------------+console.timeEnd = function (name) {+ var timeStart = Timers[name];+ if (!timeStart) {+ console.warn('unknown timer: ' + name);+ return;+ }++ var timeElapsed = new Date().valueOf() - timeStart;+ console.log(name + ': ' + timeElapsed + 'ms');+};++// ------------------------------------------------------------------------------+console.timeStamp = noop;++// ------------------------------------------------------------------------------+console.profile = noop;++// ------------------------------------------------------------------------------+console.profileEnd = noop;++// ------------------------------------------------------------------------------+console.count = noop;++// ------------------------------------------------------------------------------+console.exception = console.log;++// ------------------------------------------------------------------------------+console.table = function (data, columns) {+ console.log('%o', data);+};++// ------------------------------------------------------------------------------+// return a new function that calls both functions passed as args+// ------------------------------------------------------------------------------+function wrappedOrigCall (orgFunc, newFunc) {+ return function () {+ var args = [].slice.call(arguments);+ try { orgFunc.apply(WinConsole, args); } catch (e) {}+ try { newFunc.apply(console, args); } catch (e) {}+ };+}++// ------------------------------------------------------------------------------+// For every function that exists in the original console object, that+// also exists in the new console object, wrap the new console method+// with one that calls both+// ------------------------------------------------------------------------------+for (var key in console) {+ if (typeof WinConsole[key] === 'function') {+ console[key] = wrappedOrigCall(WinConsole[key], console[key]);+ }+}diff --git a/cordova/platforms/ios/www/cordova-js-src/plugin/ios/logger.js b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/logger.jsnew file mode 100644index 000000000..7dc82e36a--- /dev/null+++ b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/logger.js@@ -0,0 +1,349 @@+/*+ *+ * 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.+ *+*/++// ------------------------------------------------------------------------------+// The logger module exports the following properties/functions:+//+// LOG - constant for the level LOG+// ERROR - constant for the level ERROR+// WARN - constant for the level WARN+// INFO - constant for the level INFO+// DEBUG - constant for the level DEBUG+// logLevel() - returns current log level+// logLevel(value) - sets and returns a new log level+// useConsole() - returns whether logger is using console+// useConsole(value) - sets and returns whether logger is using console+// log(message,...) - logs a message at level LOG+// error(message,...) - logs a message at level ERROR+// warn(message,...) - logs a message at level WARN+// info(message,...) - logs a message at level INFO+// debug(message,...) - logs a message at level DEBUG+// logLevel(level,message,...) - logs a message specified level+//+// ------------------------------------------------------------------------------++var logger = exports;++var exec = require('cordova/exec');++var UseConsole = false;+var UseLogger = true;+var Queued = [];+var DeviceReady = false;+var CurrentLevel;++var originalConsole = console;++/**+ * Logging levels+ */++var Levels = [+ 'LOG',+ 'ERROR',+ 'WARN',+ 'INFO',+ 'DEBUG'+];++/*+ * add the logging levels to the logger object and+ * to a separate levelsMap object for testing+ */++var LevelsMap = {};+for (var i = 0; i < Levels.length; i++) {+ var level = Levels[i];+ LevelsMap[level] = i;+ logger[level] = level;+}++CurrentLevel = LevelsMap.WARN;++/**+ * Getter/Setter for the logging level+ *+ * Returns the current logging level.+ *+ * When a value is passed, sets the logging level to that value.+ * The values should be one of the following constants:+ * logger.LOG+ * logger.ERROR+ * logger.WARN+ * logger.INFO+ * logger.DEBUG+ *+ * The value used determines which messages get printed. The logging+ * values above are in order, and only messages logged at the logging+ * level or above will actually be displayed to the user. E.g., the+ * default level is WARN, so only messages logged with LOG, ERROR, or+ * WARN will be displayed; INFO and DEBUG messages will be ignored.+ */+logger.level = function (value) {+ if (arguments.length) {+ if (LevelsMap[value] === null) {+ throw new Error('invalid logging level: ' + value);+ }+ CurrentLevel = LevelsMap[value];+ }++ return Levels[CurrentLevel];+};++/**+ * Getter/Setter for the useConsole functionality+ *+ * When useConsole is true, the logger will log via the+ * browser 'console' object.+ */+logger.useConsole = function (value) {+ if (arguments.length) UseConsole = !!value;++ if (UseConsole) {+ if (typeof console === 'undefined') {+ throw new Error('global console object is not defined');+ }++ if (typeof console.log !== 'function') {+ throw new Error('global console object does not have a log function');+ }++ if (typeof console.useLogger === 'function') {+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }+ }+ }++ return UseConsole;+};++/**+ * Getter/Setter for the useLogger functionality+ *+ * When useLogger is true, the logger will log via the+ * native Logger plugin.+ */+logger.useLogger = function (value) {+ // Enforce boolean+ if (arguments.length) UseLogger = !!value;+ return UseLogger;+};++/**+ * Logs a message at the LOG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.log = function (message) { logWithArgs('LOG', arguments); };++/**+ * Logs a message at the ERROR level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.error = function (message) { logWithArgs('ERROR', arguments); };++/**+ * Logs a message at the WARN level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.warn = function (message) { logWithArgs('WARN', arguments); };++/**+ * Logs a message at the INFO level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.info = function (message) { logWithArgs('INFO', arguments); };++/**+ * Logs a message at the DEBUG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.debug = function (message) { logWithArgs('DEBUG', arguments); };++// log at the specified level with args+function logWithArgs (level, args) {+ args = [level].concat([].slice.call(args));+ logger.logLevel.apply(logger, args);+}++// return the correct formatString for an object+function formatStringForMessage (message) {+ return (typeof message === 'string') ? '' : '%o';+}++/**+ * Logs a message at the specified level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.logLevel = function (level /* , ... */) {+ // format the message with the parameters+ var formatArgs = [].slice.call(arguments, 1);+ var fmtString = formatStringForMessage(formatArgs[0]);+ if (fmtString.length > 0) {+ formatArgs.unshift(fmtString); // add formatString+ }++ var message = logger.format.apply(logger.format, formatArgs);++ if (LevelsMap[level] === null) {+ throw new Error('invalid logging level: ' + level);+ }++ if (LevelsMap[level] > CurrentLevel) return;++ // queue the message if not yet at deviceready+ if (!DeviceReady && !UseConsole) {+ Queued.push([level, message]);+ return;+ }++ // Log using the native logger if that is enabled+ if (UseLogger) {+ exec(null, null, 'Console', 'logLevel', [level, message]);+ }++ // Log using the console if that is enabled+ if (UseConsole) {+ // make sure console is not using logger+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }++ // log to the console+ switch (level) {+ case logger.LOG: originalConsole.log(message); break;+ case logger.ERROR: originalConsole.log('ERROR: ' + message); break;+ case logger.WARN: originalConsole.log('WARN: ' + message); break;+ case logger.INFO: originalConsole.log('INFO: ' + message); break;+ case logger.DEBUG: originalConsole.log('DEBUG: ' + message); break;+ }+ }+};++/**+ * Formats a string and arguments following it ala console.log()+ *+ * Any remaining arguments will be appended to the formatted string.+ *+ * for rationale, see FireBug's Console API:+ * http://getfirebug.com/wiki/index.php/Console_API+ */+logger.format = function (formatString, args) {+ return __format(arguments[0], [].slice.call(arguments, 1)).join(' ');+};++// ------------------------------------------------------------------------------+/**+ * Formats a string and arguments following it ala vsprintf()+ *+ * format chars:+ * %j - format arg as JSON+ * %o - format arg as JSON+ * %c - format arg as ''+ * %% - replace with '%'+ * any other char following % will format it's+ * arg via toString().+ *+ * Returns an array containing the formatted string and any remaining+ * arguments.+ */+function __format (formatString, args) {+ if (formatString === null || formatString === undefined) return [''];+ if (arguments.length === 1) return [formatString.toString()];++ if (typeof formatString !== 'string') { formatString = formatString.toString(); }++ var pattern = /(.*?)%(.)(.*)/;+ var rest = formatString;+ var result = [];++ while (args.length) {+ var match = pattern.exec(rest);+ if (!match) break;++ var arg = args.shift();+ rest = match[3];+ result.push(match[1]);++ if (match[2] === '%') {+ result.push('%');+ args.unshift(arg);+ continue;+ }++ result.push(__formatted(arg, match[2]));+ }++ result.push(rest);++ var remainingArgs = [].slice.call(args);+ remainingArgs.unshift(result.join(''));+ return remainingArgs;+}++function __formatted (object, formatChar) {++ try {+ switch (formatChar) {+ case 'j':+ case 'o': return JSON.stringify(object);+ case 'c': return '';+ }+ } catch (e) {+ return 'error JSON.stringify()ing argument: ' + e;+ }++ if ((object === null) || (object === undefined)) {+ return Object.prototype.toString.call(object);+ }++ return object.toString();+}++// ------------------------------------------------------------------------------+// when deviceready fires, log queued messages+logger.__onDeviceReady = function () {+ if (DeviceReady) return;++ DeviceReady = true;++ for (var i = 0; i < Queued.length; i++) {+ var messageArgs = Queued[i];+ logger.logLevel(messageArgs[0], messageArgs[1]);+ }++ Queued = null;+};++// add a deviceready event to log queued messages+document.addEventListener('deviceready', logger.__onDeviceReady, false);diff --git a/cordova/platforms/ios/www/cordova.js b/cordova/platforms/ios/www/cordova.jsnew file mode 100644index 000000000..9813b231f--- /dev/null+++ b/cordova/platforms/ios/www/cordova.js@@ -0,0 +1,2188 @@+// Platform: ios+// 9c79667cd175f51fd2edf2dc91ac8be98b89076a+/*+ 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.+*/+;(function() {+var PLATFORM_VERSION_BUILD_LABEL = '5.1.1';+// file: src/scripts/require.js+var require;+var define;++(function () {+ var modules = {};+ // Stack of moduleIds currently being built.+ var requireStack = [];+ // Map of module ID -> index into requireStack of modules currently being built.+ var inProgressModules = {};+ var SEPARATOR = '.';++ function build (module) {+ var factory = module.factory;+ var localRequire = function (id) {+ var resultantId = id;+ // Its a relative path, so lop off the last portion and add the id (minus "./")+ if (id.charAt(0) === '.') {+ resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2);+ }+ return require(resultantId);+ };+ module.exports = {};+ delete module.factory;+ factory(localRequire, module.exports, module);+ return module.exports;+ }++ require = function (id) {+ if (!modules[id]) {+ throw 'module ' + id + ' not found';+ } else if (id in inProgressModules) {+ var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;+ throw 'Cycle in require graph: ' + cycle;+ }+ if (modules[id].factory) {+ try {+ inProgressModules[id] = requireStack.length;+ requireStack.push(id);+ return build(modules[id]);+ } finally {+ delete inProgressModules[id];+ requireStack.pop();+ }+ }+ return modules[id].exports;+ };++ define = function (id, factory) {+ if (Object.prototype.hasOwnProperty.call(modules, id)) {+ throw 'module ' + id + ' already defined';+ }++ modules[id] = {+ id: id,+ factory: factory+ };+ };++ define.remove = function (id) {+ delete modules[id];+ };++ define.moduleMap = modules;+})();++// Export for use in node+if (typeof module === 'object' && typeof require === 'function') {+ module.exports.require = require;+ module.exports.define = define;+}++// file: src/cordova.js+define("cordova", function(require, exports, module) {++// Workaround for Windows 10 in hosted environment case+// http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object+if (window.cordova && !(window.cordova instanceof HTMLElement)) {+ throw new Error('cordova already defined');+}++var channel = require('cordova/channel');+var platform = require('cordova/platform');++/**+ * Intercept calls to addEventListener + removeEventListener and handle deviceready,+ * resume, and pause events.+ */+var m_document_addEventListener = document.addEventListener;+var m_document_removeEventListener = document.removeEventListener;+var m_window_addEventListener = window.addEventListener;+var m_window_removeEventListener = window.removeEventListener;++/**+ * Houses custom event handlers to intercept on document + window event listeners.+ */+var documentEventHandlers = {};+var windowEventHandlers = {};++document.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].subscribe(handler);+ } else {+ m_document_addEventListener.call(document, evt, handler, capture);+ }+};++window.addEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].subscribe(handler);+ } else {+ m_window_addEventListener.call(window, evt, handler, capture);+ }+};++document.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof documentEventHandlers[e] !== 'undefined') {+ documentEventHandlers[e].unsubscribe(handler);+ } else {+ m_document_removeEventListener.call(document, evt, handler, capture);+ }+};++window.removeEventListener = function (evt, handler, capture) {+ var e = evt.toLowerCase();+ // If unsubscribing from an event that is handled by a plugin+ if (typeof windowEventHandlers[e] !== 'undefined') {+ windowEventHandlers[e].unsubscribe(handler);+ } else {+ m_window_removeEventListener.call(window, evt, handler, capture);+ }+};++function createEvent (type, data) {+ var event = document.createEvent('Events');+ event.initEvent(type, false, false);+ if (data) {+ for (var i in data) {+ if (data.hasOwnProperty(i)) {+ event[i] = data[i];+ }+ }+ }+ return event;+}++var cordova = {+ define: define,+ require: require,+ version: PLATFORM_VERSION_BUILD_LABEL,+ platformVersion: PLATFORM_VERSION_BUILD_LABEL,+ platformId: platform.id,++ /**+ * Methods to add/remove your own addEventListener hijacking on document + window.+ */+ addWindowEventHandler: function (event) {+ return (windowEventHandlers[event] = channel.create(event));+ },+ addStickyDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.createSticky(event));+ },+ addDocumentEventHandler: function (event) {+ return (documentEventHandlers[event] = channel.create(event));+ },+ removeWindowEventHandler: function (event) {+ delete windowEventHandlers[event];+ },+ removeDocumentEventHandler: function (event) {+ delete documentEventHandlers[event];+ },++ /**+ * Retrieve original event handlers that were replaced by Cordova+ *+ * @return object+ */+ getOriginalHandlers: function () {+ return {+ document: {+ addEventListener: m_document_addEventListener,+ removeEventListener: m_document_removeEventListener+ },+ window: {+ addEventListener: m_window_addEventListener,+ removeEventListener: m_window_removeEventListener+ }+ };+ },++ /**+ * Method to fire event from native code+ * bNoDetach is required for events which cause an exception which needs to be caught in native code+ */+ fireDocumentEvent: function (type, data, bNoDetach) {+ var evt = createEvent(type, data);+ if (typeof documentEventHandlers[type] !== 'undefined') {+ if (bNoDetach) {+ documentEventHandlers[type].fire(evt);+ } else {+ setTimeout(function () {+ // Fire deviceready on listeners that were registered before cordova.js was loaded.+ if (type === 'deviceready') {+ document.dispatchEvent(evt);+ }+ documentEventHandlers[type].fire(evt);+ }, 0);+ }+ } else {+ document.dispatchEvent(evt);+ }+ },++ fireWindowEvent: function (type, data) {+ var evt = createEvent(type, data);+ if (typeof windowEventHandlers[type] !== 'undefined') {+ setTimeout(function () {+ windowEventHandlers[type].fire(evt);+ }, 0);+ } else {+ window.dispatchEvent(evt);+ }+ },++ /**+ * Plugin callback mechanism.+ */+ // Randomize the starting callbackId to avoid collisions after refreshing or navigating.+ // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.+ callbackId: Math.floor(Math.random() * 2000000000),+ callbacks: {},+ callbackStatus: {+ NO_RESULT: 0,+ OK: 1,+ CLASS_NOT_FOUND_EXCEPTION: 2,+ ILLEGAL_ACCESS_EXCEPTION: 3,+ INSTANTIATION_EXCEPTION: 4,+ MALFORMED_URL_EXCEPTION: 5,+ IO_EXCEPTION: 6,+ INVALID_ACTION: 7,+ JSON_EXCEPTION: 8,+ ERROR: 9+ },++ /**+ * Called by native code when returning successful result from an action.+ */+ callbackSuccess: function (callbackId, args) {+ cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning error result from an action.+ */+ callbackError: function (callbackId, args) {+ // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.+ // Derive success from status.+ cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);+ },++ /**+ * Called by native code when returning the result from an action.+ */+ callbackFromNative: function (callbackId, isSuccess, status, args, keepCallback) {+ try {+ var callback = cordova.callbacks[callbackId];+ if (callback) {+ if (isSuccess && status === cordova.callbackStatus.OK) {+ callback.success && callback.success.apply(null, args);+ } else if (!isSuccess) {+ callback.fail && callback.fail.apply(null, args);+ }+ /*+ else+ Note, this case is intentionally not caught.+ this can happen if isSuccess is true, but callbackStatus is NO_RESULT+ which is used to remove a callback from the list without calling the callbacks+ typically keepCallback is false in this case+ */+ // Clear callback if not expecting any more results+ if (!keepCallback) {+ delete cordova.callbacks[callbackId];+ }+ }+ } catch (err) {+ var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;+ console && console.log && console.log(msg);+ console && console.log && err.stack && console.log(err.stack);+ cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ throw err;+ }+ },++ addConstructor: function (func) {+ channel.onCordovaReady.subscribe(function () {+ try {+ func();+ } catch (e) {+ console.log('Failed to run constructor: ' + e);+ }+ });+ }+};++module.exports = cordova;++});++// file: src/common/argscheck.js+define("cordova/argscheck", function(require, exports, module) {++var utils = require('cordova/utils');++var moduleExports = module.exports;++var typeMap = {+ 'A': 'Array',+ 'D': 'Date',+ 'N': 'Number',+ 'S': 'String',+ 'F': 'Function',+ 'O': 'Object'+};++function extractParamName (callee, argIndex) {+ return (/\(\s*([^)]*?)\s*\)/).exec(callee)[1].split(/\s*,\s*/)[argIndex];+}++/**+ * Checks the given arguments' types and throws if they are not as expected.+ *+ * `spec` is a string where each character stands for the required type of the+ * argument at the same position. In other words: the character at `spec[i]`+ * specifies the required type for `args[i]`. The characters in `spec` are the+ * first letter of the required type's name. The supported types are:+ *+ * Array, Date, Number, String, Function, Object+ *+ * Lowercase characters specify arguments that must not be `null` or `undefined`+ * while uppercase characters allow those values to be passed.+ *+ * Finally, `*` can be used to allow any type at the corresponding position.+ *+ * @example+ * function foo (arr, opts) {+ * // require `arr` to be an Array and `opts` an Object, null or undefined+ * checkArgs('aO', 'my.package.foo', arguments);+ * // ...+ * }+ * @param {String} spec - the type specification for `args` as described above+ * @param {String} functionName - full name of the callee.+ * Used in the error message+ * @param {Array|arguments} args - the arguments to be checked against `spec`+ * @param {Function} [opt_callee=args.callee] - the recipient of `args`.+ * Used to extract parameter names for the error message+ * @throws {TypeError} if args do not satisfy spec+ */+function checkArgs (spec, functionName, args, opt_callee) {+ if (!moduleExports.enableChecks) {+ return;+ }+ var errMsg = null;+ var typeName;+ for (var i = 0; i < spec.length; ++i) {+ var c = spec.charAt(i);+ var cUpper = c.toUpperCase();+ var arg = args[i];+ // Asterix means allow anything.+ if (c === '*') {+ continue;+ }+ typeName = utils.typeName(arg);+ if ((arg === null || arg === undefined) && c === cUpper) {+ continue;+ }+ if (typeName !== typeMap[cUpper]) {+ errMsg = 'Expected ' + typeMap[cUpper];+ break;+ }+ }+ if (errMsg) {+ errMsg += ', but got ' + typeName + '.';+ errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;+ // Don't log when running unit tests.+ if (typeof jasmine === 'undefined') {+ console.error(errMsg);+ }+ throw TypeError(errMsg);+ }+}++function getValue (value, defaultValue) {+ return value === undefined ? defaultValue : value;+}++moduleExports.checkArgs = checkArgs;+moduleExports.getValue = getValue;+moduleExports.enableChecks = true;++});++// file: src/common/base64.js+define("cordova/base64", function(require, exports, module) {++var base64 = exports;++base64.fromArrayBuffer = function (arrayBuffer) {+ var array = new Uint8Array(arrayBuffer);+ return uint8ToBase64(array);+};++base64.toArrayBuffer = function (str) {+ var decodedStr = atob(str);+ var arrayBuffer = new ArrayBuffer(decodedStr.length);+ var array = new Uint8Array(arrayBuffer);+ for (var i = 0, len = decodedStr.length; i < len; i++) {+ array[i] = decodedStr.charCodeAt(i);+ }+ return arrayBuffer;+};++// ------------------------------------------------------------------------------++/* This code is based on the performance tests at http://jsperf.com/b64tests+ * This 12-bit-at-a-time algorithm was the best performing version on all+ * platforms tested.+ */++var b64_6bit = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';+var b64_12bit;++var b64_12bitTable = function () {+ b64_12bit = [];+ for (var i = 0; i < 64; i++) {+ for (var j = 0; j < 64; j++) {+ b64_12bit[i * 64 + j] = b64_6bit[i] + b64_6bit[j];+ }+ }+ b64_12bitTable = function () { return b64_12bit; };+ return b64_12bit;+};++function uint8ToBase64 (rawData) {+ var numBytes = rawData.byteLength;+ var output = '';+ var segment;+ var table = b64_12bitTable();+ for (var i = 0; i < numBytes - 2; i += 3) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8) + rawData[i + 2];+ output += table[segment >> 12];+ output += table[segment & 0xfff];+ }+ if (numBytes - i === 2) {+ segment = (rawData[i] << 16) + (rawData[i + 1] << 8);+ output += table[segment >> 12];+ output += b64_6bit[(segment & 0xfff) >> 6];+ output += '=';+ } else if (numBytes - i === 1) {+ segment = (rawData[i] << 16);+ output += table[segment >> 12];+ output += '==';+ }+ return output;+}++});++// file: src/common/builder.js+define("cordova/builder", function(require, exports, module) {++var utils = require('cordova/utils');++function each (objects, func, context) {+ for (var prop in objects) {+ if (objects.hasOwnProperty(prop)) {+ func.apply(context, [objects[prop], prop]);+ }+ }+}++function clobber (obj, key, value) {+ var needsProperty = false;+ try {+ obj[key] = value;+ } catch (e) {+ needsProperty = true;+ }+ // Getters can only be overridden by getters.+ if (needsProperty || obj[key] !== value) {+ utils.defineGetter(obj, key, function () {+ return value;+ });+ }+}++function assignOrWrapInDeprecateGetter (obj, key, value, message) {+ if (message) {+ utils.defineGetter(obj, key, function () {+ console.log(message);+ delete obj[key];+ clobber(obj, key, value);+ return value;+ });+ } else {+ clobber(obj, key, value);+ }+}++function include (parent, objects, clobber, merge) {+ each(objects, function (obj, key) {+ try {+ var result = obj.path ? require(obj.path) : {};++ if (clobber) {+ // Clobber if it doesn't exist.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else if (typeof obj.path !== 'undefined') {+ // If merging, merge properties onto parent, otherwise, clobber.+ if (merge) {+ recursiveMerge(parent[key], result);+ } else {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ }+ }+ result = parent[key];+ } else {+ // Overwrite if not currently defined.+ if (typeof parent[key] === 'undefined') {+ assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);+ } else {+ // Set result to what already exists, so we can build children into it if they exist.+ result = parent[key];+ }+ }++ if (obj.children) {+ include(result, obj.children, clobber, merge);+ }+ } catch (e) {+ utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');+ }+ });+}++/**+ * Merge properties from one object onto another recursively. Properties from+ * the src object will overwrite existing target property.+ *+ * @param target Object to merge properties into.+ * @param src Object to merge properties from.+ */+function recursiveMerge (target, src) {+ for (var prop in src) {+ if (src.hasOwnProperty(prop)) {+ if (target.prototype && target.prototype.constructor === target) {+ // If the target object is a constructor override off prototype.+ clobber(target.prototype, prop, src[prop]);+ } else {+ if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {+ recursiveMerge(target[prop], src[prop]);+ } else {+ clobber(target, prop, src[prop]);+ }+ }+ }+ }+}++exports.buildIntoButDoNotClobber = function (objects, target) {+ include(target, objects, false, false);+};+exports.buildIntoAndClobber = function (objects, target) {+ include(target, objects, true, false);+};+exports.buildIntoAndMerge = function (objects, target) {+ include(target, objects, true, true);+};+exports.recursiveMerge = recursiveMerge;+exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;++});++// file: src/common/channel.js+define("cordova/channel", function(require, exports, module) {++var utils = require('cordova/utils');+var nextGuid = 1;++/**+ * Custom pub-sub "channel" that can have functions subscribed to it+ * This object is used to define and control firing of events for+ * cordova initialization, as well as for custom events thereafter.+ *+ * The order of events during page load and Cordova startup is as follows:+ *+ * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.+ * onNativeReady* Internal event that indicates the Cordova native side is ready.+ * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.+ * onDeviceReady* User event fired to indicate that Cordova is ready+ * onResume User event fired to indicate a start/resume lifecycle event+ * onPause User event fired to indicate a pause lifecycle event+ *+ * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.+ * All listeners that subscribe after the event is fired will be executed right away.+ *+ * The only Cordova events that user code should register for are:+ * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript+ * pause App has moved to background+ * resume App has returned to foreground+ *+ * Listeners can be registered as:+ * document.addEventListener("deviceready", myDeviceReadyListener, false);+ * document.addEventListener("resume", myResumeListener, false);+ * document.addEventListener("pause", myPauseListener, false);+ *+ * The DOM lifecycle events should be used for saving and restoring state+ * window.onload+ * window.onunload+ *+ */++/**+ * Channel+ * @constructor+ * @param type String the channel name+ */+var Channel = function (type, sticky) {+ this.type = type;+ // Map of guid -> function.+ this.handlers = {};+ // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.+ this.state = sticky ? 1 : 0;+ // Used in sticky mode to remember args passed to fire().+ this.fireArgs = null;+ // Used by onHasSubscribersChange to know if there are any listeners.+ this.numHandlers = 0;+ // Function that is called when the first listener is subscribed, or when+ // the last listener is unsubscribed.+ this.onHasSubscribersChange = null;+};+var channel = {+ /**+ * Calls the provided function only after all of the channels specified+ * have been fired. All channels must be sticky channels.+ */+ join: function (h, c) {+ var len = c.length;+ var i = len;+ var f = function () {+ if (!(--i)) h();+ };+ for (var j = 0; j < len; j++) {+ if (c[j].state === 0) {+ throw Error('Can only use join with sticky channels.');+ }+ c[j].subscribe(f);+ }+ if (!len) h();+ },++ create: function (type) {+ return (channel[type] = new Channel(type, false));+ },+ createSticky: function (type) {+ return (channel[type] = new Channel(type, true));+ },++ /**+ * cordova Channels that must fire before "deviceready" is fired.+ */+ deviceReadyChannelsArray: [],+ deviceReadyChannelsMap: {},++ /**+ * Indicate that a feature needs to be initialized before it is ready to be used.+ * This holds up Cordova's "deviceready" event until the feature has been initialized+ * and Cordova.initComplete(feature) is called.+ *+ * @param feature {String} The unique feature name+ */+ waitForInitialization: function (feature) {+ if (feature) {+ var c = channel[feature] || this.createSticky(feature);+ this.deviceReadyChannelsMap[feature] = c;+ this.deviceReadyChannelsArray.push(c);+ }+ },++ /**+ * Indicate that initialization code has completed and the feature is ready to be used.+ *+ * @param feature {String} The unique feature name+ */+ initializationComplete: function (feature) {+ var c = this.deviceReadyChannelsMap[feature];+ if (c) {+ c.fire();+ }+ }+};++function checkSubscriptionArgument (argument) {+ if (typeof argument !== 'function' && typeof argument.handleEvent !== 'function') {+ throw new Error(+ 'Must provide a function or an EventListener object ' ++ 'implementing the handleEvent interface.'+ );+ }+}++/**+ * Subscribes the given function to the channel. Any time that+ * Channel.fire is called so too will the function.+ * Optionally specify an execution context for the function+ * and a guid that can be used to stop subscribing to the channel.+ * Returns the guid.+ */+Channel.prototype.subscribe = function (eventListenerOrFunction, eventListener) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ eventListener = eventListenerOrFunction;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ if (this.state === 2) {+ handleEvent.apply(eventListener || this, this.fireArgs);+ return;+ }++ guid = eventListenerOrFunction.observer_guid;+ if (typeof eventListener === 'object') {+ handleEvent = utils.close(eventListener, handleEvent);+ }++ if (!guid) {+ // First time any channel has seen this subscriber+ guid = '' + nextGuid++;+ }+ handleEvent.observer_guid = guid;+ eventListenerOrFunction.observer_guid = guid;++ // Don't add the same handler more than once.+ if (!this.handlers[guid]) {+ this.handlers[guid] = handleEvent;+ this.numHandlers++;+ if (this.numHandlers === 1) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Unsubscribes the function with the given guid from the channel.+ */+Channel.prototype.unsubscribe = function (eventListenerOrFunction) {+ checkSubscriptionArgument(eventListenerOrFunction);+ var handleEvent, guid, handler;++ if (eventListenerOrFunction && typeof eventListenerOrFunction === 'object') {+ // Received an EventListener object implementing the handleEvent interface+ handleEvent = eventListenerOrFunction.handleEvent;+ } else {+ // Received a function to handle event+ handleEvent = eventListenerOrFunction;+ }++ guid = handleEvent.observer_guid;+ handler = this.handlers[guid];+ if (handler) {+ delete this.handlers[guid];+ this.numHandlers--;+ if (this.numHandlers === 0) {+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++/**+ * Calls all functions subscribed to this channel.+ */+Channel.prototype.fire = function (e) {+ var fireArgs = Array.prototype.slice.call(arguments);+ // Apply stickiness.+ if (this.state === 1) {+ this.state = 2;+ this.fireArgs = fireArgs;+ }+ if (this.numHandlers) {+ // Copy the values first so that it is safe to modify it from within+ // callbacks.+ var toCall = [];+ for (var item in this.handlers) {+ toCall.push(this.handlers[item]);+ }+ for (var i = 0; i < toCall.length; ++i) {+ toCall[i].apply(this, fireArgs);+ }+ if (this.state === 2 && this.numHandlers) {+ this.numHandlers = 0;+ this.handlers = {};+ this.onHasSubscribersChange && this.onHasSubscribersChange();+ }+ }+};++// defining them here so they are ready super fast!+// DOM event that is received when the web page is loaded and parsed.+channel.createSticky('onDOMContentLoaded');++// Event to indicate the Cordova native side is ready.+channel.createSticky('onNativeReady');++// Event to indicate that all Cordova JavaScript objects have been created+// and it's time to run plugin constructors.+channel.createSticky('onCordovaReady');++// Event to indicate that all automatically loaded JS plugins are loaded and ready.+// FIXME remove this+channel.createSticky('onPluginsReady');++// Event to indicate that Cordova is ready+channel.createSticky('onDeviceReady');++// Event to indicate a resume lifecycle event+channel.create('onResume');++// Event to indicate a pause lifecycle event+channel.create('onPause');++// Channels that must fire before "deviceready" is fired.+channel.waitForInitialization('onCordovaReady');+channel.waitForInitialization('onDOMContentLoaded');++module.exports = channel;++});++// file: ../cordova-ios/cordova-js-src/exec.js+define("cordova/exec", function(require, exports, module) {++/* global require, module, atob, document */++/**+ * Creates a gap bridge iframe used to notify the native code about queued+ * commands.+ */+var cordova = require('cordova');+var utils = require('cordova/utils');+var base64 = require('cordova/base64');+var execIframe;+var commandQueue = []; // Contains pending JS->Native messages.+var isInContextOfEvalJs = 0;+var failSafeTimerId = 0;++function massageArgsJsToNative (args) {+ if (!args || utils.typeName(args) !== 'Array') {+ return args;+ }+ var ret = [];+ args.forEach(function (arg, i) {+ if (utils.typeName(arg) === 'ArrayBuffer') {+ ret.push({+ 'CDVType': 'ArrayBuffer',+ 'data': base64.fromArrayBuffer(arg)+ });+ } else {+ ret.push(arg);+ }+ });+ return ret;+}++function massageMessageNativeToJs (message) {+ if (message.CDVType === 'ArrayBuffer') {+ var stringToArrayBuffer = function (str) {+ var ret = new Uint8Array(str.length);+ for (var i = 0; i < str.length; i++) {+ ret[i] = str.charCodeAt(i);+ }+ return ret.buffer;+ };+ var base64ToArrayBuffer = function (b64) {+ return stringToArrayBuffer(atob(b64));+ };+ message = base64ToArrayBuffer(message.data);+ }+ return message;+}++function convertMessageToArgsNativeToJs (message) {+ var args = [];+ if (!message || !message.hasOwnProperty('CDVType')) {+ args.push(message);+ } else if (message.CDVType === 'MultiPart') {+ message.messages.forEach(function (e) {+ args.push(massageMessageNativeToJs(e));+ });+ } else {+ args.push(massageMessageNativeToJs(message));+ }+ return args;+}++function iOSExec () {++ var successCallback, failCallback, service, action, actionArgs;+ var callbackId = null;+ if (typeof arguments[0] !== 'string') {+ // FORMAT ONE+ successCallback = arguments[0];+ failCallback = arguments[1];+ service = arguments[2];+ action = arguments[3];+ actionArgs = arguments[4];++ // Since we need to maintain backwards compatibility, we have to pass+ // an invalid callbackId even if no callback was provided since plugins+ // will be expecting it. The Cordova.exec() implementation allocates+ // an invalid callbackId and passes it even if no callbacks were given.+ callbackId = 'INVALID';+ } else {+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' ++ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'+ );+ }++ // If actionArgs is not provided, default to an empty array+ actionArgs = actionArgs || [];++ // Register the callbacks and add the callbackId to the positional+ // arguments if given.+ if (successCallback || failCallback) {+ callbackId = service + cordova.callbackId++;+ cordova.callbacks[callbackId] =+ { success: successCallback, fail: failCallback };+ }++ actionArgs = massageArgsJsToNative(actionArgs);++ var command = [callbackId, service, action, actionArgs];++ // Stringify and queue the command. We stringify to command now to+ // effectively clone the command arguments in case they are mutated before+ // the command is executed.+ commandQueue.push(JSON.stringify(command));++ // If we're in the context of a stringByEvaluatingJavaScriptFromString call,+ // then the queue will be flushed when it returns; no need for a poke.+ // Also, if there is already a command in the queue, then we've already+ // poked the native side, so there is no reason to do so again.+ if (!isInContextOfEvalJs && commandQueue.length === 1) {+ pokeNative();+ }+}++// CB-10530+function proxyChanged () {+ var cexec = cordovaExec();++ return (execProxy !== cexec && // proxy objects are different+ iOSExec !== cexec // proxy object is not the current iOSExec+ );+}++// CB-10106+function handleBridgeChange () {+ if (proxyChanged()) {+ var commandString = commandQueue.shift();+ while (commandString) {+ var command = JSON.parse(commandString);+ var callbackId = command[0];+ var service = command[1];+ var action = command[2];+ var actionArgs = command[3];+ var callbacks = cordova.callbacks[callbackId] || {};++ execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);++ commandString = commandQueue.shift();+ }+ return true;+ }++ return false;+}++function pokeNative () {+ // CB-5488 - Don't attempt to create iframe before document.body is available.+ if (!document.body) {+ setTimeout(pokeNative);+ return;+ }++ // Check if they've removed it from the DOM, and put it back if so.+ if (execIframe && execIframe.contentWindow) {+ execIframe.contentWindow.location = 'gap://ready';+ } else {+ execIframe = document.createElement('iframe');+ execIframe.style.display = 'none';+ execIframe.src = 'gap://ready';+ document.body.appendChild(execIframe);+ }+ // Use a timer to protect against iframe being unloaded during the poke (CB-7735).+ // This makes the bridge ~ 7% slower, but works around the poke getting lost+ // when the iframe is removed from the DOM.+ // An onunload listener could be used in the case where the iframe has just been+ // created, but since unload events fire only once, it doesn't work in the normal+ // case of iframe reuse (where unload will have already fired due to the attempted+ // navigation of the page).+ failSafeTimerId = setTimeout(function () {+ if (commandQueue.length) {+ // CB-10106 - flush the queue on bridge change+ if (!handleBridgeChange()) {+ pokeNative();+ }+ }+ }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).+}++iOSExec.nativeFetchMessages = function () {+ // Stop listing for window detatch once native side confirms poke.+ if (failSafeTimerId) {+ clearTimeout(failSafeTimerId);+ failSafeTimerId = 0;+ }+ // Each entry in commandQueue is a JSON string already.+ if (!commandQueue.length) {+ return '';+ }+ var json = '[' + commandQueue.join(',') + ']';+ commandQueue.length = 0;+ return json;+};++iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {+ return iOSExec.nativeEvalAndFetch(function () {+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ function nc2 () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback);+ }+ setTimeout(nc2, 0);+ });+};++iOSExec.nativeEvalAndFetch = function (func) {+ // This shouldn't be nested, but better to be safe.+ isInContextOfEvalJs++;+ try {+ func();+ return iOSExec.nativeFetchMessages();+ } finally {+ isInContextOfEvalJs--;+ }+};++// Proxy the exec for bridge changes. See CB-10106++function cordovaExec () {+ var cexec = require('cordova/exec');+ var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function');+ return (cexec_valid && execProxy !== cexec) ? cexec : iOSExec;+}++function execProxy () {+ cordovaExec().apply(null, arguments);+}++execProxy.nativeFetchMessages = function () {+ return cordovaExec().nativeFetchMessages.apply(null, arguments);+};++execProxy.nativeEvalAndFetch = function () {+ return cordovaExec().nativeEvalAndFetch.apply(null, arguments);+};++execProxy.nativeCallback = function () {+ return cordovaExec().nativeCallback.apply(null, arguments);+};++module.exports = execProxy;++});++// file: src/common/exec/proxy.js+define("cordova/exec/proxy", function(require, exports, module) {++// internal map of proxy function+var CommandProxyMap = {};++module.exports = {++ // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...);+ add: function (id, proxyObj) {+ console.log('adding proxy for ' + id);+ CommandProxyMap[id] = proxyObj;+ return proxyObj;+ },++ // cordova.commandProxy.remove("Accelerometer");+ remove: function (id) {+ var proxy = CommandProxyMap[id];+ delete CommandProxyMap[id];+ CommandProxyMap[id] = null;+ return proxy;+ },++ get: function (service, action) {+ return (CommandProxyMap[service] ? CommandProxyMap[service][action] : null);+ }+};++});++// file: src/common/init.js+define("cordova/init", function(require, exports, module) {++var channel = require('cordova/channel');+var cordova = require('cordova');+var modulemapper = require('cordova/modulemapper');+var platform = require('cordova/platform');+var pluginloader = require('cordova/pluginloader');+var utils = require('cordova/utils');++var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];++function logUnfiredChannels (arr) {+ for (var i = 0; i < arr.length; ++i) {+ if (arr[i].state !== 2) {+ console.log('Channel not fired: ' + arr[i].type);+ }+ }+}++window.setTimeout(function () {+ if (channel.onDeviceReady.state !== 2) {+ console.log('deviceready has not fired after 5 seconds.');+ logUnfiredChannels(platformInitChannelsArray);+ logUnfiredChannels(channel.deviceReadyChannelsArray);+ }+}, 5000);++// Replace navigator before any modules are required(), to ensure it happens as soon as possible.+// We replace it so that properties that can't be clobbered can instead be overridden.+function replaceNavigator (origNavigator) {+ var CordovaNavigator = function () {};+ CordovaNavigator.prototype = origNavigator;+ var newNavigator = new CordovaNavigator();+ // This work-around really only applies to new APIs that are newer than Function.bind.+ // Without it, APIs such as getGamepads() break.+ if (CordovaNavigator.bind) {+ for (var key in origNavigator) {+ if (typeof origNavigator[key] === 'function') {+ newNavigator[key] = origNavigator[key].bind(origNavigator);+ } else {+ (function (k) {+ utils.defineGetterSetter(newNavigator, key, function () {+ return origNavigator[k];+ });+ })(key);+ }+ }+ }+ return newNavigator;+}++if (window.navigator) {+ window.navigator = replaceNavigator(window.navigator);+}++if (!window.console) {+ window.console = {+ log: function () {}+ };+}+if (!window.console.warn) {+ window.console.warn = function (msg) {+ this.log('warn: ' + msg);+ };+}++// Register pause, resume and deviceready channels as events on document.+channel.onPause = cordova.addDocumentEventHandler('pause');+channel.onResume = cordova.addDocumentEventHandler('resume');+channel.onActivated = cordova.addDocumentEventHandler('activated');+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');++// Listen for DOMContentLoaded and notify our channel subscribers.+if (document.readyState === 'complete' || document.readyState === 'interactive') {+ channel.onDOMContentLoaded.fire();+} else {+ document.addEventListener('DOMContentLoaded', function () {+ channel.onDOMContentLoaded.fire();+ }, false);+}++// _nativeReady is global variable that the native side can set+// to signify that the native code is ready. It is a global since+// it may be called before any cordova JS is ready.+if (window._nativeReady) {+ channel.onNativeReady.fire();+}++modulemapper.clobbers('cordova', 'cordova');+modulemapper.clobbers('cordova/exec', 'cordova.exec');+modulemapper.clobbers('cordova/exec', 'Cordova.exec');++// Call the platform-specific initialization.+platform.bootstrap && platform.bootstrap();++// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.+// The delay allows the attached modules to be defined before the plugin loader looks for them.+setTimeout(function () {+ pluginloader.load(function () {+ channel.onPluginsReady.fire();+ });+}, 0);++/**+ * Create all cordova objects once native side is ready.+ */+channel.join(function () {+ modulemapper.mapModules(window);++ platform.initialize && platform.initialize();++ // Fire event to notify that all objects are created+ channel.onCordovaReady.fire();++ // Fire onDeviceReady event once page has fully loaded, all+ // constructors have run and cordova info has been received from native+ // side.+ channel.join(function () {+ require('cordova').fireDocumentEvent('deviceready');+ }, channel.deviceReadyChannelsArray);++}, platformInitChannelsArray);++});++// file: src/common/modulemapper.js+define("cordova/modulemapper", function(require, exports, module) {++var builder = require('cordova/builder');+var moduleMap = define.moduleMap;+var symbolList;+var deprecationMap;++exports.reset = function () {+ symbolList = [];+ deprecationMap = {};+};++function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {+ if (!(moduleName in moduleMap)) {+ throw new Error('Module ' + moduleName + ' does not exist.');+ }+ symbolList.push(strategy, moduleName, symbolPath);+ if (opt_deprecationMessage) {+ deprecationMap[symbolPath] = opt_deprecationMessage;+ }+}++// Note: Android 2.3 does have Function.bind().+exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('c', moduleName, symbolPath, opt_deprecationMessage);+};++exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('m', moduleName, symbolPath, opt_deprecationMessage);+};++exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {+ addEntry('d', moduleName, symbolPath, opt_deprecationMessage);+};++exports.runs = function (moduleName) {+ addEntry('r', moduleName, null);+};++function prepareNamespace (symbolPath, context) {+ if (!symbolPath) {+ return context;+ }+ return symbolPath.split('.').reduce(function (cur, part) {+ return (cur[part] = cur[part] || {});+ }, context);+}++exports.mapModules = function (context) {+ var origSymbols = {};+ context.CDV_origSymbols = origSymbols;+ for (var i = 0, len = symbolList.length; i < len; i += 3) {+ var strategy = symbolList[i];+ var moduleName = symbolList[i + 1];+ var module = require(moduleName);+ // <runs/>+ if (strategy === 'r') {+ continue;+ }+ var symbolPath = symbolList[i + 2];+ var lastDot = symbolPath.lastIndexOf('.');+ var namespace = symbolPath.substr(0, lastDot);+ var lastName = symbolPath.substr(lastDot + 1);++ var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;+ var parentObj = prepareNamespace(namespace, context);+ var target = parentObj[lastName];++ if (strategy === 'm' && target) {+ builder.recursiveMerge(target, module);+ } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {+ if (!(symbolPath in origSymbols)) {+ origSymbols[symbolPath] = target;+ }+ builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);+ }+ }+};++exports.getOriginalSymbol = function (context, symbolPath) {+ var origSymbols = context.CDV_origSymbols;+ if (origSymbols && (symbolPath in origSymbols)) {+ return origSymbols[symbolPath];+ }+ var parts = symbolPath.split('.');+ var obj = context;+ for (var i = 0; i < parts.length; ++i) {+ obj = obj && obj[parts[i]];+ }+ return obj;+};++exports.reset();++});++// file: ../cordova-ios/cordova-js-src/platform.js+define("cordova/platform", function(require, exports, module) {++module.exports = {+ id: 'ios',+ bootstrap: function () {+ // Attach the console polyfill that is iOS-only to window.console+ // see the file under plugin/ios/console.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');++ require('cordova/channel').onNativeReady.fire();+ }+};++});++// file: ../cordova-ios/cordova-js-src/plugin/ios/console.js+define("cordova/plugin/ios/console", function(require, exports, module) {++// ------------------------------------------------------------------------------++var logger = require('cordova/plugin/ios/logger');++// ------------------------------------------------------------------------------+// object that we're exporting+// ------------------------------------------------------------------------------+var console = module.exports;++// ------------------------------------------------------------------------------+// copy of the original console object+// ------------------------------------------------------------------------------+var WinConsole = window.console;++// ------------------------------------------------------------------------------+// whether to use the logger+// ------------------------------------------------------------------------------+var UseLogger = false;++// ------------------------------------------------------------------------------+// Timers+// ------------------------------------------------------------------------------+var Timers = {};++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+function noop () {}++// ------------------------------------------------------------------------------+// used for unimplemented methods+// ------------------------------------------------------------------------------+console.useLogger = function (value) {+ if (arguments.length) UseLogger = !!value;++ if (UseLogger) {+ if (logger.useConsole()) {+ throw new Error('console and logger are too intertwingly');+ }+ }++ return UseLogger;+};++// ------------------------------------------------------------------------------+console.log = function () {+ if (logger.useConsole()) return;+ logger.log.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.error = function () {+ if (logger.useConsole()) return;+ logger.error.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.warn = function () {+ if (logger.useConsole()) return;+ logger.warn.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.info = function () {+ if (logger.useConsole()) return;+ logger.info.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.debug = function () {+ if (logger.useConsole()) return;+ logger.debug.apply(logger, [].slice.call(arguments));+};++// ------------------------------------------------------------------------------+console.assert = function (expression) {+ if (expression) return;++ var message = logger.format.apply(logger.format, [].slice.call(arguments, 1));+ console.log('ASSERT: ' + message);+};++// ------------------------------------------------------------------------------+console.clear = function () {};++// ------------------------------------------------------------------------------+console.dir = function (object) {+ console.log('%o', object);+};++// ------------------------------------------------------------------------------+console.dirxml = function (node) {+ console.log(node.innerHTML);+};++// ------------------------------------------------------------------------------+console.trace = noop;++// ------------------------------------------------------------------------------+console.group = console.log;++// ------------------------------------------------------------------------------+console.groupCollapsed = console.log;++// ------------------------------------------------------------------------------+console.groupEnd = noop;++// ------------------------------------------------------------------------------+console.time = function (name) {+ Timers[name] = new Date().valueOf();+};++// ------------------------------------------------------------------------------+console.timeEnd = function (name) {+ var timeStart = Timers[name];+ if (!timeStart) {+ console.warn('unknown timer: ' + name);+ return;+ }++ var timeElapsed = new Date().valueOf() - timeStart;+ console.log(name + ': ' + timeElapsed + 'ms');+};++// ------------------------------------------------------------------------------+console.timeStamp = noop;++// ------------------------------------------------------------------------------+console.profile = noop;++// ------------------------------------------------------------------------------+console.profileEnd = noop;++// ------------------------------------------------------------------------------+console.count = noop;++// ------------------------------------------------------------------------------+console.exception = console.log;++// ------------------------------------------------------------------------------+console.table = function (data, columns) {+ console.log('%o', data);+};++// ------------------------------------------------------------------------------+// return a new function that calls both functions passed as args+// ------------------------------------------------------------------------------+function wrappedOrigCall (orgFunc, newFunc) {+ return function () {+ var args = [].slice.call(arguments);+ try { orgFunc.apply(WinConsole, args); } catch (e) {}+ try { newFunc.apply(console, args); } catch (e) {}+ };+}++// ------------------------------------------------------------------------------+// For every function that exists in the original console object, that+// also exists in the new console object, wrap the new console method+// with one that calls both+// ------------------------------------------------------------------------------+for (var key in console) {+ if (typeof WinConsole[key] === 'function') {+ console[key] = wrappedOrigCall(WinConsole[key], console[key]);+ }+}++});++// file: ../cordova-ios/cordova-js-src/plugin/ios/logger.js+define("cordova/plugin/ios/logger", function(require, exports, module) {++// ------------------------------------------------------------------------------+// The logger module exports the following properties/functions:+//+// LOG - constant for the level LOG+// ERROR - constant for the level ERROR+// WARN - constant for the level WARN+// INFO - constant for the level INFO+// DEBUG - constant for the level DEBUG+// logLevel() - returns current log level+// logLevel(value) - sets and returns a new log level+// useConsole() - returns whether logger is using console+// useConsole(value) - sets and returns whether logger is using console+// log(message,...) - logs a message at level LOG+// error(message,...) - logs a message at level ERROR+// warn(message,...) - logs a message at level WARN+// info(message,...) - logs a message at level INFO+// debug(message,...) - logs a message at level DEBUG+// logLevel(level,message,...) - logs a message specified level+//+// ------------------------------------------------------------------------------++var logger = exports;++var exec = require('cordova/exec');++var UseConsole = false;+var UseLogger = true;+var Queued = [];+var DeviceReady = false;+var CurrentLevel;++var originalConsole = console;++/**+ * Logging levels+ */++var Levels = [+ 'LOG',+ 'ERROR',+ 'WARN',+ 'INFO',+ 'DEBUG'+];++/*+ * add the logging levels to the logger object and+ * to a separate levelsMap object for testing+ */++var LevelsMap = {};+for (var i = 0; i < Levels.length; i++) {+ var level = Levels[i];+ LevelsMap[level] = i;+ logger[level] = level;+}++CurrentLevel = LevelsMap.WARN;++/**+ * Getter/Setter for the logging level+ *+ * Returns the current logging level.+ *+ * When a value is passed, sets the logging level to that value.+ * The values should be one of the following constants:+ * logger.LOG+ * logger.ERROR+ * logger.WARN+ * logger.INFO+ * logger.DEBUG+ *+ * The value used determines which messages get printed. The logging+ * values above are in order, and only messages logged at the logging+ * level or above will actually be displayed to the user. E.g., the+ * default level is WARN, so only messages logged with LOG, ERROR, or+ * WARN will be displayed; INFO and DEBUG messages will be ignored.+ */+logger.level = function (value) {+ if (arguments.length) {+ if (LevelsMap[value] === null) {+ throw new Error('invalid logging level: ' + value);+ }+ CurrentLevel = LevelsMap[value];+ }++ return Levels[CurrentLevel];+};++/**+ * Getter/Setter for the useConsole functionality+ *+ * When useConsole is true, the logger will log via the+ * browser 'console' object.+ */+logger.useConsole = function (value) {+ if (arguments.length) UseConsole = !!value;++ if (UseConsole) {+ if (typeof console === 'undefined') {+ throw new Error('global console object is not defined');+ }++ if (typeof console.log !== 'function') {+ throw new Error('global console object does not have a log function');+ }++ if (typeof console.useLogger === 'function') {+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }+ }+ }++ return UseConsole;+};++/**+ * Getter/Setter for the useLogger functionality+ *+ * When useLogger is true, the logger will log via the+ * native Logger plugin.+ */+logger.useLogger = function (value) {+ // Enforce boolean+ if (arguments.length) UseLogger = !!value;+ return UseLogger;+};++/**+ * Logs a message at the LOG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.log = function (message) { logWithArgs('LOG', arguments); };++/**+ * Logs a message at the ERROR level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.error = function (message) { logWithArgs('ERROR', arguments); };++/**+ * Logs a message at the WARN level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.warn = function (message) { logWithArgs('WARN', arguments); };++/**+ * Logs a message at the INFO level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.info = function (message) { logWithArgs('INFO', arguments); };++/**+ * Logs a message at the DEBUG level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.debug = function (message) { logWithArgs('DEBUG', arguments); };++// log at the specified level with args+function logWithArgs (level, args) {+ args = [level].concat([].slice.call(args));+ logger.logLevel.apply(logger, args);+}++// return the correct formatString for an object+function formatStringForMessage (message) {+ return (typeof message === 'string') ? '' : '%o';+}++/**+ * Logs a message at the specified level.+ *+ * Parameters passed after message are used applied to+ * the message with utils.format()+ */+logger.logLevel = function (level /* , ... */) {+ // format the message with the parameters+ var formatArgs = [].slice.call(arguments, 1);+ var fmtString = formatStringForMessage(formatArgs[0]);+ if (fmtString.length > 0) {+ formatArgs.unshift(fmtString); // add formatString+ }++ var message = logger.format.apply(logger.format, formatArgs);++ if (LevelsMap[level] === null) {+ throw new Error('invalid logging level: ' + level);+ }++ if (LevelsMap[level] > CurrentLevel) return;++ // queue the message if not yet at deviceready+ if (!DeviceReady && !UseConsole) {+ Queued.push([level, message]);+ return;+ }++ // Log using the native logger if that is enabled+ if (UseLogger) {+ exec(null, null, 'Console', 'logLevel', [level, message]);+ }++ // Log using the console if that is enabled+ if (UseConsole) {+ // make sure console is not using logger+ if (console.useLogger()) {+ throw new Error('console and logger are too intertwingly');+ }++ // log to the console+ switch (level) {+ case logger.LOG: originalConsole.log(message); break;+ case logger.ERROR: originalConsole.log('ERROR: ' + message); break;+ case logger.WARN: originalConsole.log('WARN: ' + message); break;+ case logger.INFO: originalConsole.log('INFO: ' + message); break;+ case logger.DEBUG: originalConsole.log('DEBUG: ' + message); break;+ }+ }+};++/**+ * Formats a string and arguments following it ala console.log()+ *+ * Any remaining arguments will be appended to the formatted string.+ *+ * for rationale, see FireBug's Console API:+ * http://getfirebug.com/wiki/index.php/Console_API+ */+logger.format = function (formatString, args) {+ return __format(arguments[0], [].slice.call(arguments, 1)).join(' ');+};++// ------------------------------------------------------------------------------+/**+ * Formats a string and arguments following it ala vsprintf()+ *+ * format chars:+ * %j - format arg as JSON+ * %o - format arg as JSON+ * %c - format arg as ''+ * %% - replace with '%'+ * any other char following % will format it's+ * arg via toString().+ *+ * Returns an array containing the formatted string and any remaining+ * arguments.+ */+function __format (formatString, args) {+ if (formatString === null || formatString === undefined) return [''];+ if (arguments.length === 1) return [formatString.toString()];++ if (typeof formatString !== 'string') { formatString = formatString.toString(); }++ var pattern = /(.*?)%(.)(.*)/;+ var rest = formatString;+ var result = [];++ while (args.length) {+ var match = pattern.exec(rest);+ if (!match) break;++ var arg = args.shift();+ rest = match[3];+ result.push(match[1]);++ if (match[2] === '%') {+ result.push('%');+ args.unshift(arg);+ continue;+ }++ result.push(__formatted(arg, match[2]));+ }++ result.push(rest);++ var remainingArgs = [].slice.call(args);+ remainingArgs.unshift(result.join(''));+ return remainingArgs;+}++function __formatted (object, formatChar) {++ try {+ switch (formatChar) {+ case 'j':+ case 'o': return JSON.stringify(object);+ case 'c': return '';+ }+ } catch (e) {+ return 'error JSON.stringify()ing argument: ' + e;+ }++ if ((object === null) || (object === undefined)) {+ return Object.prototype.toString.call(object);+ }++ return object.toString();+}++// ------------------------------------------------------------------------------+// when deviceready fires, log queued messages+logger.__onDeviceReady = function () {+ if (DeviceReady) return;++ DeviceReady = true;++ for (var i = 0; i < Queued.length; i++) {+ var messageArgs = Queued[i];+ logger.logLevel(messageArgs[0], messageArgs[1]);+ }++ Queued = null;+};++// add a deviceready event to log queued messages+document.addEventListener('deviceready', logger.__onDeviceReady, false);++});++// file: src/common/pluginloader.js+define("cordova/pluginloader", function(require, exports, module) {++var modulemapper = require('cordova/modulemapper');++// Helper function to inject a <script> tag.+// Exported for testing.+exports.injectScript = function (url, onload, onerror) {+ var script = document.createElement('script');+ // onload fires even when script fails loads with an error.+ script.onload = onload;+ // onerror fires for malformed URLs.+ script.onerror = onerror;+ script.src = url;+ document.head.appendChild(script);+};++function injectIfNecessary (id, url, onload, onerror) {+ onerror = onerror || onload;+ if (id in define.moduleMap) {+ onload();+ } else {+ exports.injectScript(url, function () {+ if (id in define.moduleMap) {+ onload();+ } else {+ onerror();+ }+ }, onerror);+ }+}++function onScriptLoadingComplete (moduleList, finishPluginLoading) {+ // Loop through all the plugins and then through their clobbers and merges.+ for (var i = 0, module; (module = moduleList[i]); i++) {+ if (module.clobbers && module.clobbers.length) {+ for (var j = 0; j < module.clobbers.length; j++) {+ modulemapper.clobbers(module.id, module.clobbers[j]);+ }+ }++ if (module.merges && module.merges.length) {+ for (var k = 0; k < module.merges.length; k++) {+ modulemapper.merges(module.id, module.merges[k]);+ }+ }++ // Finally, if runs is truthy we want to simply require() the module.+ if (module.runs) {+ modulemapper.runs(module.id);+ }+ }++ finishPluginLoading();+}++// Handler for the cordova_plugins.js content.+// See plugman's plugin_loader.js for the details of this object.+// This function is only called if the really is a plugins array that isn't empty.+// Otherwise the onerror response handler will just call finishPluginLoading().+function handlePluginsObject (path, moduleList, finishPluginLoading) {+ // Now inject the scripts.+ var scriptCounter = moduleList.length;++ if (!scriptCounter) {+ finishPluginLoading();+ return;+ }+ function scriptLoadedCallback () {+ if (!--scriptCounter) {+ onScriptLoadingComplete(moduleList, finishPluginLoading);+ }+ }++ for (var i = 0; i < moduleList.length; i++) {+ injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback);+ }+}++function findCordovaPath () {+ var path = null;+ var scripts = document.getElementsByTagName('script');+ var term = '/cordova.js';+ for (var n = scripts.length - 1; n > -1; n--) {+ var src = scripts[n].src.replace(/\?.*$/, ''); // Strip any query param (CB-6007).+ if (src.indexOf(term) === (src.length - term.length)) {+ path = src.substring(0, src.length - term.length) + '/';+ break;+ }+ }+ return path;+}++// Tries to load all plugins' js-modules.+// This is an async process, but onDeviceReady is blocked on onPluginsReady.+// onPluginsReady is fired when there are no plugins to load, or they are all done.+exports.load = function (callback) {+ var pathPrefix = findCordovaPath();+ if (pathPrefix === null) {+ console.log('Could not find cordova.js script tag. Plugin loading may fail.');+ pathPrefix = '';+ }+ injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function () {+ var moduleList = require('cordova/plugin_list');+ handlePluginsObject(pathPrefix, moduleList, callback);+ }, callback);+};++});++// file: src/common/urlutil.js+define("cordova/urlutil", function(require, exports, module) {++/**+ * For already absolute URLs, returns what is passed in.+ * For relative URLs, converts them to absolute ones.+ */+exports.makeAbsolute = function makeAbsolute (url) {+ var anchorEl = document.createElement('a');+ anchorEl.href = url;+ return anchorEl.href;+};++});++// file: src/common/utils.js+define("cordova/utils", function(require, exports, module) {++var utils = exports;++/**+ * Defines a property getter / setter for obj[key].+ */+utils.defineGetterSetter = function (obj, key, getFunc, opt_setFunc) {+ if (Object.defineProperty) {+ var desc = {+ get: getFunc,+ configurable: true+ };+ if (opt_setFunc) {+ desc.set = opt_setFunc;+ }+ Object.defineProperty(obj, key, desc);+ } else {+ obj.__defineGetter__(key, getFunc);+ if (opt_setFunc) {+ obj.__defineSetter__(key, opt_setFunc);+ }+ }+};++/**+ * Defines a property getter for obj[key].+ */+utils.defineGetter = utils.defineGetterSetter;++utils.arrayIndexOf = function (a, item) {+ if (a.indexOf) {+ return a.indexOf(item);+ }+ var len = a.length;+ for (var i = 0; i < len; ++i) {+ if (a[i] === item) {+ return i;+ }+ }+ return -1;+};++/**+ * Returns whether the item was found in the array.+ */+utils.arrayRemove = function (a, item) {+ var index = utils.arrayIndexOf(a, item);+ if (index !== -1) {+ a.splice(index, 1);+ }+ return index !== -1;+};++utils.typeName = function (val) {+ return Object.prototype.toString.call(val).slice(8, -1);+};++/**+ * Returns an indication of whether the argument is an array or not+ */+utils.isArray = Array.isArray ||+ function (a) { return utils.typeName(a) === 'Array'; };++/**+ * Returns an indication of whether the argument is a Date or not+ */+utils.isDate = function (d) {+ return (d instanceof Date);+};++/**+ * Does a deep clone of the object.+ */+utils.clone = function (obj) {+ if (!obj || typeof obj === 'function' || utils.isDate(obj) || typeof obj !== 'object') {+ return obj;+ }++ var retVal, i;++ if (utils.isArray(obj)) {+ retVal = [];+ for (i = 0; i < obj.length; ++i) {+ retVal.push(utils.clone(obj[i]));+ }+ return retVal;+ }++ retVal = {};+ for (i in obj) {+ // 'unknown' type may be returned in custom protocol activation case on+ // Windows Phone 8.1 causing "No such interface supported" exception on+ // cloning (https://issues.apache.org/jira/browse/CB-11522)+ // eslint-disable-next-line valid-typeof+ if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') {+ retVal[i] = utils.clone(obj[i]);+ }+ }+ return retVal;+};++/**+ * Returns a wrapped version of the function+ */+utils.close = function (context, func, params) {+ return function () {+ var args = params || arguments;+ return func.apply(context, args);+ };+};++// ------------------------------------------------------------------------------+function UUIDcreatePart (length) {+ var uuidpart = '';+ for (var i = 0; i < length; i++) {+ var uuidchar = parseInt((Math.random() * 256), 10).toString(16);+ if (uuidchar.length === 1) {+ uuidchar = '0' + uuidchar;+ }+ uuidpart += uuidchar;+ }+ return uuidpart;+}++/**+ * Create a UUID+ */+utils.createUUID = function () {+ return UUIDcreatePart(4) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(2) + '-' ++ UUIDcreatePart(6);+};++/**+ * Extends a child object from a parent object using classical inheritance+ * pattern.+ */+utils.extend = (function () {+ // proxy used to establish prototype chain+ var F = function () {};+ // extend Child from Parent+ return function (Child, Parent) {++ F.prototype = Parent.prototype;+ Child.prototype = new F();+ Child.__super__ = Parent.prototype;+ Child.prototype.constructor = Child;+ };+}());++/**+ * Alerts a message in any available way: alert or console.log.+ */+utils.alert = function (msg) {+ if (window.alert) {+ window.alert(msg);+ } else if (console && console.log) {+ console.log(msg);+ }+};++});++window.cordova = require('cordova');+// file: src/scripts/bootstrap.js+require('cordova/init');++})();diff --git a/cordova/platforms/ios/www/cordova_plugins.js b/cordova/platforms/ios/www/cordova_plugins.jsnew file mode 100644index 000000000..e8ef01fbe--- /dev/null+++ b/cordova/platforms/ios/www/cordova_plugins.js@@ -0,0 +1,242 @@+cordova.define('cordova/plugin_list', function(require, exports, module) {+ module.exports = [+ {+ "id": "cordova-plugin-device.device",+ "file": "plugins/cordova-plugin-device/www/device.js",+ "pluginId": "cordova-plugin-device",+ "clobbers": [+ "device"+ ]+ },+ {+ "id": "cordova-plugin-background-mode.BackgroundMode",+ "file": "plugins/cordova-plugin-background-mode/www/background-mode.js",+ "pluginId": "cordova-plugin-background-mode",+ "clobbers": [+ "cordova.plugins.backgroundMode",+ "plugin.backgroundMode"+ ]+ },+ {+ "id": "cordova-plugin-camera.Camera",+ "file": "plugins/cordova-plugin-camera/www/CameraConstants.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "Camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverOptions",+ "file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverOptions"+ ]+ },+ {+ "id": "cordova-plugin-camera.camera",+ "file": "plugins/cordova-plugin-camera/www/Camera.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "navigator.camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverHandle",+ "file": "plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverHandle"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryEntry",+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryReader",+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryReader"+ ]+ },+ {+ "id": "cordova-plugin-file.Entry",+ "file": "plugins/cordova-plugin-file/www/Entry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Entry"+ ]+ },+ {+ "id": "cordova-plugin-file.File",+ "file": "plugins/cordova-plugin-file/www/File.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.File"+ ]+ },+ {+ "id": "cordova-plugin-file.FileEntry",+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.FileError",+ "file": "plugins/cordova-plugin-file/www/FileError.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileError"+ ]+ },+ {+ "id": "cordova-plugin-file.FileReader",+ "file": "plugins/cordova-plugin-file/www/FileReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileReader"+ ]+ },+ {+ "id": "cordova-plugin-file.FileSystem",+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadOptions",+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadOptions"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadResult",+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadResult"+ ]+ },+ {+ "id": "cordova-plugin-file.FileWriter",+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileWriter"+ ]+ },+ {+ "id": "cordova-plugin-file.Flags",+ "file": "plugins/cordova-plugin-file/www/Flags.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Flags"+ ]+ },+ {+ "id": "cordova-plugin-file.LocalFileSystem",+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.LocalFileSystem"+ ],+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.Metadata",+ "file": "plugins/cordova-plugin-file/www/Metadata.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Metadata"+ ]+ },+ {+ "id": "cordova-plugin-file.ProgressEvent",+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.ProgressEvent"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems",+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",+ "pluginId": "cordova-plugin-file"+ },+ {+ "id": "cordova-plugin-file.requestFileSystem",+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.requestFileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.isChrome",+ "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.iosFileSystem",+ "file": "plugins/cordova-plugin-file/www/ios/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems-roots",+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.fileSystemPaths",+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "cordova"+ ],+ "runs": true+ },+ {+ "id": "cordova-plugin-file-opener2.FileOpener2",+ "file": "plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js",+ "pluginId": "cordova-plugin-file-opener2",+ "clobbers": [+ "cordova.plugins.fileOpener2"+ ]+ }+ ];+ module.exports.metadata = {+ "cordova-plugin-device": "2.0.3",+ "cordova-plugin-background-mode": "0.7.3",+ "cordova-plugin-camera": "4.1.0",+ "cordova-plugin-file": "6.0.2",+ "cordova-plugin-file-opener2": "3.0.4",+ "cordova-plugin-whitelist": "1.3.4"+ };+});\ No newline at end of filediff --git a/cordova/platforms/ios/www/index.html b/cordova/platforms/ios/www/index.htmlnew file mode 100644index 000000000..398557d72--- /dev/null+++ b/cordova/platforms/ios/www/index.html@@ -0,0 +1,74 @@+<!DOCTYPE html>+<html>++<head>+ <title>TagSpaces Mobile</title>+ <meta http-equiv="Content-Security-Policy" content="connect-src file: *; default-src 'self' data: gap: cdvfile: ; script-src 'self' ; style-src 'self' 'unsafe-inline' data: blob: ; media-src *; img-src * data: content:;">+ <meta name="format-detection" content="telephone=no">+ <meta name="msapplication-tap-highlight" content="no">+ <meta charset="utf-8">+ <meta name="viewport"+ content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">+ <meta name="theme-color" content="#1DD19F">+ <meta name="description" content="PWA for TagSpaces Pro">+ <meta name="apple-mobile-web-app-capable" content="yes">+ <meta name="apple-mobile-web-app-status-bar-style" content="black">+ <meta name="apple-mobile-web-app-title" content="TagSpaces PRO">+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/iphone5_splash.png" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/iphone6_splash.png" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/iphoneplus_splash.png" media="(device-width: 621px) and (device-height: 1104px) and (-webkit-device-pixel-ratio: 3)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/iphonex_splash.png" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/iphonexr_splash.png" media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/iphonexsmax_splash.png" media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/ipad_splash.png" media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/ipadpro1_splash.png" media="(device-width: 834px) and (device-height: 1112px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/ipadpro3_splash.png" media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />+ <link href="/node_modules/@tagspaces/pro/assets/splashscreens/ipadpro2_splash.png" media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />+ <link rel="icon" sizes="192x192" href="/node_modules/@tagspaces/pro/assets/icons/192x192.png" />+ <link rel="apple-touch-icon" href="/node_modules/@tagspaces/pro/assets/icons/192x192.png" />+ <link rel="stylesheet" type="text/css" href="dist/style.css">+ <script type="text/javascript" src="extconfig.js"></script>+</head>++<body style="overflow: hidden; margin: 0; padding: 0;">+ <noscript>This app requires JavaScript</noscript>+ <div id="root">+ <div+ style="text-align: center; width: 100%; height: 100%; font-size: 1.4em; position:absolute; z-index: 999999; background-color: #F5F5F5; user-select: none; -webkit-user-select: none; -moz-user-select: none; -webkit-app-region: drag"+ class="appBackgroundTile">+ <div style="top:45%; width: 100%; text-align: center; position:absolute;">+ <svg style="vertical-align: middle" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100">+ <g id="layer1" transform="matrix(0.33346217,0,0,0.33346217,-0.01300084,-250.91)">+ <rect style="fill:none;fill-opacity:1;stroke:none" id="rect3052-8-1" width="299.42227" height="299.42227"+ x="-0.019505024" y="752.95935" />+ <path style="fill:#ffffff;fill-opacity:1;stroke:none"+ d="m 181.90177,787.75394 70.88695,43.53834 C 180.29225,977.67059 187.41436,950.59754 124.58989,989.154 L 65.05006,905.90077 Z"+ id="rect3052-8-2-2" />+ <ellipse style="fill:#616577;fill-opacity:1;stroke:none" id="path4875-4-7-5-6-2" cx="192.4187"+ cy="851.11481" rx="15.970615" ry="15.782593" />+ <path+ style="fill:none;stroke:#a466aa;stroke-width:27.50978279;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"+ d="M 159.73623,964.91671 134.54529,941.61879" id="path3108-5-39-8" />+ <path+ style="fill:none;stroke:#ffffff;stroke-width:34.19813538;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"+ d="m 162.16161,795.17204 90.03628,0.34544 0,86.1724 -115.50748,117.79375 -88.457192,-81.6665 z"+ id="path3923-1-1-4-9-8" />+ <path+ style="fill:#f7901e;fill-opacity:1;stroke:#33b5be;stroke-width:27.50978279;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"+ d="m 204.81469,910.87834 -50.38182,-45.3016" id="path3108-9-1-76-7" />+ <path+ style="fill:#616577;fill-opacity:1;stroke:#f7901e;stroke-width:27.50978279;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"+ d="M 182.93838,938.7066 144.48907,904.40668" id="path3108-0-7-9-8" />+ <path+ style="fill:none;stroke:#616577;stroke-width:31.96374702;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"+ d="m 164.34385,800.70161 83.03644,0 0,79.10209 -110.49206,113.42316 -82.031957,-75.83333 z"+ id="path3923-1-1-4-9" />+ </g>+ </svg>+ </div>+ </div>+ </div>+ <script type="text/javascript" src="cordova.js"></script>+ <script type="text/javascript" src="dist/bundle.js"></script>+</body>+</html>diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-background-mode/www/background-mode.js b/cordova/platforms/ios/www/plugins/cordova-plugin-background-mode/www/background-mode.jsnew file mode 100644index 000000000..7895b27ad--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-background-mode/www/background-mode.js@@ -0,0 +1,513 @@+cordova.define("cordova-plugin-background-mode.BackgroundMode", function(require, exports, module) {+/*+ Copyright 2013-2017 appPlant GmbH++ 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 = require('cordova/exec'),+ channel = require('cordova/channel');++/**+ * Activates the background mode. When activated the application+ * will be prevented from going to sleep while in background+ * for the next time.+ *+ * @return [ Void ]+ */+exports.enable = function()+{+ if (this.isEnabled())+ return;++ var fn = function() {+ exports._isEnabled = true;+ exports.fireEvent('enable');+ };++ cordova.exec(fn, null, 'BackgroundMode', 'enable', []);+};++/**+ * Deactivates the background mode. When deactivated the application+ * will not stay awake while in background.+ *+ * @return [ Void ]+ */+exports.disable = function()+{+ if (!this.isEnabled())+ return;++ var fn = function() {+ exports._isEnabled = false;+ exports.fireEvent('disable');+ };++ cordova.exec(fn, null, 'BackgroundMode', 'disable', []);+};++/**+ * Enable or disable the background mode.+ *+ * @param [ Bool ] enable The status to set for.+ *+ * @return [ Void ]+ */+exports.setEnabled = function (enable)+{+ if (enable) {+ this.enable();+ } else {+ this.disable();+ }+};++/**+ * List of all available options with their default value.+ *+ * @return [ Object ]+ */+exports.getDefaults = function()+{+ return this._defaults;+};++/**+ * The actual applied settings.+ *+ * @return [ Object ]+ */+exports.getSettings = function()+{+ return this._settings || {};+};++/**+ * Overwrite the default settings.+ *+ * @param [ Object ] overrides Dict of options to be overridden.+ *+ * @return [ Void ]+ */+exports.setDefaults = function (overrides)+{+ var defaults = this.getDefaults();++ for (var key in defaults)+ {+ if (overrides.hasOwnProperty(key))+ {+ defaults[key] = overrides[key];+ }+ }++ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundMode', 'configure', [defaults, false]);+ }+};++/**+ * Configures the notification settings for Android.+ * Will be merged with the defaults.+ *+ * @param [ Object ] options Dict of options to be overridden.+ *+ * @return [ Void ]+ */+exports.configure = function (options)+{+ var settings = this.getSettings(),+ defaults = this.getDefaults();++ if (!this._isAndroid)+ return;++ if (!this._isActive)+ {+ console.log('BackgroundMode is not active, skipped...');+ return;+ }++ this._mergeObjects(options, settings);+ this._mergeObjects(options, defaults);+ this._settings = options;++ cordova.exec(null, null, 'BackgroundMode', 'configure', [options, true]);+};++/**+ * Enable GPS-tracking in background (Android).+ *+ * @return [ Void ]+ */+exports.disableWebViewOptimizations = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'webview', []);+ }+};++/**+ * Disables battery optimazation mode for the app.+ *+ * @return [ Void ]+ */+exports.disableBatteryOptimizations = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'battery', []);+ }+};++/**+ * Opens the system settings dialog where the user can tweak or turn off any+ * custom app start settings added by the manufacturer if available.+ *+ * @param [ Object|Bool ] options Set to false if you dont want to display an+ * alert dialog first.+ *+ * @return [ Void ]+ */+exports.openAppStartSettings = function (options)+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'appstart', [options]);+ }+};++/**+ * Move app to background (Android only).+ *+ * @return [ Void ]+ */+exports.moveToBackground = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'background', []);+ }+};++/**+ * Move app to foreground when in background (Android only).+ *+ * @return [ Void ]+ */+exports.moveToForeground = function()+{+ if (this.isActive() && this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'foreground', []);+ }+};++/**+ * Exclude the app from the recent tasks list (Android only).+ *+ * @return [ Void ]+ */+exports.excludeFromTaskList = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'tasklist', []);+ }+};++/**+ * Override the back button on Android to go to background+ * instead of closing the app.+ *+ * @return [ Void ]+ */+exports.overrideBackButton = function()+{+ document.addEventListener('backbutton', function() {+ exports.moveToBackground();+ }, false);+};++/**+ * If the screen is off.+ *+ * @param [ Function ] fn Callback function to invoke with boolean arg.+ *+ * @return [ Void ]+ */+exports.isScreenOff = function (fn)+{+ if (this._isAndroid)+ {+ cordova.exec(fn, null, 'BackgroundModeExt', 'dimmed', []);+ }+ else+ {+ fn(undefined);+ }+};++/**+ * Wake up the device.+ *+ * @return [ Void ]+ */+exports.wakeUp = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'wakeup', []);+ }+};++/**+ * Wake up and unlock the device.+ *+ * @return [ Void ]+ */+exports.unlock = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'unlock', []);+ }+};++/**+ * If the mode is enabled or disabled.+ *+ * @return [ Boolean ]+ */+exports.isEnabled = function()+{+ return this._isEnabled !== false;+};++/**+ * If the mode is active.+ *+ * @return [ Boolean ]+ */+exports.isActive = function()+{+ return this._isActive !== false;+};++exports._listener = {};++/**+ * Fire event with given arguments.+ *+ * @param [ String ] event The event's name.+ * @param [ Array<Object> ] The callback's arguments.+ *+ * @return [ Void ]+ */+exports.fireEvent = function (event)+{+ var args = Array.apply(null, arguments).slice(1),+ listener = this._listener[event];++ if (!listener)+ return;++ for (var i = 0; i < listener.length; i++)+ {+ var fn = listener[i][0],+ scope = listener[i][1];++ fn.apply(scope, args);+ }+};++/**+ * Register callback for given event.+ *+ * @param [ String ] event The event's name.+ * @param [ Function ] callback The function to be exec as callback.+ * @param [ Object ] scope The callback function's scope.+ *+ * @return [ Void ]+ */+exports.on = function (event, callback, scope)+{+ if (typeof callback !== "function")+ return;++ if (!this._listener[event])+ {+ this._listener[event] = [];+ }++ var item = [callback, scope || window];++ this._listener[event].push(item);+};++/**+ * Unregister callback for given event.+ *+ * @param [ String ] event The event's name.+ * @param [ Function ] callback The function to be exec as callback.+ *+ * @return [ Void ]+ */+exports.un = function (event, callback)+{+ var listener = this._listener[event];++ if (!listener)+ return;++ for (var i = 0; i < listener.length; i++)+ {+ var fn = listener[i][0];++ if (fn == callback)+ {+ listener.splice(i, 1);+ break;+ }+ }+};++/**+ * @private+ *+ * Flag indicates if the mode is enabled.+ */+exports._isEnabled = false;++/**+ * @private+ *+ * Flag indicates if the mode is active.+ */+exports._isActive = false;++/**+ * @private+ *+ * Default values of all available options.+ */+exports._defaults =+{+ title: 'App is running in background',+ text: 'Doing heavy tasks.',+ bigText: false,+ resume: true,+ silent: false,+ hidden: true,+ color: undefined,+ icon: 'icon'+};++/**+ * @private+ *+ * Merge settings with default values.+ *+ * @param [ Object ] options The custom options.+ * @param [ Object ] toMergeIn The options to merge in.+ *+ * @return [ Object ] Default values merged with custom values.+ */+exports._mergeObjects = function (options, toMergeIn)+{+ for (var key in toMergeIn)+ {+ if (!options.hasOwnProperty(key))+ {+ options[key] = toMergeIn[key];+ continue;+ }+ }++ return options;+};++/**+ * @private+ *+ * Setter for the isActive flag. Resets the+ * settings if the mode isnt active anymore.+ *+ * @param [ Boolean] value The new value for the flag.+ *+ * @return [ Void ]+ */+exports._setActive = function(value)+{+ if (this._isActive == value)+ return;++ this._isActive = value;+ this._settings = value ? this._mergeObjects({}, this._defaults) : {};+};++/**+ * @private+ *+ * Initialize the plugin.+ *+ * Method should be called after the 'deviceready' event+ * but before the event listeners will be called.+ *+ * @return [ Void ]+ */+exports._pluginInitialize = function()+{+ this._isAndroid = device.platform.match(/^android|amazon/i) !== null;+ this.setDefaults({});++ if (device.platform == 'browser')+ {+ this.enable();+ this._isEnabled = true;+ }++ this._isActive = this._isActive || device.platform == 'browser';+};++// Called before 'deviceready' listener will be called+channel.onCordovaReady.subscribe(function()+{+ channel.onCordovaInfoReady.subscribe(function() {+ exports._pluginInitialize();+ });+});++// Called after 'deviceready' event+channel.deviceready.subscribe(function()+{+ if (exports.isEnabled())+ {+ exports.fireEvent('enable');+ }++ if (exports.isActive())+ {+ exports.fireEvent('activate');+ }+});++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/Camera.js b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/Camera.jsnew file mode 100644index 000000000..3f614ec80--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/Camera.js@@ -0,0 +1,188 @@+cordova.define("cordova-plugin-camera.camera", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var exec = require('cordova/exec');+var Camera = require('./Camera');+// XXX: commented out+// CameraPopoverHandle = require('./CameraPopoverHandle');++/**+ * @namespace navigator+ */++/**+ * @exports camera+ */+var cameraExport = {};++// Tack on the Camera Constants to the base camera plugin.+for (var key in Camera) {+ cameraExport[key] = Camera[key];+}++/**+ * Callback function that provides an error message.+ * @callback module:camera.onError+ * @param {string} message - The message is provided by the device's native code.+ */++/**+ * Callback function that provides the image data.+ * @callback module:camera.onSuccess+ * @param {string} imageData - Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`]{@link module:camera.CameraOptions} in effect.+ * @example+ * // Show image+ * //+ * function cameraCallback(imageData) {+ * var image = document.getElementById('myImage');+ * image.src = "data:image/jpeg;base64," + imageData;+ * }+ */++/**+ * Optional parameters to customize the camera settings.+ * * [Quirks](#CameraOptions-quirks)+ * @typedef module:camera.CameraOptions+ * @type {Object}+ * @property {number} [quality=50] - Quality of the saved image, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information about the camera's resolution is unavailable.)+ * @property {module:Camera.DestinationType} [destinationType=FILE_URI] - Choose the format of the return value.+ * @property {module:Camera.PictureSourceType} [sourceType=CAMERA] - Set the source of the picture.+ * @property {Boolean} [allowEdit=false] - Allow simple editing of image before selection.+ * @property {module:Camera.EncodingType} [encodingType=JPEG] - Choose the returned image file's encoding.+ * @property {number} [targetWidth] - Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant.+ * @property {number} [targetHeight] - Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant.+ * @property {module:Camera.MediaType} [mediaType=PICTURE] - Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`.+ * @property {Boolean} [correctOrientation] - Rotate the image to correct for the orientation of the device during capture.+ * @property {Boolean} [saveToPhotoAlbum] - Save the image to the photo album on the device after capture.+ * @property {module:CameraPopoverOptions} [popoverOptions] - iOS-only options that specify popover location in iPad.+ * @property {module:Camera.Direction} [cameraDirection=BACK] - Choose the camera to use (front- or back-facing).+ */++/**+ * @description Takes a photo using the camera, or retrieves a photo from the device's+ * image gallery. The image is passed to the success callback as a+ * Base64-encoded `String`, or as the URI for the image file.+ *+ * The `camera.getPicture` function opens the device's default camera+ * application that allows users to snap pictures by default - this behavior occurs,+ * when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`]{@link module:Camera.PictureSourceType}.+ * Once the user snaps the photo, the camera application closes and the application is restored.+ *+ * If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or+ * `Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays+ * that allows users to select an existing image.+ *+ * The return value is sent to the [`cameraSuccess`]{@link module:camera.onSuccess} callback function, in+ * one of the following formats, depending on the specified+ * `cameraOptions`:+ *+ * - A `String` containing the Base64-encoded photo image.+ * - A `String` representing the image file location on local storage (default).+ *+ * You can do whatever you want with the encoded image or URI, for+ * example:+ *+ * - Render the image in an `<img>` tag, as in the example below+ * - Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)+ * - Post the data to a remote server+ *+ * __NOTE__: Photo resolution on newer devices is quite good. Photos+ * selected from the device's gallery are not downscaled to a lower+ * quality, even if a `quality` parameter is specified. To avoid common+ * memory problems, set `Camera.destinationType` to `FILE_URI` rather+ * than `DATA_URL`.+ *+ * __Supported Platforms__+ *+ * - Android+ * - BlackBerry+ * - Browser+ * - Firefox+ * - FireOS+ * - iOS+ * - Windows+ * - WP8+ * - Ubuntu+ *+ * More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).+ *+ * @example+ * navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);+ * @param {module:camera.onSuccess} successCallback+ * @param {module:camera.onError} errorCallback+ * @param {module:camera.CameraOptions} options CameraOptions+ */+cameraExport.getPicture = function (successCallback, errorCallback, options) {+ argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);+ options = options || {};+ var getValue = argscheck.getValue;++ var quality = getValue(options.quality, 50);+ var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);+ var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);+ var targetWidth = getValue(options.targetWidth, -1);+ var targetHeight = getValue(options.targetHeight, -1);+ var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);+ var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);+ var allowEdit = !!options.allowEdit;+ var correctOrientation = !!options.correctOrientation;+ var saveToPhotoAlbum = !!options.saveToPhotoAlbum;+ var popoverOptions = getValue(options.popoverOptions, null);+ var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);++ var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,+ mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];++ exec(successCallback, errorCallback, 'Camera', 'takePicture', args);+ // XXX: commented out+ // return new CameraPopoverHandle();+};++/**+ * Removes intermediate image files that are kept in temporary storage+ * after calling [`camera.getPicture`]{@link module:camera.getPicture}. Applies only when the value of+ * `Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the+ * `Camera.destinationType` equals `Camera.DestinationType.FILE_URI`.+ *+ * __Supported Platforms__+ *+ * - iOS+ *+ * @example+ * navigator.camera.cleanup(onSuccess, onFail);+ *+ * function onSuccess() {+ * console.log("Camera cleanup success.")+ * }+ *+ * function onFail(message) {+ * alert('Failed because: ' + message);+ * }+ */+cameraExport.cleanup = function (successCallback, errorCallback) {+ exec(successCallback, errorCallback, 'Camera', 'cleanup', []);+};++module.exports = cameraExport;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/CameraConstants.js b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/CameraConstants.jsnew file mode 100644index 000000000..4f4b046f1--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/CameraConstants.js@@ -0,0 +1,104 @@+cordova.define("cordova-plugin-camera.Camera", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * @module Camera+ */+module.exports = {+ /**+ * @description+ * Defines the output format of `Camera.getPicture` call.+ * _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with+ * `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will+ * disable any image modifications (resize, quality change, cropping, etc.) due+ * to implementation specific.+ *+ * @enum {number}+ */+ DestinationType: {+ /** Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible */+ DATA_URL: 0,+ /** Return file uri (content://media/external/images/media/2 for Android) */+ FILE_URI: 1,+ /** Return native uri (eg. asset-library://... for iOS) */+ NATIVE_URI: 2+ },+ /**+ * @enum {number}+ */+ EncodingType: {+ /** Return JPEG encoded image */+ JPEG: 0,+ /** Return PNG encoded image */+ PNG: 1+ },+ /**+ * @enum {number}+ */+ MediaType: {+ /** Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType */+ PICTURE: 0,+ /** Allow selection of video only, ONLY RETURNS URL */+ VIDEO: 1,+ /** Allow selection from all media types */+ ALLMEDIA: 2+ },+ /**+ * @description+ * Defines the output format of `Camera.getPicture` call.+ * _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`+ * along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality+ * change, cropping, etc.) due to implementation specific.+ *+ * @enum {number}+ */+ PictureSourceType: {+ /** Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) */+ PHOTOLIBRARY: 0,+ /** Take picture from camera */+ CAMERA: 1,+ /** Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) */+ SAVEDPHOTOALBUM: 2+ },+ /**+ * Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.+ * @enum {number}+ */+ PopoverArrowDirection: {+ ARROW_UP: 1,+ ARROW_DOWN: 2,+ ARROW_LEFT: 4,+ ARROW_RIGHT: 8,+ ARROW_ANY: 15+ },+ /**+ * @enum {number}+ */+ Direction: {+ /** Use the back-facing camera */+ BACK: 0,+ /** Use the front-facing camera */+ FRONT: 1+ }+};++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.jsnew file mode 100644index 000000000..6e03c52ee--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js@@ -0,0 +1,59 @@+cordova.define("cordova-plugin-camera.CameraPopoverOptions", function(require, exports, module) {+/*+ *+ * 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 Camera = require('./Camera');++/**+ * @namespace navigator+ */++/**+ * iOS-only parameters that specify the anchor element location and arrow+ * direction of the popover when selecting images from an iPad's library+ * or album.+ * Note that the size of the popover may change to adjust to the+ * direction of the arrow and orientation of the screen. Make sure to+ * account for orientation changes when specifying the anchor element+ * location.+ * @module CameraPopoverOptions+ * @param {Number} [x=0] - x pixel coordinate of screen element onto which to anchor the popover.+ * @param {Number} [y=32] - y pixel coordinate of screen element onto which to anchor the popover.+ * @param {Number} [width=320] - width, in pixels, of the screen element onto which to anchor the popover.+ * @param {Number} [height=480] - height, in pixels, of the screen element onto which to anchor the popover.+ * @param {module:Camera.PopoverArrowDirection} [arrowDir=ARROW_ANY] - Direction the arrow on the popover should point.+ * @param {Number} [popoverWidth=0] - width of the popover (0 or not specified will use apple's default width).+ * @param {Number} [popoverHeight=0] - height of the popover (0 or not specified will use apple's default height).+ */+var CameraPopoverOptions = function (x, y, width, height, arrowDir, popoverWidth, popoverHeight) {+ // information of rectangle that popover should be anchored to+ this.x = x || 0;+ this.y = y || 32;+ this.width = width || 320;+ this.height = height || 480;+ this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;+ this.popoverWidth = popoverWidth || 0;+ this.popoverHeight = popoverHeight || 0;+};++module.exports = CameraPopoverOptions;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.jsnew file mode 100644index 000000000..6da9fa35d--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js@@ -0,0 +1,69 @@+cordova.define("cordova-plugin-camera.CameraPopoverHandle", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');++/**+ * @namespace navigator+ */++/**+ * A handle to an image picker popover.+ *+ * __Supported Platforms__+ *+ * - iOS+ *+ * @example+ * navigator.camera.getPicture(onSuccess, onFail,+ * {+ * destinationType: Camera.DestinationType.FILE_URI,+ * sourceType: Camera.PictureSourceType.PHOTOLIBRARY,+ * popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY, 300, 600)+ * });+ *+ * // Reposition the popover if the orientation changes.+ * window.onorientationchange = function() {+ * var cameraPopoverHandle = new CameraPopoverHandle();+ * var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY, 400, 500);+ * cameraPopoverHandle.setPosition(cameraPopoverOptions);+ * }+ * @module CameraPopoverHandle+ */+var CameraPopoverHandle = function () {+ /**+ * Can be used to reposition the image selection dialog,+ * for example, when the device orientation changes.+ * @memberof CameraPopoverHandle+ * @instance+ * @method setPosition+ * @param {module:CameraPopoverOptions} popoverOptions+ */+ this.setPosition = function (popoverOptions) {+ var args = [ popoverOptions ];+ exec(null, null, 'Camera', 'repositionPopover', args);+ };+};++module.exports = CameraPopoverHandle;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-device/www/device.js b/cordova/platforms/ios/www/plugins/cordova-plugin-device/www/device.jsnew file mode 100644index 000000000..ae48e3546--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-device/www/device.js@@ -0,0 +1,86 @@+cordova.define("cordova-plugin-device.device", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var channel = require('cordova/channel');+var utils = require('cordova/utils');+var exec = require('cordova/exec');+var cordova = require('cordova');++channel.createSticky('onCordovaInfoReady');+// Tell cordova channel to wait on the CordovaInfoReady event+channel.waitForInitialization('onCordovaInfoReady');++/**+ * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the+ * phone, etc.+ * @constructor+ */+function Device () {+ this.available = false;+ this.platform = null;+ this.version = null;+ this.uuid = null;+ this.cordova = null;+ this.model = null;+ this.manufacturer = null;+ this.isVirtual = null;+ this.serial = null;++ var me = this;++ channel.onCordovaReady.subscribe(function () {+ me.getInfo(function (info) {+ // ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js+ // TODO: CB-5105 native implementations should not return info.cordova+ var buildLabel = cordova.version;+ me.available = true;+ me.platform = info.platform;+ me.version = info.version;+ me.uuid = info.uuid;+ me.cordova = buildLabel;+ me.model = info.model;+ me.isVirtual = info.isVirtual;+ me.manufacturer = info.manufacturer || 'unknown';+ me.serial = info.serial || 'unknown';+ channel.onCordovaInfoReady.fire();+ }, function (e) {+ me.available = false;+ utils.alert('[ERROR] Error initializing Cordova: ' + e);+ });+ });+}++/**+ * Get device info+ *+ * @param {Function} successCallback The function to call when the heading data is available+ * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)+ */+Device.prototype.getInfo = function (successCallback, errorCallback) {+ argscheck.checkArgs('fF', 'Device.getInfo', arguments);+ exec(successCallback, errorCallback, 'Device', 'getDeviceInfo', []);+};++module.exports = new Device();++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.jsnew file mode 100644index 000000000..395c4d973--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js@@ -0,0 +1,54 @@+cordova.define("cordova-plugin-file-opener2.FileOpener2", function(require, exports, module) {+/*jslint browser: true, devel: true, node: true, sloppy: true, plusplus: true*/+/*global require, cordova */+/*+The MIT License (MIT)++Copyright (c) 2013 pwlin - [email protected]++Permission is hereby granted, free of charge, to any person obtaining a copy of+this software and associated documentation files (the "Software"), to deal in+the Software without restriction, including without limitation the rights to+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software is furnished to do so,+subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+*/+var exec = require('cordova/exec');++function FileOpener2() {}++FileOpener2.prototype.open = function (fileName, contentType, callbackContext) {+ contentType = contentType || '';+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'open', [fileName, contentType]);+};++FileOpener2.prototype.showOpenWithDialog = function (fileName, contentType, callbackContext) {+ contentType = contentType || '';+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'open', [fileName, contentType, false, callbackContext.position || [0, 0]]);+};++FileOpener2.prototype.uninstall = function (packageId, callbackContext) {+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'uninstall', [packageId]);+};++FileOpener2.prototype.appIsInstalled = function (packageId, callbackContext) {+ callbackContext = callbackContext || {};+ exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener2', 'appIsInstalled', [packageId]);+};++module.exports = new FileOpener2();++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/DirectoryEntry.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/DirectoryEntry.jsnew file mode 100644index 000000000..bb676eb6c--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/DirectoryEntry.js@@ -0,0 +1,120 @@+cordova.define("cordova-plugin-file.DirectoryEntry", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var utils = require('cordova/utils');+var exec = require('cordova/exec');+var Entry = require('./Entry');+var FileError = require('./FileError');+var DirectoryReader = require('./DirectoryReader');++/**+ * An interface representing a directory on the file system.+ *+ * {boolean} isFile always false (readonly)+ * {boolean} isDirectory always true (readonly)+ * {DOMString} name of the directory, excluding the path leading to it (readonly)+ * {DOMString} fullPath the absolute full path to the directory (readonly)+ * {FileSystem} filesystem on which the directory resides (readonly)+ */+var DirectoryEntry = function (name, fullPath, fileSystem, nativeURL) {++ // add trailing slash if it is missing+ if ((fullPath) && !/\/$/.test(fullPath)) {+ fullPath += '/';+ }+ // add trailing slash if it is missing+ if (nativeURL && !/\/$/.test(nativeURL)) {+ nativeURL += '/';+ }+ DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL);+};++utils.extend(DirectoryEntry, Entry);++/**+ * Creates a new DirectoryReader to read entries from this directory+ */+DirectoryEntry.prototype.createReader = function () {+ return new DirectoryReader(this.toInternalURL());+};++/**+ * Creates or looks up a directory+ *+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory+ * @param {Flags} options to create or exclusively create the directory+ * @param {Function} successCallback is called with the new entry+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryEntry.prototype.getDirectory = function (path, options, successCallback, errorCallback) {+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);+ var fs = this.filesystem;+ var win = successCallback && function (result) {+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);+ successCallback(entry);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getDirectory', [this.toInternalURL(), path, options]);+};++/**+ * Deletes a directory and all of it's contents+ *+ * @param {Function} successCallback is called with no parameters+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryEntry.prototype.removeRecursively = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(successCallback, fail, 'File', 'removeRecursively', [this.toInternalURL()]);+};++/**+ * Creates or looks up a file+ *+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file+ * @param {Flags} options to create or exclusively create the file+ * @param {Function} successCallback is called with the new entry+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryEntry.prototype.getFile = function (path, options, successCallback, errorCallback) {+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);+ var fs = this.filesystem;+ var win = successCallback && function (result) {+ var FileEntry = require('./FileEntry');+ var entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL);+ successCallback(entry);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getFile', [this.toInternalURL(), path, options]);+};++module.exports = DirectoryEntry;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/DirectoryReader.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/DirectoryReader.jsnew file mode 100644index 000000000..417c85f10--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/DirectoryReader.js@@ -0,0 +1,75 @@+cordova.define("cordova-plugin-file.DirectoryReader", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var FileError = require('./FileError');++/**+ * An interface that lists the files and directories in a directory.+ */+function DirectoryReader (localURL) {+ this.localURL = localURL || null;+ this.hasReadEntries = false;+}++/**+ * Returns a list of entries from a directory.+ *+ * @param {Function} successCallback is called with a list of entries+ * @param {Function} errorCallback is called with a FileError+ */+DirectoryReader.prototype.readEntries = function (successCallback, errorCallback) {+ // If we've already read and passed on this directory's entries, return an empty list.+ if (this.hasReadEntries) {+ successCallback([]);+ return;+ }+ var reader = this;+ var win = typeof successCallback !== 'function' ? null : function (result) {+ var retVal = [];+ for (var i = 0; i < result.length; i++) {+ var entry = null;+ if (result[i].isDirectory) {+ entry = new (require('./DirectoryEntry'))();+ } else if (result[i].isFile) {+ entry = new (require('./FileEntry'))();+ }+ entry.isDirectory = result[i].isDirectory;+ entry.isFile = result[i].isFile;+ entry.name = result[i].name;+ entry.fullPath = result[i].fullPath;+ entry.filesystem = new (require('./FileSystem'))(result[i].filesystemName);+ entry.nativeURL = result[i].nativeURL;+ retVal.push(entry);+ }+ reader.hasReadEntries = true;+ successCallback(retVal);+ };+ var fail = typeof errorCallback !== 'function' ? null : function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'readEntries', [this.localURL]);+};++module.exports = DirectoryReader;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Entry.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Entry.jsnew file mode 100644index 000000000..b296d999e--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Entry.js@@ -0,0 +1,263 @@+cordova.define("cordova-plugin-file.Entry", function(require, exports, module) {+/*+ *+ * 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 argscheck = require('cordova/argscheck');+var exec = require('cordova/exec');+var FileError = require('./FileError');+var Metadata = require('./Metadata');++/**+ * Represents a file or directory on the local file system.+ *+ * @param isFile+ * {boolean} true if Entry is a file (readonly)+ * @param isDirectory+ * {boolean} true if Entry is a directory (readonly)+ * @param name+ * {DOMString} name of the file or directory, excluding the path+ * leading to it (readonly)+ * @param fullPath+ * {DOMString} the absolute full path to the file or directory+ * (readonly)+ * @param fileSystem+ * {FileSystem} the filesystem on which this entry resides+ * (readonly)+ * @param nativeURL+ * {DOMString} an alternate URL which can be used by native+ * webview controls, for example media players.+ * (optional, readonly)+ */+function Entry (isFile, isDirectory, name, fullPath, fileSystem, nativeURL) {+ this.isFile = !!isFile;+ this.isDirectory = !!isDirectory;+ this.name = name || '';+ this.fullPath = fullPath || '';+ this.filesystem = fileSystem || null;+ this.nativeURL = nativeURL || null;+}++/**+ * Look up the metadata of the entry.+ *+ * @param successCallback+ * {Function} is called with a Metadata object+ * @param errorCallback+ * {Function} is called with a FileError+ */+Entry.prototype.getMetadata = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);+ var success = successCallback && function (entryMetadata) {+ var metadata = new Metadata({+ size: entryMetadata.size,+ modificationTime: entryMetadata.lastModifiedDate+ });+ successCallback(metadata);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(success, fail, 'File', 'getFileMetadata', [this.toInternalURL()]);+};++/**+ * Set the metadata of the entry.+ *+ * @param successCallback+ * {Function} is called with a Metadata object+ * @param errorCallback+ * {Function} is called with a FileError+ * @param metadataObject+ * {Object} keys and values to set+ */+Entry.prototype.setMetadata = function (successCallback, errorCallback, metadataObject) {+ argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);+ exec(successCallback, errorCallback, 'File', 'setMetadata', [this.toInternalURL(), metadataObject]);+};++/**+ * Move a file or directory to a new location.+ *+ * @param parent+ * {DirectoryEntry} the directory to which to move this entry+ * @param newName+ * {DOMString} new name of the entry, defaults to the current name+ * @param successCallback+ * {Function} called with the new DirectoryEntry object+ * @param errorCallback+ * {Function} called with a FileError+ */+Entry.prototype.moveTo = function (parent, newName, successCallback, errorCallback) {+ argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ var srcURL = this.toInternalURL();+ // entry name+ var name = newName || this.name;+ var success = function (entry) {+ if (entry) {+ if (successCallback) {+ // create appropriate Entry object+ var newFSName = entry.filesystemName || (entry.filesystem && entry.filesystem.name);+ var fs = newFSName ? new FileSystem(newFSName, { name: '', fullPath: '/' }) : new FileSystem(parent.filesystem.name, { name: '', fullPath: '/' }); // eslint-disable-line no-undef+ var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('cordova-plugin-file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL);+ successCallback(result);+ }+ } else {+ // no Entry object returned+ if (fail) {+ fail(FileError.NOT_FOUND_ERR);+ }+ }+ };++ // copy+ exec(success, fail, 'File', 'moveTo', [srcURL, parent.toInternalURL(), name]);+};++/**+ * Copy a directory to a different location.+ *+ * @param parent+ * {DirectoryEntry} the directory to which to copy the entry+ * @param newName+ * {DOMString} new name of the entry, defaults to the current name+ * @param successCallback+ * {Function} called with the new Entry object+ * @param errorCallback+ * {Function} called with a FileError+ */+Entry.prototype.copyTo = function (parent, newName, successCallback, errorCallback) {+ argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ var srcURL = this.toInternalURL();+ // entry name+ var name = newName || this.name;+ // success callback+ var success = function (entry) {+ if (entry) {+ if (successCallback) {+ // create appropriate Entry object+ var newFSName = entry.filesystemName || (entry.filesystem && entry.filesystem.name);+ var fs = newFSName ? new FileSystem(newFSName, { name: '', fullPath: '/' }) : new FileSystem(parent.filesystem.name, { name: '', fullPath: '/' }); // eslint-disable-line no-undef+ var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('cordova-plugin-file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL);+ successCallback(result);+ }+ } else {+ // no Entry object returned+ if (fail) {+ fail(FileError.NOT_FOUND_ERR);+ }+ }+ };++ // copy+ exec(success, fail, 'File', 'copyTo', [srcURL, parent.toInternalURL(), name]);+};++/**+ * Return a URL that can be passed across the bridge to identify this entry.+ */+Entry.prototype.toInternalURL = function () {+ if (this.filesystem && this.filesystem.__format__) {+ return this.filesystem.__format__(this.fullPath, this.nativeURL);+ }+};++/**+ * Return a URL that can be used to identify this entry.+ * Use a URL that can be used to as the src attribute of a <video> or+ * <audio> tag. If that is not possible, construct a cdvfile:// URL.+ */+Entry.prototype.toURL = function () {+ if (this.nativeURL) {+ return this.nativeURL;+ }+ // fullPath attribute may contain the full URL in the case that+ // toInternalURL fails.+ return this.toInternalURL() || 'file://localhost' + this.fullPath;+};++/**+ * Backwards-compatibility: In v1.0.0 - 1.0.2, .toURL would only return a+ * cdvfile:// URL, and this method was necessary to obtain URLs usable by the+ * webview.+ * See CB-6051, CB-6106, CB-6117, CB-6152, CB-6199, CB-6201, CB-6243, CB-6249,+ * and CB-6300.+ */+Entry.prototype.toNativeURL = function () {+ console.log("DEPRECATED: Update your code to use 'toURL'");+ return this.toURL();+};++/**+ * Returns a URI that can be used to identify this entry.+ *+ * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.+ * @return uri+ */+Entry.prototype.toURI = function (mimeType) {+ console.log("DEPRECATED: Update your code to use 'toURL'");+ return this.toURL();+};++/**+ * Remove a file or directory. It is an error to attempt to delete a+ * directory that is not empty. It is an error to attempt to delete a+ * root directory of a file system.+ *+ * @param successCallback {Function} called with no parameters+ * @param errorCallback {Function} called with a FileError+ */+Entry.prototype.remove = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'Entry.remove', arguments);+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(successCallback, fail, 'File', 'remove', [this.toInternalURL()]);+};++/**+ * Look up the parent DirectoryEntry of this entry.+ *+ * @param successCallback {Function} called with the parent DirectoryEntry object+ * @param errorCallback {Function} called with a FileError+ */+Entry.prototype.getParent = function (successCallback, errorCallback) {+ argscheck.checkArgs('FF', 'Entry.getParent', arguments);+ var fs = this.filesystem;+ var win = successCallback && function (result) {+ var DirectoryEntry = require('./DirectoryEntry');+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);+ successCallback(entry);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getParent', [this.toInternalURL()]);+};++module.exports = Entry;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/File.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/File.jsnew file mode 100644index 000000000..c77178653--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/File.js@@ -0,0 +1,81 @@+cordova.define("cordova-plugin-file.File", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Constructor.+ * name {DOMString} name of the file, without path information+ * fullPath {DOMString} the full path of the file, including the name+ * type {DOMString} mime type+ * lastModifiedDate {Date} last modified date+ * size {Number} size of the file in bytes+ */++var File = function (name, localURL, type, lastModifiedDate, size) {+ this.name = name || '';+ this.localURL = localURL || null;+ this.type = type || null;+ this.lastModified = lastModifiedDate || null;+ // For backwards compatibility, store the timestamp in lastModifiedDate as well+ this.lastModifiedDate = lastModifiedDate || null;+ this.size = size || 0;++ // These store the absolute start and end for slicing the file.+ this.start = 0;+ this.end = this.size;+};++/**+ * Returns a "slice" of the file. Since Cordova Files don't contain the actual+ * content, this really returns a File with adjusted start and end.+ * Slices of slices are supported.+ * start {Number} The index at which to start the slice (inclusive).+ * end {Number} The index at which to end the slice (exclusive).+ */+File.prototype.slice = function (start, end) {+ var size = this.end - this.start;+ var newStart = 0;+ var newEnd = size;+ if (arguments.length) {+ if (start < 0) {+ newStart = Math.max(size + start, 0);+ } else {+ newStart = Math.min(size, start);+ }+ }++ if (arguments.length >= 2) {+ if (end < 0) {+ newEnd = Math.max(size + end, 0);+ } else {+ newEnd = Math.min(end, size);+ }+ }++ var newFile = new File(this.name, this.localURL, this.type, this.lastModified, this.size);+ newFile.start = this.start + newStart;+ newFile.end = this.start + newEnd;+ return newFile;+};++module.exports = File;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileEntry.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileEntry.jsnew file mode 100644index 000000000..6651b5542--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileEntry.js@@ -0,0 +1,95 @@+cordova.define("cordova-plugin-file.FileEntry", function(require, exports, module) {+/*+ *+ * 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 utils = require('cordova/utils');+var exec = require('cordova/exec');+var Entry = require('./Entry');+var FileWriter = require('./FileWriter');+var File = require('./File');+var FileError = require('./FileError');++/**+ * An interface representing a file on the file system.+ *+ * {boolean} isFile always true (readonly)+ * {boolean} isDirectory always false (readonly)+ * {DOMString} name of the file, excluding the path leading to it (readonly)+ * {DOMString} fullPath the absolute full path to the file (readonly)+ * {FileSystem} filesystem on which the file resides (readonly)+ */+var FileEntry = function (name, fullPath, fileSystem, nativeURL) {+ // remove trailing slash if it is present+ if (fullPath && /\/$/.test(fullPath)) {+ fullPath = fullPath.substring(0, fullPath.length - 1);+ }+ if (nativeURL && /\/$/.test(nativeURL)) {+ nativeURL = nativeURL.substring(0, nativeURL.length - 1);+ }++ FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);+};++utils.extend(FileEntry, Entry);++/**+ * Creates a new FileWriter associated with the file that this FileEntry represents.+ *+ * @param {Function} successCallback is called with the new FileWriter+ * @param {Function} errorCallback is called with a FileError+ */+FileEntry.prototype.createWriter = function (successCallback, errorCallback) {+ this.file(function (filePointer) {+ var writer = new FileWriter(filePointer);++ if (writer.localURL === null || writer.localURL === '') {+ if (errorCallback) {+ errorCallback(new FileError(FileError.INVALID_STATE_ERR));+ }+ } else {+ if (successCallback) {+ successCallback(writer);+ }+ }+ }, errorCallback);+};++/**+ * Returns a File that represents the current state of the file that this FileEntry represents.+ *+ * @param {Function} successCallback is called with the new File object+ * @param {Function} errorCallback is called with a FileError+ */+FileEntry.prototype.file = function (successCallback, errorCallback) {+ var localURL = this.toInternalURL();+ var win = successCallback && function (f) {+ var file = new File(f.name, localURL, f.type, f.lastModifiedDate, f.size);+ successCallback(file);+ };+ var fail = errorCallback && function (code) {+ errorCallback(new FileError(code));+ };+ exec(win, fail, 'File', 'getFileMetadata', [localURL]);+};++module.exports = FileEntry;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileError.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileError.jsnew file mode 100644index 000000000..f378c3874--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileError.js@@ -0,0 +1,49 @@+cordova.define("cordova-plugin-file.FileError", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * FileError+ */+function FileError (error) {+ this.code = error || null;+}++// File error codes+// Found in DOMException+FileError.NOT_FOUND_ERR = 1;+FileError.SECURITY_ERR = 2;+FileError.ABORT_ERR = 3;++// Added by File API specification+FileError.NOT_READABLE_ERR = 4;+FileError.ENCODING_ERR = 5;+FileError.NO_MODIFICATION_ALLOWED_ERR = 6;+FileError.INVALID_STATE_ERR = 7;+FileError.SYNTAX_ERR = 8;+FileError.INVALID_MODIFICATION_ERR = 9;+FileError.QUOTA_EXCEEDED_ERR = 10;+FileError.TYPE_MISMATCH_ERR = 11;+FileError.PATH_EXISTS_ERR = 12;++module.exports = FileError;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileReader.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileReader.jsnew file mode 100644index 000000000..5c030913b--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileReader.js@@ -0,0 +1,301 @@+cordova.define("cordova-plugin-file.FileReader", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var modulemapper = require('cordova/modulemapper');+var utils = require('cordova/utils');+var FileError = require('./FileError');+var ProgressEvent = require('./ProgressEvent');+var origFileReader = modulemapper.getOriginalSymbol(window, 'FileReader');++/**+ * This class reads the mobile device file system.+ *+ * For Android:+ * The root directory is the root of the file system.+ * To read from the SD card, the file name is "sdcard/my_file.txt"+ * @constructor+ */+var FileReader = function () {+ this._readyState = 0;+ this._error = null;+ this._result = null;+ this._progress = null;+ this._localURL = '';+ this._realReader = origFileReader ? new origFileReader() : {}; // eslint-disable-line new-cap+};++/**+ * Defines the maximum size to read at a time via the native API. The default value is a compromise between+ * minimizing the overhead of many exec() calls while still reporting progress frequently enough for large files.+ * (Note attempts to allocate more than a few MB of contiguous memory on the native side are likely to cause+ * OOM exceptions, while the JS engine seems to have fewer problems managing large strings or ArrayBuffers.)+ */+FileReader.READ_CHUNK_SIZE = 256 * 1024;++// States+FileReader.EMPTY = 0;+FileReader.LOADING = 1;+FileReader.DONE = 2;++utils.defineGetter(FileReader.prototype, 'readyState', function () {+ return this._localURL ? this._readyState : this._realReader.readyState;+});++utils.defineGetter(FileReader.prototype, 'error', function () {+ return this._localURL ? this._error : this._realReader.error;+});++utils.defineGetter(FileReader.prototype, 'result', function () {+ return this._localURL ? this._result : this._realReader.result;+});++function defineEvent (eventName) {+ utils.defineGetterSetter(FileReader.prototype, eventName, function () {+ return this._realReader[eventName] || null;+ }, function (value) {+ this._realReader[eventName] = value;+ });+}+defineEvent('onloadstart'); // When the read starts.+defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)+defineEvent('onload'); // When the read has successfully completed.+defineEvent('onerror'); // When the read has failed (see errors).+defineEvent('onloadend'); // When the request has completed (either in success or failure).+defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.++function initRead (reader, file) {+ // Already loading something+ if (reader.readyState === FileReader.LOADING) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ reader._result = null;+ reader._error = null;+ reader._progress = 0;+ reader._readyState = FileReader.LOADING;++ if (typeof file.localURL === 'string') {+ reader._localURL = file.localURL;+ } else {+ reader._localURL = '';+ return true;+ }++ if (reader.onloadstart) {+ reader.onloadstart(new ProgressEvent('loadstart', {target: reader}));+ }+}++/**+ * Callback used by the following read* functions to handle incremental or final success.+ * Must be bound to the FileReader's this along with all but the last parameter,+ * e.g. readSuccessCallback.bind(this, "readAsText", "UTF-8", offset, totalSize, accumulate)+ * @param readType The name of the read function to call.+ * @param encoding Text encoding, or null if this is not a text type read.+ * @param offset Starting offset of the read.+ * @param totalSize Total number of bytes or chars to read.+ * @param accumulate A function that takes the callback result and accumulates it in this._result.+ * @param r Callback result returned by the last read exec() call, or null to begin reading.+ */+function readSuccessCallback (readType, encoding, offset, totalSize, accumulate, r) {+ if (this._readyState === FileReader.DONE) {+ return;+ }++ var CHUNK_SIZE = FileReader.READ_CHUNK_SIZE;+ if (readType === 'readAsDataURL') {+ // Windows proxy does not support reading file slices as Data URLs+ // so read the whole file at once.+ CHUNK_SIZE = cordova.platformId === 'windows' ? totalSize : // eslint-disable-line no-undef+ // Calculate new chunk size for data URLs to be multiply of 3+ // Otherwise concatenated base64 chunks won't be valid base64 data+ FileReader.READ_CHUNK_SIZE - (FileReader.READ_CHUNK_SIZE % 3) + 3;+ }++ if (typeof r !== 'undefined') {+ accumulate(r);+ this._progress = Math.min(this._progress + CHUNK_SIZE, totalSize);++ if (typeof this.onprogress === 'function') {+ this.onprogress(new ProgressEvent('progress', {loaded: this._progress, total: totalSize}));+ }+ }++ if (typeof r === 'undefined' || this._progress < totalSize) {+ var execArgs = [+ this._localURL,+ offset + this._progress,+ offset + this._progress + Math.min(totalSize - this._progress, CHUNK_SIZE)];+ if (encoding) {+ execArgs.splice(1, 0, encoding);+ }+ exec(+ readSuccessCallback.bind(this, readType, encoding, offset, totalSize, accumulate),+ readFailureCallback.bind(this),+ 'File', readType, execArgs);+ } else {+ this._readyState = FileReader.DONE;++ if (typeof this.onload === 'function') {+ this.onload(new ProgressEvent('load', {target: this}));+ }++ if (typeof this.onloadend === 'function') {+ this.onloadend(new ProgressEvent('loadend', {target: this}));+ }+ }+}++/**+ * Callback used by the following read* functions to handle errors.+ * Must be bound to the FileReader's this, e.g. readFailureCallback.bind(this)+ */+function readFailureCallback (e) {+ if (this._readyState === FileReader.DONE) {+ return;+ }++ this._readyState = FileReader.DONE;+ this._result = null;+ this._error = new FileError(e);++ if (typeof this.onerror === 'function') {+ this.onerror(new ProgressEvent('error', {target: this}));+ }++ if (typeof this.onloadend === 'function') {+ this.onloadend(new ProgressEvent('loadend', {target: this}));+ }+}++/**+ * Abort reading file.+ */+FileReader.prototype.abort = function () {+ if (origFileReader && !this._localURL) {+ return this._realReader.abort();+ }+ this._result = null;++ if (this._readyState === FileReader.DONE || this._readyState === FileReader.EMPTY) {+ return;+ }++ this._readyState = FileReader.DONE;++ // If abort callback+ if (typeof this.onabort === 'function') {+ this.onabort(new ProgressEvent('abort', {target: this}));+ }+ // If load end callback+ if (typeof this.onloadend === 'function') {+ this.onloadend(new ProgressEvent('loadend', {target: this}));+ }+};++/**+ * Read text file.+ *+ * @param file {File} File object containing file properties+ * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)+ */+FileReader.prototype.readAsText = function (file, encoding) {+ if (initRead(this, file)) {+ return this._realReader.readAsText(file, encoding);+ }++ // Default encoding is UTF-8+ var enc = encoding || 'UTF-8';++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsText', enc, file.start, totalSize, function (r) {+ if (this._progress === 0) {+ this._result = '';+ }+ this._result += r;+ }.bind(this));+};++/**+ * Read file and return data as a base64 encoded data url.+ * A data url is of the form:+ * data:[<mediatype>][;base64],<data>+ *+ * @param file {File} File object containing file properties+ */+FileReader.prototype.readAsDataURL = function (file) {+ if (initRead(this, file)) {+ return this._realReader.readAsDataURL(file);+ }++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsDataURL', null, file.start, totalSize, function (r) {+ var commaIndex = r.indexOf(',');+ if (this._progress === 0) {+ this._result = r;+ } else {+ this._result += r.substring(commaIndex + 1);+ }+ }.bind(this));+};++/**+ * Read file and return data as a binary data.+ *+ * @param file {File} File object containing file properties+ */+FileReader.prototype.readAsBinaryString = function (file) {+ if (initRead(this, file)) {+ return this._realReader.readAsBinaryString(file);+ }++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsBinaryString', null, file.start, totalSize, function (r) {+ if (this._progress === 0) {+ this._result = '';+ }+ this._result += r;+ }.bind(this));+};++/**+ * Read file and return data as a binary data.+ *+ * @param file {File} File object containing file properties+ */+FileReader.prototype.readAsArrayBuffer = function (file) {+ if (initRead(this, file)) {+ return this._realReader.readAsArrayBuffer(file);+ }++ var totalSize = file.end - file.start;+ readSuccessCallback.bind(this)('readAsArrayBuffer', null, file.start, totalSize, function (r) {+ var resultArray = (this._progress === 0 ? new Uint8Array(totalSize) : new Uint8Array(this._result));+ resultArray.set(new Uint8Array(r), this._progress);+ this._result = resultArray.buffer;+ }.bind(this));+};++module.exports = FileReader;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileSystem.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileSystem.jsnew file mode 100644index 000000000..ad9ea7859--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileSystem.js@@ -0,0 +1,58 @@+cordova.define("cordova-plugin-file.FileSystem", function(require, exports, module) {+/*+ *+ * 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 DirectoryEntry = require('./DirectoryEntry');++/**+ * An interface representing a file system+ *+ * @constructor+ * {DOMString} name the unique name of the file system (readonly)+ * {DirectoryEntry} root directory of the file system (readonly)+ */+var FileSystem = function (name, root) {+ this.name = name;+ if (root) {+ this.root = new DirectoryEntry(root.name, root.fullPath, this, root.nativeURL);+ } else {+ this.root = new DirectoryEntry(this.name, '/', this);+ }+};++FileSystem.prototype.__format__ = function (fullPath, nativeUrl) {+ return fullPath;+};++FileSystem.prototype.toJSON = function () {+ return '<FileSystem: ' + this.name + '>';+};++// Use instead of encodeURI() when encoding just the path part of a URI rather than an entire URI.+FileSystem.encodeURIPath = function (path) {+ // Because # is a valid filename character, it must be encoded to prevent part of the+ // path from being parsed as a URI fragment.+ return encodeURI(path).replace(/#/g, '%23');+};++module.exports = FileSystem;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileUploadOptions.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileUploadOptions.jsnew file mode 100644index 000000000..6acd09334--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileUploadOptions.js@@ -0,0 +1,44 @@+cordova.define("cordova-plugin-file.FileUploadOptions", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Options to customize the HTTP request used to upload files.+ * @constructor+ * @param fileKey {String} Name of file request parameter.+ * @param fileName {String} Filename to be used by the server. Defaults to image.jpg.+ * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.+ * @param params {Object} Object with key: value params to send to the server.+ * @param headers {Object} Keys are header names, values are header values. Multiple+ * headers of the same name are not supported.+ */+var FileUploadOptions = function (fileKey, fileName, mimeType, params, headers, httpMethod) {+ this.fileKey = fileKey || null;+ this.fileName = fileName || null;+ this.mimeType = mimeType || null;+ this.params = params || null;+ this.headers = headers || null;+ this.httpMethod = httpMethod || null;+};++module.exports = FileUploadOptions;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileUploadResult.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileUploadResult.jsnew file mode 100644index 000000000..e3c3a7431--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileUploadResult.js@@ -0,0 +1,33 @@+cordova.define("cordova-plugin-file.FileUploadResult", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * FileUploadResult+ * @constructor+ */+module.exports = function FileUploadResult (size, code, content) {+ this.bytesSent = size;+ this.responseCode = code;+ this.response = content;+};++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileWriter.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileWriter.jsnew file mode 100644index 000000000..c3e856219--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/FileWriter.js@@ -0,0 +1,328 @@+cordova.define("cordova-plugin-file.FileWriter", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var FileError = require('./FileError');+var FileReader = require('./FileReader');+var ProgressEvent = require('./ProgressEvent');++/**+ * This class writes to the mobile device file system.+ *+ * For Android:+ * The root directory is the root of the file system.+ * To write to the SD card, the file name is "sdcard/my_file.txt"+ *+ * @constructor+ * @param file {File} File object containing file properties+ * @param append if true write to the end of the file, otherwise overwrite the file+ */+var FileWriter = function (file) {+ this.fileName = '';+ this.length = 0;+ if (file) {+ this.localURL = file.localURL || file;+ this.length = file.size || 0;+ }+ // default is to write at the beginning of the file+ this.position = 0;++ this.readyState = 0; // EMPTY++ this.result = null;++ // Error+ this.error = null;++ // Event handlers+ this.onwritestart = null; // When writing starts+ this.onprogress = null; // While writing the file, and reporting partial file data+ this.onwrite = null; // When the write has successfully completed.+ this.onwriteend = null; // When the request has completed (either in success or failure).+ this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.+ this.onerror = null; // When the write has failed (see errors).+};++// States+FileWriter.INIT = 0;+FileWriter.WRITING = 1;+FileWriter.DONE = 2;++/**+ * Abort writing file.+ */+FileWriter.prototype.abort = function () {+ // check for invalid state+ if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ // set error+ this.error = new FileError(FileError.ABORT_ERR);++ this.readyState = FileWriter.DONE;++ // If abort callback+ if (typeof this.onabort === 'function') {+ this.onabort(new ProgressEvent('abort', {'target': this}));+ }++ // If write end callback+ if (typeof this.onwriteend === 'function') {+ this.onwriteend(new ProgressEvent('writeend', {'target': this}));+ }+};++/**+ * Writes data to the file+ *+ * @param data text or blob to be written+ * @param isPendingBlobReadResult {Boolean} true if the data is the pending blob read operation result+ */+FileWriter.prototype.write = function (data, isPendingBlobReadResult) {++ var that = this;+ var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined');+ /* eslint-disable no-undef */+ var isProxySupportBlobNatively = (cordova.platformId === 'windows8' || cordova.platformId === 'windows');+ var isBinary;++ // Check to see if the incoming data is a blob+ if (data instanceof File || (!isProxySupportBlobNatively && supportsBinary && data instanceof Blob)) {+ var fileReader = new FileReader();+ /* eslint-enable no-undef */+ fileReader.onload = function () {+ // Call this method again, with the arraybuffer as argument+ FileWriter.prototype.write.call(that, this.result, true /* isPendingBlobReadResult */);+ };+ fileReader.onerror = function () {+ // DONE state+ that.readyState = FileWriter.DONE;++ // Save error+ that.error = this.error;++ // If onerror callback+ if (typeof that.onerror === 'function') {+ that.onerror(new ProgressEvent('error', {'target': that}));+ }++ // If onwriteend callback+ if (typeof that.onwriteend === 'function') {+ that.onwriteend(new ProgressEvent('writeend', {'target': that}));+ }+ };++ // WRITING state+ this.readyState = FileWriter.WRITING;++ if (supportsBinary) {+ fileReader.readAsArrayBuffer(data);+ } else {+ fileReader.readAsText(data);+ }+ return;+ }++ // Mark data type for safer transport over the binary bridge+ isBinary = supportsBinary && (data instanceof ArrayBuffer);+ if (isBinary && cordova.platformId === 'windowsphone') { // eslint-disable-line no-undef+ // create a plain array, using the keys from the Uint8Array view so that we can serialize it+ data = Array.apply(null, new Uint8Array(data));+ }++ // Throw an exception if we are already writing a file+ if (this.readyState === FileWriter.WRITING && !isPendingBlobReadResult) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ // WRITING state+ this.readyState = FileWriter.WRITING;++ var me = this;++ // If onwritestart callback+ if (typeof me.onwritestart === 'function') {+ me.onwritestart(new ProgressEvent('writestart', {'target': me}));+ }++ // Write file+ exec(+ // Success callback+ function (r) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // position always increases by bytes written because file would be extended+ me.position += r;+ // The length of the file is now where we are done writing.++ me.length = me.position;++ // DONE state+ me.readyState = FileWriter.DONE;++ // If onwrite callback+ if (typeof me.onwrite === 'function') {+ me.onwrite(new ProgressEvent('write', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ },+ // Error callback+ function (e) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // DONE state+ me.readyState = FileWriter.DONE;++ // Save error+ me.error = new FileError(e);++ // If onerror callback+ if (typeof me.onerror === 'function') {+ me.onerror(new ProgressEvent('error', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ }, 'File', 'write', [this.localURL, data, this.position, isBinary]);+};++/**+ * Moves the file pointer to the location specified.+ *+ * If the offset is a negative number the position of the file+ * pointer is rewound. If the offset is greater than the file+ * size the position is set to the end of the file.+ *+ * @param offset is the location to move the file pointer to.+ */+FileWriter.prototype.seek = function (offset) {+ // Throw an exception if we are already writing a file+ if (this.readyState === FileWriter.WRITING) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ if (!offset && offset !== 0) {+ return;+ }++ // See back from end of file.+ if (offset < 0) {+ this.position = Math.max(offset + this.length, 0);+ // Offset is bigger than file size so set position+ // to the end of the file.+ } else if (offset > this.length) {+ this.position = this.length;+ // Offset is between 0 and file size so set the position+ // to start writing.+ } else {+ this.position = offset;+ }+};++/**+ * Truncates the file to the size specified.+ *+ * @param size to chop the file at.+ */+FileWriter.prototype.truncate = function (size) {+ // Throw an exception if we are already writing a file+ if (this.readyState === FileWriter.WRITING) {+ throw new FileError(FileError.INVALID_STATE_ERR);+ }++ // WRITING state+ this.readyState = FileWriter.WRITING;++ var me = this;++ // If onwritestart callback+ if (typeof me.onwritestart === 'function') {+ me.onwritestart(new ProgressEvent('writestart', {'target': this}));+ }++ // Write file+ exec(+ // Success callback+ function (r) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // DONE state+ me.readyState = FileWriter.DONE;++ // Update the length of the file+ me.length = r;+ me.position = Math.min(me.position, r);++ // If onwrite callback+ if (typeof me.onwrite === 'function') {+ me.onwrite(new ProgressEvent('write', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ },+ // Error callback+ function (e) {+ // If DONE (cancelled), then don't do anything+ if (me.readyState === FileWriter.DONE) {+ return;+ }++ // DONE state+ me.readyState = FileWriter.DONE;++ // Save error+ me.error = new FileError(e);++ // If onerror callback+ if (typeof me.onerror === 'function') {+ me.onerror(new ProgressEvent('error', {'target': me}));+ }++ // If onwriteend callback+ if (typeof me.onwriteend === 'function') {+ me.onwriteend(new ProgressEvent('writeend', {'target': me}));+ }+ }, 'File', 'truncate', [this.localURL, size]);+};++module.exports = FileWriter;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Flags.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Flags.jsnew file mode 100644index 000000000..cdb12bb73--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Flags.js@@ -0,0 +1,39 @@+cordova.define("cordova-plugin-file.Flags", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Supplies arguments to methods that lookup or create files and directories.+ *+ * @param create+ * {boolean} file or directory if it doesn't exist+ * @param exclusive+ * {boolean} used with create; if true the command will fail if+ * target path exists+ */+function Flags (create, exclusive) {+ this.create = create || false;+ this.exclusive = exclusive || false;+}++module.exports = Flags;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/LocalFileSystem.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/LocalFileSystem.jsnew file mode 100644index 000000000..4ce684812--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/LocalFileSystem.js@@ -0,0 +1,26 @@+cordova.define("cordova-plugin-file.LocalFileSystem", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++exports.TEMPORARY = 0;+exports.PERSISTENT = 1;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Metadata.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Metadata.jsnew file mode 100644index 000000000..22366e167--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/Metadata.js@@ -0,0 +1,43 @@+cordova.define("cordova-plugin-file.Metadata", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++/**+ * Information about the state of the file or directory+ *+ * {Date} modificationTime (readonly)+ */+var Metadata = function (metadata) {+ if (typeof metadata === 'object') {+ this.modificationTime = new Date(metadata.modificationTime);+ this.size = metadata.size || 0;+ } else if (typeof metadata === 'undefined') {+ this.modificationTime = null;+ this.size = 0;+ } else {+ /* Backwards compatiblity with platforms that only return a timestamp */+ this.modificationTime = new Date(metadata);+ }+};++module.exports = Metadata;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/ProgressEvent.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/ProgressEvent.jsnew file mode 100644index 000000000..cbecdb12b--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/ProgressEvent.js@@ -0,0 +1,70 @@+cordova.define("cordova-plugin-file.ProgressEvent", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++// If ProgressEvent exists in global context, use it already, otherwise use our own polyfill+// Feature test: See if we can instantiate a native ProgressEvent;+// if so, use that approach,+// otherwise fill-in with our own implementation.+//+// NOTE: right now we always fill in with our own. Down the road would be nice if we can use whatever is native in the webview.+var ProgressEvent = (function () {+ /*+ var createEvent = function(data) {+ var event = document.createEvent('Events');+ event.initEvent('ProgressEvent', false, false);+ if (data) {+ for (var i in data) {+ if (data.hasOwnProperty(i)) {+ event[i] = data[i];+ }+ }+ if (data.target) {+ // TODO: cannot call <some_custom_object>.dispatchEvent+ // need to first figure out how to implement EventTarget+ }+ }+ return event;+ };+ try {+ var ev = createEvent({type:"abort",target:document});+ return function ProgressEvent(type, data) {+ data.type = type;+ return createEvent(data);+ };+ } catch(e){+ */+ return function ProgressEvent (type, dict) {+ this.type = type;+ this.bubbles = false;+ this.cancelBubble = false;+ this.cancelable = false;+ this.lengthComputable = false;+ this.loaded = dict && dict.loaded ? dict.loaded : 0;+ this.total = dict && dict.total ? dict.total : 0;+ this.target = dict && dict.target ? dict.target : null;+ };+ // }+})();++module.exports = ProgressEvent;++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/browser/isChrome.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/browser/isChrome.jsnew file mode 100644index 000000000..90450d862--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/browser/isChrome.js@@ -0,0 +1,29 @@+cordova.define("cordova-plugin-file.isChrome", function(require, exports, module) {+/*+ *+ * 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.+ *+ */++module.exports = function () {+ // window.webkitRequestFileSystem and window.webkitResolveLocalFileSystemURL are available only in Chrome and+ // possibly a good flag to indicate that we're running in Chrome+ return window.webkitRequestFileSystem && window.webkitResolveLocalFileSystemURL;+};++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystemPaths.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystemPaths.jsnew file mode 100644index 000000000..4bfc0f629--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystemPaths.js@@ -0,0 +1,65 @@+cordova.define("cordova-plugin-file.fileSystemPaths", function(require, exports, module) {+/*+ *+ * 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 = require('cordova/exec');+var channel = require('cordova/channel');++exports.file = {+ // Read-only directory where the application is installed.+ applicationDirectory: null,+ // Root of app's private writable storage+ applicationStorageDirectory: null,+ // Where to put app-specific data files.+ dataDirectory: null,+ // Cached files that should survive app restarts.+ // Apps should not rely on the OS to delete files in here.+ cacheDirectory: null,+ // Android: the application space on external storage.+ externalApplicationStorageDirectory: null,+ // Android: Where to put app-specific data files on external storage.+ externalDataDirectory: null,+ // Android: the application cache on external storage.+ externalCacheDirectory: null,+ // Android: the external storage (SD card) root.+ externalRootDirectory: null,+ // iOS: Temp directory that the OS can clear at will.+ tempDirectory: null,+ // iOS: Holds app-specific files that should be synced (e.g. to iCloud).+ syncedDataDirectory: null,+ // iOS: Files private to the app, but that are meaningful to other applications (e.g. Office files)+ documentsDirectory: null,+ // BlackBerry10: Files globally available to all apps+ sharedDirectory: null+};++channel.waitForInitialization('onFileSystemPathsReady');+channel.onCordovaReady.subscribe(function () {+ function after (paths) {+ for (var k in paths) {+ exports.file[k] = paths[k];+ }+ channel.initializationComplete('onFileSystemPathsReady');+ }+ exec(after, null, 'File', 'requestAllPaths', []);+});++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystems-roots.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystems-roots.jsnew file mode 100644index 000000000..6e02953e8--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystems-roots.js@@ -0,0 +1,49 @@+cordova.define("cordova-plugin-file.fileSystems-roots", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++// Map of fsName -> FileSystem.+var fsMap = null;+var FileSystem = require('./FileSystem');+var exec = require('cordova/exec');++// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.+require('./fileSystems').getFs = function (name, callback) {+ function success (response) {+ fsMap = {};+ for (var i = 0; i < response.length; ++i) {+ var fsRoot = response[i];+ if (fsRoot) {+ var fs = new FileSystem(fsRoot.filesystemName, fsRoot);+ fsMap[fs.name] = fs;+ }+ }+ callback(fsMap[name]);+ }++ if (fsMap) {+ callback(fsMap[name]);+ } else {+ exec(success, null, 'File', 'requestAllFileSystems', []);+ }+};++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystems.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystems.jsnew file mode 100644index 000000000..e61ceafc8--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/fileSystems.js@@ -0,0 +1,28 @@+cordova.define("cordova-plugin-file.fileSystems", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.+module.exports.getFs = function (name, callback) {+ callback(null);+};++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/ios/FileSystem.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/ios/FileSystem.jsnew file mode 100644index 000000000..551b51545--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/ios/FileSystem.js@@ -0,0 +1,32 @@+cordova.define("cordova-plugin-file.iosFileSystem", function(require, exports, module) {+/*+ *+ * 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.+ *+*/+/* eslint no-undef : 0 */+FILESYSTEM_PROTOCOL = 'cdvfile';++module.exports = {+ __format__: function (fullPath) {+ var path = ('/' + this.name + (fullPath[0] === '/' ? '' : '/') + FileSystem.encodeURIPath(fullPath)).replace('//', '/');+ return FILESYSTEM_PROTOCOL + '://localhost' + path;+ }+};++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/requestFileSystem.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/requestFileSystem.jsnew file mode 100644index 000000000..7f652193c--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/requestFileSystem.js@@ -0,0 +1,84 @@+cordova.define("cordova-plugin-file.requestFileSystem", function(require, exports, module) {+/*+ *+ * 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.+ *+*/++(function () {+ // For browser platform: not all browsers use this file.+ function checkBrowser () {+ if (cordova.platformId === 'browser' && require('./isChrome')()) { // eslint-disable-line no-undef+ module.exports = window.requestFileSystem || window.webkitRequestFileSystem;+ return true;+ }+ return false;+ }+ if (checkBrowser()) {+ return;+ }++ var argscheck = require('cordova/argscheck');+ var FileError = require('./FileError');+ var FileSystem = require('./FileSystem');+ var exec = require('cordova/exec');+ var fileSystems = require('./fileSystems');++ /**+ * Request a file system in which to store application data.+ * @param type local file system type+ * @param size indicates how much storage space, in bytes, the application expects to need+ * @param successCallback invoked with a FileSystem object+ * @param errorCallback invoked if error occurs retrieving file system+ */+ var requestFileSystem = function (type, size, successCallback, errorCallback) {+ argscheck.checkArgs('nnFF', 'requestFileSystem', arguments);+ var fail = function (code) {+ if (errorCallback) {+ errorCallback(new FileError(code));+ }+ };++ if (type < 0) {+ fail(FileError.SYNTAX_ERR);+ } else {+ // if successful, return a FileSystem object+ var success = function (file_system) {+ if (file_system) {+ if (successCallback) {+ fileSystems.getFs(file_system.name, function (fs) {+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)+ if (!fs) {+ fs = new FileSystem(file_system.name, file_system.root);+ }+ successCallback(fs);+ });+ }+ } else {+ // no FileSystem object returned+ fail(FileError.NOT_FOUND_ERR);+ }+ };+ exec(success, fail, 'File', 'requestFileSystem', [type, size]);+ }+ };++ module.exports = requestFileSystem;+})();++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.jsnew file mode 100644index 000000000..73715bc0e--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js@@ -0,0 +1,94 @@+cordova.define("cordova-plugin-file.resolveLocalFileSystemURI", function(require, exports, module) {+/*+ *+ * 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.+ *+*/+(function () {+ // For browser platform: not all browsers use overrided `resolveLocalFileSystemURL`.+ function checkBrowser () {+ if (cordova.platformId === 'browser' && require('./isChrome')()) { // eslint-disable-line no-undef+ module.exports.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;+ return true;+ }+ return false;+ }+ if (checkBrowser()) {+ return;+ }++ var argscheck = require('cordova/argscheck');+ var DirectoryEntry = require('./DirectoryEntry');+ var FileEntry = require('./FileEntry');+ var FileError = require('./FileError');+ var exec = require('cordova/exec');+ var fileSystems = require('./fileSystems');++ /**+ * Look up file system Entry referred to by local URI.+ * @param {DOMString} uri URI referring to a local file or directory+ * @param successCallback invoked with Entry object corresponding to URI+ * @param errorCallback invoked if error occurs retrieving file system entry+ */+ module.exports.resolveLocalFileSystemURL = module.exports.resolveLocalFileSystemURL || function (uri, successCallback, errorCallback) {+ argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments);+ // error callback+ var fail = function (error) {+ if (errorCallback) {+ errorCallback(new FileError(error));+ }+ };+ // sanity check for 'not:valid:filename' or '/not:valid:filename'+ // file.spec.12 window.resolveLocalFileSystemURI should error (ENCODING_ERR) when resolving invalid URI with leading /.+ if (!uri || uri.split(':').length > 2) {+ setTimeout(function () {+ fail(FileError.ENCODING_ERR);+ }, 0);+ return;+ }+ // if successful, return either a file or directory entry+ var success = function (entry) {+ if (entry) {+ if (successCallback) {+ // create appropriate Entry object+ var fsName = entry.filesystemName || (entry.filesystem && entry.filesystem.name) || (entry.filesystem === window.PERSISTENT ? 'persistent' : 'temporary'); // eslint-disable-line no-undef+ fileSystems.getFs(fsName, function (fs) {+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)+ if (!fs) {+ fs = new FileSystem(fsName, {name: '', fullPath: '/'}); // eslint-disable-line no-undef+ }+ var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL);+ successCallback(result);+ });+ }+ } else {+ // no Entry object returned+ fail(FileError.NOT_FOUND_ERR);+ }+ };++ exec(success, fail, 'File', 'resolveLocalFileSystemURI', [uri]);+ };++ module.exports.resolveLocalFileSystemURI = function () {+ console.log('resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.');+ module.exports.resolveLocalFileSystemURL.apply(this, arguments);+ };+})();++});diff --git a/package.json b/package.jsonindex a0f0a6182..7f282fc7c 100644--- a/package.json+++ b/package.json@@ -61,6 +61,8 @@"run-web": "yarn build-web && yarn prepare-web && node scripts/webserver.js","run-android": "yarn build-cordova && cd cordova && cordova run android && cd ..","run-android-dev": "yarn prepare-cordova && yarn build-cordova-dev && cd cordova && cordova run android && cd ..",+ "run-ios-dev": "yarn prepare-cordova && yarn build-cordova-dev && cd cordova && cordova run ios && cd ..",+ "cordova-list-emulators": "cd cordova && cordova run --list --emulator && cd ..","cordova-add-android": "cd cordova && cordova platform add android && cd ..","cordova-create-app": "cordova create ./cordova org.tagspaces.mobile TagSpaces","update-changelog": "git log v3.4.2..HEAD --no-merges --format=%B > CHANGELOG.TXT",